content
stringlengths
7
2.61M
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, with_statement import cuisine from revolver import group def test_revolver_is_just_a_wrapper(): assert group.get == cuisine.group_check assert group.create == cuisine.group_create assert group.ensure == cuisine.group_ensure assert group.user_add == cuisine.group_user_add assert group.user_check == cuisine.group_user_check assert group.user_ensure == cuisine.group_user_ensure
The present invention relates to apparatus and methods for establishing data communication between a multiplicity of spaced locations. More particularly, the present invention relates to systems and apparatus for allowing a plurality of electronic units to establish data transmission and/or reception between those units. Although not necessarily limited thereto, the present invention is useful in establishing multiple bit data communications for discrete but spaced electronic systems, subsystems and the like which require data interfacing. That is, the present invention is useful in establishing parallel data interconnections between multiple data processing units, multiple memory units, the various elements internal to a data processing unit such as are involved in so-called virtual processor systems, multiple control units or any of a wide variety of existing electronic systems and subsystems requiring data exchanges as well as various combinations of the aforementioned units. A remarkably wide variety of systems and subsystems have been developed in the art of electronic data processing and handling. In order for such systems to realize the efficiency and speed of operation potentially available, means for rapidly effecting data exchanges between such units have become increasingly critical. For instance, the relatively self-contained early computers have given way to more sophisticated systems such as multiple processor systems which require access to multiple discrete data storage units. Yet another example of potential multiple data communication paths are in association with the varieties of data communication control units and supervisory elements which must handle data exchanges therewith. Thus, the use of separate hard wired interconnections from each unit to all other units which must exchange data has become prohibitive. One prior art approach to resolving the hard wired data interfacing problem is the use of a single common but multiple wired bus between all units which must effect data exchanges with some means of allowing one of the parallel attached subsystems to transmit or receive data from that common bus. Such systems frequently employ time division multiplexing on the common bus wherein the particular unit is preassigned a specific time slot during which data can be transmitted or received. Yet other arrangements such as selector channels allow a unit to request that it be granted the common bus to the exclusion of the other units with some control circuitry to supervise which unit is allowed access at a given time. As a result, the efficiency of data transmission through the common bus is necessarily reduced since concurrent communications between multiple stations is not possible. Current data busses have the disadvantages that they are expensive and relatively slow. The direct hardwiring of such systems could be implemented through coax or fiber optics but the cost of fabricating such systems is prohibitive where parallel paths are necessary to increase the rate of data transfer. A complex digital system may be viewed as a collection of devices [e.g.: processors, memories, etc.] interconnected by switches. These switches have two significant parameters in speed as to the data transfer rate and in concurrency as to the number of separate conversations among devices which can be supported. Some prior art time division multiplexing systems increase concurrency of the switch by sacrificing speed. They require the various conversations among devices to occur at different times. Despite the disadvantages, time-multiplex bus systems are frequently used as the input-output device switch in existing digital computer systems. Current technology limits the speed of switches to about 10 to the 8th power transfers per second with rapidly increaing difficulty of implementation for speeds above 10 to the 7th power transfers per second. Thus for speeds of 10 to the 7th power transfers per second or greater, time division multiplexing is virtually ruled out as a technique for generating concurrency and a more complex and more expensive switch must be used. A common need for high concurrency switches exists in connection with multiple processor and multiple memory systems. In such applications, several processors may attempt to access data in several memories with only one such communication link being allowed at a given time. A system of N processors communicating with N memories via W-bit word transfers requires a switch of concurrency N to prevent lockout of processors by the switch. If the switch is located at one central location, then it requires N.W wires coming into it with the processors and the same number from the memories. If the switch is distributed throughout the system, there is still a "cut" of the system [a hypothetical plane which separates the system into component parts] which crosses N.W wires. It is predominantly the cost of connecting these wires that makes the price of high concurrency switches unreasonable. Thus there is a continuing need for a more economical way of implementing communication interconnections inexpensively. In considering an optical switch, one approach is to model the optical system after existing systems while attempting to overcome some of the existing system limitations. A fiber system can be used in a similar manner to present systems and cross talk can be expected to be lower and system transfer rate expected to be slightly higher. There are many problems and drawbacks associated with such systems. For instance, introduction of energy into fibers can be difficult. If light emitting diodes (LED) are used, the light is emitted into a wide cone even with a lens on the LED which results in a small fraction of the power actually being introduced into the fiber. Laser diodes could be used as high energy, high directivity sources but they are slower, more expensive and have a shorter life span. Coupling energy from the line for time-multiplex operation presents additional problems. Fiber optic couplers have been built as mentioned above, but the losses incurred by selecting light at each device requires more powerful and usually slower LEDs or more sensitive detectors or both. In addition, the couplers may introduce reflections which could be transferred to improper detectors. The requirement for couplers assumes a time-multiplex system. A high concurrency approach could be used by letting each device have a separate fiber optic line to every other device. This solves some problems, particularly since each LED must illuminate only one detector through the fiber. Hence, low power LEDs and fast detectors could be employed. Unfortunately, the large number of interconnections for high concurrency switches creates even more severe problems for fiber optics than for conductive wires since each light guide must be carefully coupled to its devices. It has been known in the past that light emitting devices and light sensitive devices can be arranged so as to provide communications between units. Although the light coupling elements have been used for electrical isolation between units requiring data exchanges such as in U.S. Pat. No. 3,888,772 by Neuner, such elements have likewise been used for other purposes such as in the switching matrix configuration of U.S. Pat. No. 3,078,373 by Wittenberg. There have been some efforts to employ light coupled systems for data communications between different locations. For instance, U.S. Pat. No. 3,851,167 by Levine shows an in-line receive/transmit repeater for a fiber optic cable transmission system. Other data communication systems have used various forms of optical modulation and demodulation for data communication such as in the systems shown in U.S. Pat. Nos. 3,652,858 by Kinsel and 3,899,430 by Ancker-Johnson, the latter including a laser originated closed light loop between transceiver stations. Another time-division multiplexed optical communication system including a closed loop synchronization arrangement for the optical path at the receiving station is shown in U.S. Pat. No. 3,699,344 by Rutz. Still others have suggested that lens arrangements can be used to select particular receiving detectors from transmitted light beams as in U.S. Pat. Nos. 3,679,904 Weiner and 3,739,173 by Broussaud. In the prior art optical data communication systems, the interfacing requires relatively sophisticated modulation/demodulation apparatus and data conversion devices in order to present the data to the communicating unit requiring it. Further, many such systems suffer from essentially the same disadvantages as hard wired common bus systems since they are effectively time division multiplex dependent. Accordingly, there has been a continuing need for a data interfacing system which requires minimal modification to the existing data processing or handling units demanding the data exchanges and further with minimal apparatus associated with establishing the transmission/reception interface at each location. Still further, there has been a continuing demand for a data communication bus system which allows concurrent data exchanges between various combinations of units while avoiding the necessity for large numbers of hard wired interconnections.
export declare const cisPuzzlePiece: string[];
<reponame>malishav/coap import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('coapMessage') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import coapOption as o import coapUtils as u import coapException as e import coapDefines as d def sortOptions(options): # TODO implement sorting when more options are implemented return options ''' 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Ver| T | TKL | Code | Message ID | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Token (if any, TKL bytes) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options (if any) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1 1 1 1 1 1 1 1| Payload (if any) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ''' def buildMessage(msgtype,token,code,messageId,options=[],payload=[]): assert msgtype in d.TYPE_ALL assert code in d.METHOD_ALL+d.COAP_RC_ALL message = [] # determine token length TKL = None for tokenLen in range(1,8+1): if token < (1<<(8*tokenLen)): TKL = tokenLen break if not TKL: raise ValueError('token {0} too long'.format(token)) # header message += [d.COAP_VERSION<<6 | msgtype<<4 | TKL] message += [code] message += u.int2buf(messageId,2) message += u.int2buf(token,TKL) # options options = sortOptions(options) lastOptionNum = 0 for option in options: assert option.optionNumber>=lastOptionNum message += option.toBytes(lastOptionNum) lastOptionNum = option.optionNumber # payload if payload: message += [d.COAP_PAYLOAD_MARKER] message += payload return message def parseMessage(message): returnVal = {} # header if len(message)<4: raise e.messageFormatError('message to short, {0} bytes: not space for header'.format(len(message))) returnVal['version'] = (message[0]>>6)&0x03 if returnVal['version']!=d.COAP_VERSION: raise e.messageFormatError('invalid CoAP version {0}'.format(returnVal['version'])) returnVal['type'] = (message[0]>>4)&0x03 if returnVal['type'] not in d.TYPE_ALL: raise e.messageFormatError('invalid message type {0}'.format(returnVal['type'])) TKL = message[0]&0x0f if TKL>8: raise e.messageFormatError('TKL too large {0}'.format(TKL)) returnVal['code'] = message[1] returnVal['messageId'] = u.buf2int(message[2:4]) message = message[4:] # token if len(message)<TKL: raise e.messageFormatError('message to short, {0} bytes: not space for token'.format(len(message))) returnVal['token'] = u.buf2int(message[:TKL]) message = message[TKL:] # options returnVal['options'] = [] currentOptionNumber = 0 while True: (option,message) = o.parseOption(message,currentOptionNumber) if not option: break returnVal['options']+= [option] currentOptionNumber = option.optionNumber # payload returnVal['payload'] = message log.debug('parsed message: {0}'.format(returnVal)) return returnVal
Q: Must tangible assets be depreciated or can I take a one-time expense? Let's say my company purchases some tangible/fixed/long-term asset. Am I required to take a prorated depreciation expense each year for the life of the asset? Do I have the option to report the expense as a lump-sum/one-time expense on my income statement? Is it up to me to decide what I want my earnings to look like that year (i.e. lower if I take the one-time expense and higher using a depreciation expense)? Or is all of this somehow dependent on whether I am using GAAP? A: For public US companies listed on an exchange, they must follow SEC guidelines. Thus, their financial statements will be prepared under US GAAP. To answer your question, yes, if the cost is over their capitalization policy amount, it must be capitalized and depreciated. Under GAAP there are several options for depreciation, such as straight line and unit-of-production. The choice is always disclosed in the footnotes of the 10-K. Ideally the company would choose a method that resembles the actual depreciation of the asset most closely so the statements are more reliable.
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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. */ #include <WCDB/pragma.hpp> namespace WCDB { const Pragma Pragma::ApplicationId("application_id"); const Pragma Pragma::AutoVacuum("auto_vacuum"); const Pragma Pragma::AutomaticIndex("automatic_index"); const Pragma Pragma::BusyTimeout("busy_timeout"); const Pragma Pragma::CacheSize("cache_size"); const Pragma Pragma::CacheSpill("cache_spill"); const Pragma Pragma::CaseSensitiveLike("case_sensitive_like"); const Pragma Pragma::CellSizeCheck("cell_size_check"); const Pragma Pragma::CheckpointFullfsync("checkpoint_fullfsync"); const Pragma Pragma::CollationList("collation_list"); const Pragma Pragma::CompileOptions("compile_options"); const Pragma Pragma::CountChanges("count_changes"); const Pragma Pragma::DataStoreDirectory("data_store_directory"); const Pragma Pragma::DataVersion("data_version"); const Pragma Pragma::DatabaseList("database_list"); const Pragma Pragma::DefaultCacheSize("default_cache_size"); const Pragma Pragma::DeferForeignKeys("defer_foreign_keys"); const Pragma Pragma::EmptyResultCallbacks("empty_result_callbacks"); const Pragma Pragma::Encoding("encoding"); const Pragma Pragma::ForeignKeyCheck("foreign_key_check"); const Pragma Pragma::ForeignKeyList("foreign_key_list"); const Pragma Pragma::ForeignKeys("foreign_keys"); const Pragma Pragma::FreelistCount("freelist_count"); const Pragma Pragma::FullColumnNames("full_column_names"); const Pragma Pragma::Fullfsync("fullfsync"); const Pragma Pragma::IgnoreCheckConstraints("ignore_check_constraints"); const Pragma Pragma::IncrementalVacuum("incremental_vacuum"); const Pragma Pragma::IndexInfo("index_info"); const Pragma Pragma::IndexList("index_list"); const Pragma Pragma::IndexXinfo("index_xinfo"); const Pragma Pragma::IntegrityCheck("integrity_check"); const Pragma Pragma::JournalMode("journal_mode"); const Pragma Pragma::JournalSizeLimit("journal_size_limit"); const Pragma Pragma::LegacyFileFormat("legacy_file_format"); const Pragma Pragma::LockingMode("locking_mode"); const Pragma Pragma::MaxPageCount("max_page_count"); const Pragma Pragma::MmapSize("mmap_size"); const Pragma Pragma::PageCount("page_count"); const Pragma Pragma::PageSize("page_size"); const Pragma Pragma::ParserTrace("parser_trace"); const Pragma Pragma::QueryOnly("query_only"); const Pragma Pragma::QuickCheck("quick_check"); const Pragma Pragma::ReadUncommitted("read_uncommitted"); const Pragma Pragma::RecursiveTriggers("recursive_triggers"); const Pragma Pragma::ReverseUnorderedSelects("reverse_unordered_selects"); const Pragma Pragma::SchemaVersion("schema_version"); const Pragma Pragma::SecureDelete("secure_delete"); const Pragma Pragma::ShortColumnNames("short_column_names"); const Pragma Pragma::ShrinkMemory("shrink_memory"); const Pragma Pragma::SoftHeapLimit("soft_heap_limit"); const Pragma Pragma::Stats("stats"); const Pragma Pragma::Synchronous("synchronous"); const Pragma Pragma::TableInfo("table_info"); const Pragma Pragma::TempStore("temp_store"); const Pragma Pragma::TempStoreDirectory("temp_store_directory"); const Pragma Pragma::Threads("threads"); const Pragma Pragma::UserVersion("user_version"); const Pragma Pragma::VdbeAddoptrace("vdbe_addoptrace"); const Pragma Pragma::VdbeDebug("vdbe_debug"); const Pragma Pragma::VdbeListing("vdbe_listing"); const Pragma Pragma::VdbeTrace("vdbe_trace"); const Pragma Pragma::WalAutocheckpoint("wal_autocheckpoint"); const Pragma Pragma::WalCheckpoint("wal_checkpoint"); const Pragma Pragma::WritableSchema("writable_schema"); Pragma::Pragma(const char *name) : Describable(name) { } const std::string &Pragma::getName() const { return m_description; } } //namespace WCDB
<reponame>HEALINGBUDZ/healingbudzandroid<filename>HealingBudz/app/src/main/java/com/codingpixel/healingbudz/Utilities/KeyboardUtils.java package com.codingpixel.healingbudz.Utilities; /** * Created by incubasyss on 15/01/2018. */ import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.inputmethod.InputMethodManager; import java.util.HashMap; /** * Based on the following Stackoverflow answer: * http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android */ @SuppressWarnings("WeakerAccess") public class KeyboardUtils implements ViewTreeObserver.OnGlobalLayoutListener { private final static int MAGIC_NUMBER = 200; private SoftKeyboardToggleListener mCallback; private View mRootView; private Boolean prevValue = null; private float mScreenDensity = 1; private static HashMap<SoftKeyboardToggleListener, KeyboardUtils> sListenerMap = new HashMap<>(); public interface SoftKeyboardToggleListener { void onToggleSoftKeyboard(boolean isVisible); } @Override public void onGlobalLayout() { Rect r = new Rect(); mRootView.getWindowVisibleDisplayFrame(r); int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top); float dp = heightDiff / mScreenDensity; boolean isVisible = dp > MAGIC_NUMBER; if (mCallback != null && (prevValue == null || isVisible != prevValue)) { prevValue = isVisible; mCallback.onToggleSoftKeyboard(isVisible); } } /** * Add a new keyboard listener * * @param act calling activity * @param listener callback */ public static void addKeyboardToggleListener(Activity act, SoftKeyboardToggleListener listener) { removeKeyboardToggleListener(listener); sListenerMap.put(listener, new KeyboardUtils(act, listener)); } /** * Remove a registered listener * * @param listener {@link SoftKeyboardToggleListener} */ public static void removeKeyboardToggleListener(SoftKeyboardToggleListener listener) { if (sListenerMap.containsKey(listener)) { KeyboardUtils k = sListenerMap.get(listener); k.removeListener(); sListenerMap.remove(listener); } } /** * Remove all registered keyboard listeners */ public static void removeAllKeyboardToggleListeners() { for (SoftKeyboardToggleListener l : sListenerMap.keySet()) sListenerMap.get(l).removeListener(); sListenerMap.clear(); } /** * Manually toggle soft keyboard visibility * * @param context calling context */ public static void toggleKeyboardVisibility(Context context) { InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } /** * Force closes the soft keyboard * * @param activeView the view with the keyboard focus */ public static void forceCloseKeyboard(View activeView) { InputMethodManager inputMethodManager = (InputMethodManager) activeView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activeView.getWindowToken(), 0); } private void removeListener() { mCallback = null; mRootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } private KeyboardUtils(Activity act, SoftKeyboardToggleListener listener) { mCallback = listener; mRootView = ((ViewGroup) act.findViewById(android.R.id.content)).getChildAt(0); mRootView.getViewTreeObserver().addOnGlobalLayoutListener(this); mScreenDensity = act.getResources().getDisplayMetrics().density; } }
Improvement of p-type GaAs0.51Sb0.49 metal-oxide-semiconductor interface properties by using ultrathin In0.53Ga0.47As interfacial layers The effects of interfacial In0.53Ga0.47As layers on Al2O3/GaAs0.51Sb0.49 metal-oxide-semiconductor (MOS) structures on InP substrates have systematically been studied. It is found that the interfacial InGaAs layers can reduce Dit values of the Al2O3/GaAsSb MOS interfaces down to 341011cm−2eV−1, which is almost one order of the magnitude lower than in the MOS interfaces without any InGaAs interfacial layers. It is also found that the InGaAs thickness of 1.01.5nm is sufficient to reduce Dit to this low value. In order to obtain these results, the influence of an additional parasitic conductance and capacitance related to the GaAsSb/InP heterointerface needs to be considered, because the C-V characteristics of Al2O3/GaAs0.51Sb0.49/InP MOS capacitors in the accumulation region exhibit strong frequency dispersion, regardless of the InGaAs interfacial layer. We present through simulation of the C-V characteristics using a 2-dimensional device simulator that the correction of this series resistance and capacitance by using an equivalent circuit model can effectively eliminate the influence of the potential barrier at the GaAsSb/InP heterointerface from the experimental C-V ones, allowing us to employ the conventional conductance method for extracting interface trap density (Dit).The effects of interfacial In0.53Ga0.47As layers on Al2O3/GaAs0.51Sb0.49 metal-oxide-semiconductor (MOS) structures on InP substrates have systematically been studied. It is found that the interfacial InGaAs layers can reduce Dit values of the Al2O3/GaAsSb MOS interfaces down to 341011cm−2eV−1, which is almost one order of the magnitude lower than in the MOS interfaces without any InGaAs interfacial layers. It is also found that the InGaAs thickness of 1.01.5nm is sufficient to reduce Dit to this low value. In order to obtain these results, the influence of an additional parasitic conductance and capacitance related to the GaAsSb/InP heterointerface needs to be considered, because the C-V characteristics of Al2O3/GaAs0.51Sb0.49/InP MOS capacitors in the accumulation region exhibit strong frequency dispersion, regardless of the InGaAs interfacial layer. We present through simulation of the C-V characteristics using a 2-dimensional device simulator that the correction of this series resistance and c...
Following a rocky meeting with her strongest Republican critics in the Senate on Tuesday, U.N. Ambassador Susan Rice plans to meet with two more Republican senators on Wednesday. Rice will sit with Sens. Susan Collins of Maine and Bob Corker of Tennessee on Wednesday. Corker is next in line to be ranking member of the Senate Foreign Relations Committee. "She always delivers the party line, the company line, whatever the talking points are," Corker said, according to the Associated Press. "I think most of us hold the secretary of state and secretary of treasury to a whole different level. We understand that they're going to support the administration, but we also want to know that they are independent enough, when administration is off-base, that they are putting pressure. I think that's what worries me most about Rice." Rice has been widely reported as President Obama's top choice for secretary of state, and the president has fiercely defended her amid a firestorm of criticism over her statements explaining the Sept. 11 terrorist attack in Libya. After their meeting with Rice, Republican Sens. John McCain, Lindsey Graham and Kelly Ayotte said they were more disturbed than they were before the meeting. Ayotte said on CBS that she would place a hold on the nomination if Rice were tapped for secretary of state. "We are significantly troubled by many of the answers that we got and some that we didn't get concerning evidence that was overwhelming leading up to the attack on our consulate," McCain said after the morning meeting with Rice. On Tuesday, the White House and several Democrats on the Hill defended Rice against what they said was unfair criticism. Further, Senate Majority Leader Harry Reid, D-Nev., called the criticism "outrageous," saying the real questions that need answering surround how to prevent any further attacks on diplomats abroad. "The personal attacks against Ambassador Rice by certain Republican senators have been outrageous and utterly unmoored from facts and reality," Reid said on Tuesday, according to AP. Following her meeting with the three senators of Tuesday, Rice also sat down with retiring Sen. Joe Lieberman, the chairman of the Senate Homeland Security Committee. If Rice were to be nominated as Secretary of State Hillary Clinton's successor, she would only need five Republicans to reach 60 votes and cloture for the nomination.
from .data import download_data from .data import filter_point_in_polygon from .data import get_data_from_nc from .data import get_data_from_source from .data import get_index from .data import get_profiles_within_polygon from .data import is_inside_the_polygon from .filters import cluster_analysis from .plot import plot_DMQC_vs_RTQC from .plot import plot_filtered_profiles_data from .plot import plot_six_diagrams
<reponame>jnthn/intellij-community class OxfordBug { private int f(int m, int n) throws Exception { int i = 0; while (i < n) { i++; <selection>if (i == m) { n += m; throw new Exception("" + n); }</selection> } return n; } }
Clostridium defficiel in the urogenital tract of males and females. A study of the occurrence of Clostridium difficile in the urogenital tract of males and females revealed higher isolation-rates in patients attending the special (venereal-disease) clinic than in patients attending family-planning and urological clinics. The presence of Cl. difficile in patients with venereal diseases is being investigated to see if the organism is simply an opportunist infecting a urethra disturbed by some antecedent disease, or if it is perhaps a primary cuase of disease.
<reponame>clarkgrg/ts-jsonparse import './lib/string.ext'; import { eTokens, Token } from './lib/tokens'; import { Lexer } from './lib/lexer'; import { ParsingError } from './lib/error'; /** * Parent class for Abstract Syntax Tree */ abstract class AST { public getName(): string { return this.constructor.name; } } /** * jObject - class for Objects; */ class jObject extends AST { public children: jNameValue[] = []; constructor() { super(); } } /** * jArray - class for Arrays */ class jArray extends AST { public children: AST[] = []; constructor() { super(); } } /** * jPrimative - class for number, string, booleans, and null */ class jPrimative extends AST { private token: Token; public value: number | string | boolean | null; constructor(token: Token) { super(); this.token = token; if (token.isTrue()) this.value = true; else if (token.isFalse()) this.value = false; else if (token.isNull()) this.value = null; else this.value = token.value; } } /** * jNameValue - class for name-value pairs */ class jNameValue extends AST { public name: string; public value: jPrimative | jObject | jArray; constructor(name: string, value: jPrimative | jObject | jArray) { super(); this.name = name; this.value = value; } } abstract class Node_Visitor { public visit(node: AST): any { if (node.getName() === 'jPrimative') { return this.visit_jPrimative(node); } else if (node.getName() === 'jNameValue') { return this.visit_jNameValue(node); } else if (node.getName() === 'jObject') { return this.visit_jObject(node); } else if (node.getName() === 'jArray') { return this.visit_jArray(node); } this.error('No visit_method()'); } protected error(msg: string): void { throw new ParsingError(msg); } protected abstract visit_jObject(node: AST): void; protected abstract visit_jArray(node: AST): void; protected abstract visit_jNameValue(node: AST): void; protected abstract visit_jPrimative( node: AST ): number | string | boolean | null; } /** * Create object from AST */ export class JSONBuilder extends Node_Visitor { private tree: AST; constructor(tree: AST) { super(); this.tree = tree; } protected visit_jObject(node: jObject): {} { const obj: Record<string, any> = {}; for (const child of node.children) { obj[child.name] = this.visit(child.value); } return obj; } protected visit_jArray(node: jArray): any[] { const arr = []; for (const child of node.children) { arr.push(this.visit(child)); } return arr; } protected visit_jNameValue(node: jNameValue): void {} protected visit_jPrimative( node: jPrimative ): number | string | boolean | null { return node.value; } public getJSON() { return this.visit(this.tree); } } /** * Parser class */ export class Parser { public current_token: Token | null = null; private lexer: Lexer; constructor(text: string) { this.lexer = new Lexer(text); this.current_token = this.lexer.get_next_token(); return this; } /** * Handle errors * @param msg */ private error(msg: string): void { throw new ParsingError(msg); } /** * compare the current token type with the passed token thype and if they match * then 'eat' the current token and assign the next token to the current_token * otherwise raist and excpetion * @param token_type */ private eat(token_type: eTokens): void { if (this.current_token?.type === token_type) { this.current_token = this.lexer.get_next_token(); } else { this.error('Parser invalid syntax'); } } /** * value : object * | array * | NUMBER * | STRING * | TRUE * | FALSE * | NULL */ private value(): jObject | jArray | jPrimative { const token = this.current_token; if (token?.isBeginObject()) { return this.object(); } if (token?.isBeginArray()) { return this.array(); } if (token?.isNumber()) { this.eat(eTokens.NUMBER); return new jPrimative(token); } if (token?.isString()) { this.eat(eTokens.STRING); return new jPrimative(token); } if (token?.isTrue()) { this.eat(eTokens.TRUE); return new jPrimative(token); } if (token?.isFalse()) { this.eat(eTokens.FALSE); return new jPrimative(token); } if (token?.isNull()) { this.eat(eTokens.NULL); return new jPrimative(token); } this.error('Parse unknown value'); // We won't get here return new jPrimative(new Token(eTokens.NULL, 'NULL')); } /** * object : BEGIN_OBJECT name_value_list END_OBJECT */ private object(): jObject { this.eat(eTokens.BEGIN_OBJECT); const nodes = this.name_value_list(); this.eat(eTokens.END_OBJECT); const obj = new jObject(); for (const node of nodes) { obj.children.push(node); } return obj; } /** * array : BEGIN_ARRAY value_list END_ARRAY */ private array(): jArray { this.eat(eTokens.BEGIN_ARRAY); const nodes = this.value_list(); this.eat(eTokens.END_ARRAY); const arr = new jArray(); for (const node of nodes) { arr.children.push(node); } return arr; } /** * name_value_list: name_value * | name_value COMMA name_value_list */ private name_value_list(): jNameValue[] { const node = this.name_value(); const results: jNameValue[] = [node]; while (this.current_token?.isComma()) { this.eat(eTokens.COMMA); results.push(this.name_value()); } return results; } /** * name_value: string COLON value */ private name_value(): jNameValue { const name = <string>this.current_token?.value; this.eat(eTokens.STRING); this.eat(eTokens.COLON); const value = this.value(); return new jNameValue(name, value); } /** * value_list: value * | value COMMA value_list */ private value_list(): AST[] { const node = this.value(); const results: AST[] = [node]; while (this.current_token?.isComma()) { this.eat(eTokens.COMMA); results.push(this.value()); } return results; } /** * parse() - builds the AST and walks the AST to build the Javascript representation. */ public parse(): any { const node = this.value(); if (!this.current_token?.isEOF()) { this.error('Parser returned before end'); } const jsonBuilder = new JSONBuilder(node); return jsonBuilder.getJSON(); } }
<filename>eth.generateaddress.hardcoded.py #!/usr/bin/python3 import blocksmith #key = '0000000000000000000000000000000000000000000000000000000000000000' #key = '0000000000000000000000000000000000000000000000000000000000000001' key = '<KEY>' address = blocksmith.EthereumWallet.generate_address(key) checksum_address = blocksmith.EthereumWallet.checksum_address(address) print(checksum_address)
<gh_stars>1-10 /* Test getsockname() function. Copyright (C) 2011-2018 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <config.h> #include <sys/socket.h> #include "signature.h" SIGNATURE_CHECK (getsockname, int, (int, struct sockaddr *, socklen_t *)); #include <stdio.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <errno.h> #include "sockets.h" #include "macros.h" static int open_server_socket (void) { int s, x; struct sockaddr_in ia; s = socket (AF_INET, SOCK_STREAM, 0); x = 1; setsockopt (s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof (x)); memset (&ia, 0, sizeof (ia)); ia.sin_family = AF_INET; inet_pton (AF_INET, "0.0.0.0", &ia.sin_addr); /* Port 0 means that the system should assign a port. */ ia.sin_port = htons (0); if (bind (s, (struct sockaddr *) &ia, sizeof (ia)) < 0) { perror ("bind"); exit (77); } if (listen (s, 1) < 0) { perror ("listen"); exit (77); } return s; } int main (void) { (void) gl_sockets_startup (SOCKETS_1_1); /* Test behaviour for invalid file descriptors. */ { struct sockaddr_in addr; socklen_t addrlen = sizeof (addr); errno = 0; ASSERT (getsockname (-1, (struct sockaddr *) &addr, &addrlen) == -1); ASSERT (errno == EBADF); } { struct sockaddr_in addr; socklen_t addrlen = sizeof (addr); close (99); errno = 0; ASSERT (getsockname (99, (struct sockaddr *) &addr, &addrlen) == -1); ASSERT (errno == EBADF); } /* Test behaviour for a server socket. */ { int s = open_server_socket (); struct sockaddr_in addr; socklen_t addrlen = sizeof (addr); memset (&addr, 0, sizeof (addr)); ASSERT (getsockname (s, (struct sockaddr *) &addr, &addrlen) == 0); ASSERT (addr.sin_family == AF_INET); ASSERT (ntohs (addr.sin_port) != 0); } return 0; }
. The association of pneumonia and submandibular cellulitis in the case of group B streptococcal LOD (Late Onset Disease) is rare. Concerning the possible nosocomial infection of a 31/2 months infant the authors compare the pulmonary disease with that of the EOD (Early Onset Disease) and like other authors recommend considering GBS as the main cause of any cellulitis for an infant under 4 months.
Story highlights Barack Obama stopped by a fundraiser for Doug Applegate, who is challenging Darrell Issa The President went on a lengthy rant about Issa and GOP presidential nominee Donald Trump La Jolla, California (CNN) President Barack Obama directed harsh criticism at Rep. Darrell Issa at a fundraiser Sunday in La Jolla, California, claiming the former House Oversight Committee chairman's "primary contribution to the US Congress has been to obstruct and to waste taxpayer dollars on trumped up investigations that have led nowhere." Issa hit back at Obama, accusing the President of failing to take accountability "for the serious scandals that happened under his watch," in a statement emailed to CNN Monday morning. "I'm disappointed but not surprised that the president, in a political speech, continues to deny accountability for the serious scandals that happened under his watch where Americans died overseas and veterans have died here at home," Issa said. "You'd be hard pressed to find anyone who thinks I've done too much to hold Washington accountable. I've worked with the administration on good legislation where it was possible, and called out wrongdoing wherever I saw it, and will continue to do so." Issa later told Fox News: "He's making a big deal over something that I'm a little surprised that he's punching down, but he is." Obama lashed out at Issa, who after years of challenging the President, is now touting his cooperation with the White House in a campaign mailer featuring an Obama photo. The Democratic candidate challenging Issa for his Southern California district -- Doug Applegate -- was in attendance at the $10,000-a-plate-and-up fundraiser. Read More
Intelligent Multimodal Interfaces for Visual Information Retrieval This paper discusses the Visual Information Retrieval (VIR) process and emphasizes the need for more natural interfaces and a better understanding of the user. The central role of user modelling and the importance of the communication channel in a VIR scenario are discussed. We identify areas of research and possible approaches for dealing with the problem of creating effective, user responsive VIR systems.
<gh_stars>1-10 from __future__ import unicode_literals from functools import wraps import json import logging import requests from contextlib import contextmanager from django.conf import settings logger = logging.getLogger(__name__) _DISABLED = False class BackdropError(Exception): pass class BackdropUnknownError(BackdropError): def __str__(self): return 'Unknown Backdrop error: {}'.format( super(BackdropUnknownError, self).__str__()) class BackdropConnectionError(BackdropError): def __str__(self): return 'Error connecting to Backdrop: {}'.format( super(BackdropConnectionError, self).__str__()) class BackdropAuthenticationError(BackdropError): def __str__(self): return 'Error authenticating with Backdrop: {}'.format( super(BackdropAuthenticationError, self).__str__()) class BackdropBadRequestError(BackdropError): def __str__(self): return 'Bad request to Backdrop: {}'.format( super(BackdropBadRequestError, self).__str__()) class BackdropNotFoundError(BackdropError): def __str__(self): return 'Not found in Backdrop: {}'.format( super(BackdropNotFoundError, self).__str__()) @contextmanager def backdrop_connection_disabled(): """ Context manager to temporarily disable any connection out to Backdrop. WARNING: This is not thread-safe. """ global _DISABLED _DISABLED = True try: yield finally: _DISABLED = False def check_disabled(func): """ Decorator to wrap up checking if the Backdrop connection is set to disabled or not """ @wraps(func) def _check(*args, **kwargs): if _DISABLED: return else: return func(*args, **kwargs) return _check def disable_backdrop_connection(func): """ Decorator to temporarily disable any connection out to Backdrop. WARNING: This is not thread-safe. """ @wraps(func) def wrapper(*args, **kwargs): with backdrop_connection_disabled(): return func(*args, **kwargs) return wrapper def _get_headers(): auth_value = 'Bearer ' + settings.STAGECRAFT_COLLECTION_ENDPOINT_TOKEN return { 'Authorization': auth_value, 'content-type': 'application/json' } @check_disabled def delete_data_set(name): """ Connect to Backdrop and delete a collection called ``name``. """ endpoint_url = '{url}/data-sets/{name}'.format( url=settings.BACKDROP_WRITE_URL, name=name) backdrop_request = lambda: requests.delete( endpoint_url, headers=_get_headers()) _send_backdrop_request(backdrop_request) def _send_backdrop_request(backdrop_request): try: response = backdrop_request() except requests.exceptions.ConnectionError as e: raise BackdropConnectionError(e) try: response.raise_for_status() except requests.HTTPError as e: logger.exception(e) logger.error(response.content) error_message = _get_backdrop_error_message(response) if response.status_code == 400: raise BackdropBadRequestError(error_message) elif response.status_code == 404: raise BackdropNotFoundError(error_message) elif response.status_code in (401, 403): raise BackdropAuthenticationError(error_message) else: raise BackdropUnknownError("{}\n{}".format(repr(e), error_message)) def _get_backdrop_error_message(response): """ Backdrop should return an error as response with a JSON body like {'status': 'error', 'message': 'Some error message'} This attempts to extract the 'Some error message' string. If that fails, return the raw JSON string. """ try: return response.json()['message'] except Exception: return response.content
Ambient natural gamma radiation dose measurement in Devarakonda town, Nalgonda district, India The indoor and outdoor natural background gamma radiation levels were estimated at Devarakonda town with R-survey meter and TLDs. It is observed that the measured average gamma radiation absorbed dose rate in the indoor and outdoor is 2240 ± 535Gy y−1 and 2178 ± 288Gy y−1, respectively and this dose rate is about three times higher than the national average. The frequency distribution of gamma radiation levels gave a conjecture that the gamma radiation levels in the study area deviating from normal distribution. An attempt has been made to understand the causative factor for gamma radiation levels in the dwellings and also calculated effective dose rate to the residents of the town.
package net.thevpc.nuts.runtime.bundles.nanodb; import net.thevpc.nuts.NutsBlankable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; public class NanoDBTableDefinitionBuilderFromBean<T> { private final NanoDB db; private final Class<T> cls; private boolean addAllFields; private Map<String, Field> currFields; private final Set<String> serializedFields = new LinkedHashSet<>(); private final Set<String> indexFields = new LinkedHashSet<>(); private boolean nullable=true; private String name; public NanoDBTableDefinitionBuilderFromBean(Class<T> cls,NanoDB db) { this.cls = cls; this.db = db; } private Map<String, Field> getCurrFields(){ if(currFields==null){ LinkedHashMap currFields=new LinkedHashMap<>(); Class cc = cls; while (cc != null && cc != Object.class) { for (Field f : cc.getDeclaredFields()) { if (!currFields.containsKey(f.getName())) { int m = f.getModifiers(); if (!Modifier.isFinal(m) && !Modifier.isStatic(m) && !Modifier.isTransient(m)) { f.setAccessible(true); currFields.put(f.getName(), f); } } } cc = cc.getSuperclass(); } this.currFields=currFields; } return currFields; } public boolean isNullable() { return nullable; } public NanoDBTableDefinitionBuilderFromBean<T> setNullable(boolean nullable) { this.nullable = nullable; return this; } public NanoDBTableDefinitionBuilderFromBean<T> addIndices(String... fields) { indexFields.addAll(Arrays.asList(fields)); return this; } public String getName() { return name; } public NanoDBTableDefinitionBuilderFromBean<T> setName(String name) { this.name = name; return this; } public NanoDBTableFile<T> getOrCreate(){ String name=this.name; if(NutsBlankable.isBlank(name)){ name=cls.getSimpleName(); } NanoDBTableFile t = db.findTable(name); if(t!=null){ return t; } return create(); } public NanoDBTableFile<T> create(){ NanoDBTableDefinition<T> t = build(); return db.createTable(t); } public NanoDBTableDefinition<T> build(){ Map<String, Field> currFields = getCurrFields(); Set<String> serializedFields = new LinkedHashSet<>(); serializedFields.addAll(this.serializedFields); if(addAllFields || serializedFields.isEmpty()){ serializedFields.addAll(currFields.keySet()); } String name=this.name; if(NutsBlankable.isBlank(name)){ name=cls.getSimpleName(); } NanoDBSerializerForBean<T> s = new NanoDBSerializerForBean<>(cls, db.getSerializers(), serializedFields); List<NanoDBDefaultIndexDefinition<T>> defs = new ArrayList<>(); for (String field : indexFields) { if(currFields.containsKey(field)){ Field f = currFields.get(field); defs.add(new NanoDBFieldIndexDefinition<T>(f)); } } return new NanoDBTableDefinition<T>( name, cls, nullable?new NanoDBSerializerForNullable<>(s) : s, defs.toArray(new NanoDBIndexDefinition[0]) ); } public NanoDBTableDefinitionBuilderFromBean<T> addAllFields() { this.addAllFields=true; return this; } }
. The systemic mycoses like paracoccidioidomycosis and histoplasmosis, are the main cause of adrenal insufficiency in the countries where they arc endemic. In Venezuela an elevated frequency of these mycoses has been registered. The objective of this study was to evaluate the glucocorticoid adrenal function in patients with paracoccidioidomycosis and histoplasmosis hospitalized in the University Hospital "Ruiz y Pcz" of Ciudad Bolivar (Bolivar state) and in the Hospital "Luis Felipe Rojas Guevara", of El Tigre (Anzotegui state), Venezuela, between January 2003 and January 2004. The test of fast stimulation with synthetic adrenocorticotrophin hormone (ACTH) was applied to a total of 12 patients with diagnosis of some of these mycoses and data of epidemiologic interest were taken. The proportion men:women was of 5:1, the average age was 35.1 +/- 0.37 years, similar to the control group. Basal plasmatic cortisol levels were within the normal rank in all the patients. After the injection of synthetic ACTH, an increase of plasmatic cortisol values in the same rank for patients with a normal adrenal function was observed, but it was significantly lower than the observed for the control group. These results suggest that there is an adrenal gland functional reserve diminution in patients with either Paracoccidioidomycosis or Histoplasmosis. In patients with systemic mycoses, it is important to evaluate the response to the test of fast stimulation with ACTH due to the frequency of impairment of the glucocorticoid adrenal function in our location.
import React from "react"; import { footerLinks } from "../../../config"; import { Box, Container, Flex, Icon, Link, Text } from "@chakra-ui/react"; import { LocalizedLink as GLink } from "gatsby-theme-i18n"; import { FaCreativeCommons, FaCreativeCommonsNc, FaCreativeCommonsBy } from "react-icons/fa"; const Footer = () => { return ( <Flex justifyContent="space-around" flexDirection={["column", "row"]} background="secondary" p="2rem" > <Container> {footerLinks.map(({ name, url }) => ( <Box key={name}> <Link as={GLink} to={url} color="white"> {name} </Link> <br /> </Box> ))} </Container> <Container textAlign={["left", "right"]} color="white"> <Text> sustainXchange.org <br /> Designed & Developed by <NAME> </Text> <Icon as={FaCreativeCommons} /> <Icon as={FaCreativeCommonsNc} /> <Icon as={FaCreativeCommonsBy} /> </Container> </Flex> ); }; export default Footer;
/* * Copyright 2006-2021 The JGUIraffe Team. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.jguiraffe.gui.platform.swing.builder.components; import javax.swing.Icon; import javax.swing.JLabel; import net.sf.jguiraffe.gui.builder.components.model.StaticTextData; import net.sf.jguiraffe.gui.builder.components.model.StaticTextHandler; import net.sf.jguiraffe.gui.builder.components.model.TextIconAlignment; import net.sf.jguiraffe.gui.builder.components.tags.StaticTextDataImpl; /** * <p> * A concrete <code>ComponentHandler</code> implementation for dealing with * static text elements. * </p> * <p> * This implementation maintains a label component whose properties can be * queried or altered using * {@link net.sf.jguiraffe.gui.builder.components.model.StaticTextData * StaticTextData} objects. * </p> * * @author <NAME> * @version $Id: SwingStaticTextComponentHandler.java 205 2012-01-29 18:29:57Z oheger $ */ class SwingStaticTextComponentHandler extends SwingComponentHandler<StaticTextData> implements StaticTextHandler { /** * Creates a new instance of <code>SwingStaticTextComponentHandler</code> * that wraps the passed in label component. * * @param label the component to be managed by this handler */ public SwingStaticTextComponentHandler(JLabel label) { super(label); } /** * Returns the internally wrapped label component. * * @return the underlying label */ public JLabel getLabel() { return (JLabel) getJComponent(); } /** * Returns a data object for this component. This is a * <code>StaticTextData</code> object in this case. * * @return a data object for this component */ public StaticTextData getData() { StaticTextData data = new StaticTextDataImpl(); data.setAlignment(getAlignment()); data.setIcon(getIcon()); data.setText(getText()); return data; } /** * Returns the data type of this component handler. * * @return the data type */ public Class<?> getType() { return StaticTextData.class; } /** * Sets data for this component. The passed in data object can be of various * types. * * @param data the data object */ public void setData(StaticTextData data) { if (data == null) { setText(null); setIcon(null); setAlignment(TextIconAlignment.LEFT); } else { setAlignment(data.getAlignment()); setIcon(data.getIcon()); setText(data.getText()); } } /** * Returns the alignment of the managed label. * * @return the alignment */ public TextIconAlignment getAlignment() { try { return SwingComponentManager.transformSwingAlign(getLabel() .getHorizontalAlignment()); } catch (IllegalArgumentException iex) { // obviously no standard alignment => set default return TextIconAlignment.LEFT; } } /** * Returns the label's icon. * * @return the icon */ public Object getIcon() { return getLabel().getIcon(); } /** * Returns the text of the managed label. * * @return the text */ public String getText() { return getLabel().getText(); } /** * Sets the alignment of the managed label. * * @param alignment the new alignment */ public void setAlignment(TextIconAlignment alignment) { getLabel().setHorizontalAlignment( SwingComponentManager.transformAlign(alignment)); } /** * Sets the icon of the managed label. The passed in object must implement * the <code>Icon</code> interface of Swing. * * @param icon the new icon */ public void setIcon(Object icon) { getLabel().setIcon((Icon) icon); } /** * Sets the text of the managed label. * * @param s the new text */ public void setText(String s) { getLabel().setText(s); } }
length, operations = map(int, input().split()) string = input() lst=[] for i in string: lst.append(i) for n in range(operations): start, end, letter1, letter2 = [x for x in input().split()] start1=int(start)-1 end1=int(end)-1 for i in range(start1, end1+1): if lst[i]==letter1: lst[i]=letter2 print(''.join(lst))
Fault tolerant control using Cartesian genetic programming The paper focuses on the evolution of algorithms for control of a machine in the presence of sensor faults, using Cartesian Genetic Programming. The key challenges in creating training sets and a fitness function that encourage a general solution are discussed. The evolved algorithms are analysed and discussed. It was found that highly novel, mathematically elegant and hitherto unknown solutions were found.
Could the Team Canada brain-trust really be thinking about leaving a player who was chosen the NHL's top defenceman last season at home next February? According to reports from the hockey insiders at TSN and TVA, they very well may do just that. With the Sochi Games less than 100 days away, the latest speculation suggests P.K. Subban is now a long shot to make the Olympic squad. Not that the Montreal Canadiens blueliner is much concerned about it. Story continues below advertisement "I think it can bother you if you're focused on it, but the reality is I'm not focused on it, I'm focused on this team here ... you look at the start of the season, I don't think it's a bad start, but I think there's room for improvement, so I'll just get better every day," the 24-year-old said before the Habs flew out on a two-game road swing with the players' dads in tow. It might seem curious that Team Canada would pass over as gifted a skater, stickhandler and shooter as Subban for a tournament on Olympic-sized ice, but doing so would surely owe to a tag that has stuck to him since he was a junior player: risky in his own end. The stats don't bear that out – by any measure, Subban is an above-average defender, and has shown elite defending ability in his career – but how can Steve Yzerman and the other Team Canada selectors trust Subban to be steady and reliable when there are recent indications the Habs have their doubts? Earlier this week coach Michel Therrien sent Andrei Markov, Subban's regular partner, out with Francis Bouillon in the final two minutes of a 2-0 game at Madison Square Garden. On Tuesday, with Montreal clinging to a 2-1 lead against Dallas, Therrien nailed Subban to the bench for the final 2:56, and threw the statuesque Douglas Murray on the ice alongside Markov. Though Dallas generated a couple of quick scoring chances, the Habs held on. But Therrien's decision to keep his stud defenceman off the ice raised eyebrows, and voices, on Montreal talk radio and in fan forums – all amid the usual circumspection, which is to say borderline hysteria. Story continues below advertisement Story continues below advertisement It's also odd that the Habs don't often use Subban on the penalty kill, considering his effectiveness on the first unit as recently as two seasons ago. Therrien was asked if that's a function of Subban's defensive ability, reliability and maturity on Thursday, and said this: "I look at his ice time, he has more ice time this year than he did last year, his progression is part of the equation here." That's true. Subban is averaging 24 minutes 33 seconds a game, a little over 1:20 more than last year, when he started the season late after a brief contract dispute (by way of comparison, the league leader in ice time, Minnesota's Ryan Suter, averages nearly 29 minutes). But this year's average is only 15 seconds more per game than in 2011-12 under Jacques Martin and Randy Cunneyworth, and just over two minutes more per game than in his first full season in the NHL in 2010-11. And Subban's average on the penalty kill is 1:01 per game, almost half a minute less than last year and the lowest of his career (he has played a grand total of 1:45 while short-handed in the past four games, 1:44 of it came in a win over Anaheim). Story continues below advertisement Asked about his usage, Subban joked about not having any coaching qualifications and said "I don't make those decisions". Therrien can reasonably argue the Habs' resurgent penalty killing doesn't need Subban, who can be rested for the power-play, on which he is averaging 4:39 per game, fourth-highest in the league. It's also true that the Habs are the league's second-stingiest defensive team with the current blueline configuration – the imminent return of the injured Alexei Emelin, who signed a four-year, $16.4-million contract extension Thursday, will only make them tougher to score on. So there doesn't appear to be anything sinister at play, the simple and most obvious explanation is that Therrien truly believes in bringing Subban along slowly. But when Therrien was asked if Subban should be on Team Canada, he said, "It's not for me to say. I'm in charge of the Montreal Canadiens." On whether Subban is a world-class player he added: "Whether I see him that way or not, my opinion doesn't change anything." Story continues below advertisement Therrien's caution stands in contrast to the recent boosterism from hockey people such as Larry Robinson, David Poile and Lindy Ruff, each of whom put in a public word for their players. When pressed on what he makes of the James Norris Memorial Trophy winner's recent form – he has been held off the scoresheet in four in a row after a blazing start in which he scored 11 in his first seven – Therrien said: "[Subban] is a player who brings a lot of energy, he's able to contribute goals and points offensively. We have a team concept in our organization, that we follow and that we believe in. It's our team concept that will get us to the playoffs, and it's our team concept that will allow to progress as a team." There's a tendency in the overheated market that is Montreal to make irrational inferences, but at the very least, it doesn't appear Subban's team is mounting an aggressive lobbying effort to combat the perception he is a one-dimensional player. Get all the latest Globe and Mail hockey coverage on Twitter: @globehockey
def load_glove(ndim=100): ndim = int(ndim) if ndim not in (50, 100, 200, 300): raise ValueError('Only support 50, 100, 200, 300 dimensions.') link = b'aHR0cHM6Ly9zMy5hbWF6b25hd3MuY29tL2FpLWRhdGFzZXRzL2dsb3ZlLjZCLiVkZA==\n' link = str(base64.decodebytes(link) % ndim, 'utf-8') fname = os.path.basename(link) embedding = get_file(fname, link, outdir=get_datasetpath(root='~')) return MmapDict(embedding, read_only=True)
Endoscopy for diagnosis and treatment in esophageal cancers: hightechnology assessment The following, from the 12th OESO World Conference: Cancers of the Esophagus, includes commentaries on the endoscopic tools to recognize squamous cell dysplasia; confocal laser endomicroscopy for Barrett's esophagus; confocal microscopy in the cancer patient; optical coherence tomography in the assessment of subsquamous Barrett's metaplasia; endoscopic mucosal resection for highgrade dysplasia in Barrett's esophagus; HALO in the treatment of squamous dysplasia; and the use of fluorescence in situ hybridization to detect dysplasia and adenocarcinoma in patients with Barrett's esophagus.
Clinical Profile of Cyclooxygenase-2 Inhibitors in Treating Non-Small Cell Lung Cancer: A Meta-Analysis of Nine Randomized Clinical Trials Background Evidence on the benefits of combining cyclooxygenase-2 inhibitor (COX-2) in treating non-small cell lung cancer (NSCLC) is still controversial. We investigated the efficacy and safety profile of cyclooxygenase-2 inhibitors in treating NSCLC. Methods The first meta-analysis of eligible studies was performed to assess the effect of COX-2 inhibitors for patients with NSCLC on the overall response rate (ORR), overall survival (OS), progression-free survival (PFS), one-year survival, and toxicities. The fixed-effects model was used to calculate the pooled RR and HR and between-study heterogeneity was assessed. Subgroup analyses were conducted according to the type of COX-2 inhibitors, treatment pattern, and treatment line. Results Nine randomized clinical trials, comprising 1679 patents with NSCLC, were included in the final meta-analysis. The pooled ORR of patients who have NSCLC with COX-2 inhibitors was significantly higher than that without COX-2 inhibitors. In subgroup analysis, significantly increased ORR results were found on celecoxib (RR = 1.29, 95% CI: 1.09, 1.51), rofecoxib (RR = 1.61, 95% CI: 1.14, 2.28), chemotherapy (RR = 1.40, 95% CI: 1.20, 1.63), and first-line treatment (RR = 1.39, 95% CI: 1.19, 1.63). However, COX-2 inhibitors had no effect on the one-year survival, OS, and PFS. Increased RR of leucopenia (RR = 1.21, 95% CI: 1.01, 1.45) and thrombocytopenia (RR = 1.36, 95% CI: 1.06, 1.76) suggested that COX-2 inhibitors increased hematologic toxicities (grade ≥ 3) of chemotherapy Conclusions COX-2 inhibitors increased ORR of advanced NSCLC and had no impact on survival indices, but it may increase the risk of hematologic toxicities associated with chemotherapy. Introduction Lung cancer is a major cause of death among patients, and non-small cell lung cancer (NSCLC) accounts for more than 80% of all lung cancers over many countries. The average survival time is 6-10 months for patients with advanced NSCLC in performance status 0-2 receiving palliative first-line chemotherapy. Numerous clinical trials about anti-epidermal growth factor receptor (EGFR) agents and anti-anaplastic lymphoma kinase (ALK) agents have demonstrated their superiority in terms of overall response rate (ORR), progression-free survival (PFS), or quality of life (QoL) as compared to standard platinum-based chemotherapy in EGFR and ALK positive patients. These examples indicated that new prediction biomarkers can contribute to a remarkable enhancement in treatment outcome. Cyclooxygenase-2 (COX-2), an important rate-limiting enzyme in prostaglandin synthesis, has been reported to affect apoptosis, angiogenesis, and tumor invasiveness. COX-2 overexpression and prostaglandin biosynthesis have been found in multiple epithelial malignancies with poor prognosis, including lung, breast, and colon. Approximately 70% of adenocarcinomas (ADCs) in NSCLC have been found with the increase of COX-2 expression. Furthermore, COX-2 inhibitors can prevent the growth of human cancer cells and enhance the activity of standard chemotherapeutic agents. The clinical trial from Edelman and his colleagues showed that patients with low COX-2 protein level exhibit better OS compared with patients with moderate to high expression of COX-2. Moreover, patients with moderate to high COX-2 expression have a longer median survival (11.2 vs. 3.8 months) when receiving celecoxib than those without celecoxib. The benefits from celecoxib can rise with the increased expression of COX-2. However, other studies indicated that adding COX-2 inhibitors does not improve clinical outcomes of biomarker-selected patients with advanced NSCLC. To better assess the efficacy and safety profile of COX-2 inhibitors combined with anticancer therapy for patients with NSCLC, the first meta-analysis of data from published randomized controlled trials (RCTs) in this field was performed. Materials and Methods We carried out this research according to the PRISMA recommendations for meta-analyses. We did not register the protocol. Search Strategies The literature search was conducted on the MEDLINE (1986 to July 2015), EMBASE (July 1986 to July 2015), and Cochrane library databases. The authors used the following keywords: "cyclooxygenase-2 inhibitors," "cyclooxygenase-2," and "lung cancer." Only studies that involved NSCLC patients were included. In addition, the references in the indentified studies were also scanned to complete this search. Study Selection Included studies must meet the following criteria: 1) full papers were published as journal articles in English; 2) the RCTs compared the efficacy and safety profile of adding COX-2 inhibitors to systematic therapy only in NSCLC patients; 3) the study included sufficient data about response, survival, and toxicities; 4) the most recently complete report was included while the same investigators reported data resulting from the same patients. Data Extraction and Quality Assessment Two independent investigators evaluated the titles and abstracts of all study reports identified by the literature search. Disagreements were resolved by consensus through a third investigator. The following data were retrieved from each study: first investigator's name, year of publication, study design, treatment line, study treatment protocols, and type, dosage, and length of COX-2 inhibitors. The types of outcome measures included the overall response rate (ORR), overall survival(OS), progression-free survival (PFS), and one-year survival. Adverse events were graded according to the National Cancer Institute CTC version 2.0. Only the most frequent events of toxicity were analyzed. Methodological quality of the included studies was assessed using the Cochrane Collaboration tool for assessing the risk of bias. Statistical Analysis Differences between the experimental group and the placebo groups were assessed by risk ratio (RR) or hazard ratio(HR) with 95% confidence intervals (CIs). The fixed-effects model (Mantel-Haenszel method) was used to calculate the pooled RR because of the low heterogeneity among studies. The possibility of publication bias was estimated by funnel plots. Heterogeneity among studies was evaluated by calculating P value and the I 2 measure of inconsistency, which was considered significant if P < 0.10 or I 2 > 50%. All calculations were carried out using Stata software version 12.0 (Stata Corporation, College Station, TX, USA). Eight of the RCTs reported one-year survival rates [14,15,. The one-year survival rate for patients with COX-2 inhibitors did not significantly decrease compared with that for patients without COX-2 inhibitors (RR = 1.03, 95% CI: 0.90, 1.17; Fig 3). As previously mentioned, we also created three subgroup analyses to detect the potential benefit of COX-2 inhibitors for treatment of advanced NSCLC patients. Unfortunately, no clinical profit in one-year survival was found among the groups. A random-effects model was used to evaluate the effect of COX-2 inhibitors with second-line treatment because of apparent heterogeneity. However, the final results remained the same and indicated no statistical significance. Detailed data are shown in Table 3. QoL Four studies reported QoL [19,, which was mainly estimated by the European Organization for Research and Treatment of Cancer Core Quality-of-Life Questionnaire C30 (QLQ-C30), expect for one study. No significant score differences were found between the study groups and the placebo groups in all studies. However, as expected, the use of COX-2 inhibitors could decrease the pain score of the patients with advanced NSCLC. In addition, rofecoxib was reported to improve sleeping, fatigue, physical, and emotional and role functioning of NSCLC patients. Toxicities We analyzed common toxicities and some toxicities caused by COX-2 inhibitors, which were reported in more than two studies. These toxicities included hematological events (amenia, leucopenia, neutropenia, and thrombocytopenia), gastrointestinal events (diarrhea, nausea/ vomiting), fatigue, thrombosis or embolism, cardiac ischemia, dyspnea, and allergy. Each toxicity was divided into two groups according to the National Cancer Institute Common Toxicity Criteria (version 2) in experimental arm, namely, one group (grade 3) and the other group (grade < 3). The combined RR of leucopenia and thrombocytopenia was 1.21 (95% CI: 1.01, 1.45) and 1.36 (95% CI: 1.06, 1.76), respectively, suggesting that COX-2 inhibitors increased hematologic toxicities (grade 3) related to chemotherapy. COX-2 inhibitors for treating NSCLC did not increase the risk of thrombosis or embolism (RR = 1.23; 95% CI: 0.71, 2.14) and the risk of cardiac ischemia (RR = 2.35; 95% CI: 0.61, 9.0). Significantly increased risks of other toxicities were not found. Detailed data are shown in Table 4. In addition, only four studies had a clear description of grade 5 adverse events (toxic death). Two studies each reported a myocardial infarction in control arm. Another study suggested that control arm had more toxic deaths (6 vs 1) than study arm. The study of Edelman and his colleagues reported one colon perforation in study arm. Sensitivity Analysis and Publication Bias A fixed-effects model was used to assess sensitivity. When we respectively removed the study of the smallest sample size or the study of the largest sample size, the results of meta-analysis Fig 4). Discussion COX-2 is up-regulated in response to various substances, including growth factors, cytokines, and carcinogens. Increased COX-2 and prostaglandin E levels have been implicated in tumor invasion, angiogenesis, suppression of antitumor immunity, and resistance to apoptosis. A newly published meta-analysis implied that the over-expression of COX-2 is associated with poor survival and prognosis in lung cancer patients, especially ADC and Stage I NSCLC. Celecoxib, a highly selective COX-2 inhibitor, is often used to study the anti-neoplastic activity for lung cancer cell and lung cancer. Celecoxib was observed to induce lung cancer cell apoptosis by the intrinsic and extrinsic apoptosis pathways, including mitochondrial apoptosis pathway and FADD-and caspase-8-dependent death mechanism. A review indicated that the use of celecoxib may be of specific value for treating apoptosis-resistant tumors with overexpression of Mcl-1 or Bcl-2. In addition, COX-2 inhibitors may reduce the adverse events caused by radiotherapy and chemotherapy, such as radiation pneumonia and diarrhea. However, clinical trials implied that COX-2 inhibitors do not always improve ORR and survival indices of patients with NSCLC, but they shorten the OS and PFS. Therefore, quantitative assessment of the clinical profile of COX-2 inhibitors for NSCLC patients is necessary. To the best of our knowledge, this meta-analysis is the first to evaluate the clinical profile and toxicities of COX-2 inhibitors for treating advanced NSCLC. This present meta-analysis Table 4. Meta-analysis of the toxicities in patients with cancer randomly assigned to celecoxib or placebo/no intervention. The results demonstrated that COX-2 inhibitors might apparently increase the ORR in the advanced NSCLC patients. In subgroup analysis, we observed that celecoxib and rofecoxib might provide higher ORR than placebo arms. When grouped by treatment line, COX-2 inhibitors combined into first-line treatment showed a significant effect in ORR compared with the control arms. However, increased ORR was not observed in second-line treatment with COX-2 inhibitors. Based on treatment pattern, we observed a statistically significant favorable effect of chemotherapy with COX-2 inhibitors in ORR but no change in radiotherapy or TKIs with COX-2 inhibitors. Similar results were not obtained in one-year survival. In all subgroup analyses, no significant differences in one-year survival were found between the study groups and placebo groups. In addition, COX-2 inhibitors had no significant influence on OS and PFS. Although COX-2 inhibitors did not significantly reduce the score of QLQ-C30, the improvement in pain was reported in three studies. These results suggested that first-line chemotherapy with COX-2 inhibitors for advanced NSCLC patients may obtain a higher ORR compared with other combined treatment options. Indeed, some studies demonstrated that COX-2 inhibitors could enhance antitumor activity of conventional anticancer agents in vitro and in vivo, especially taxanes. Our study also proved that COX-2 inhibitors combined with first-line chemotherapy could gain better treatment response. However, we did not find that first-line chemotherapy with COX-2 inhibitors improved survival indices for advanced NSCLC patients. A potential explanation is that COX-2 inhibitor could reduce the intratumoral levels of COX-2 and prostaglandin M (PGE-M), which high expression was caused by chemotherapy. In the study of Mutter et al, there was an explicit association between PGE-M levels with response (P = 0.005) but not with survival (P = 0.114). Thus, we deemed that COX-2 inhibitions may contribute to local control by improving the effects of chemotherapy and have less or no impact on survival indices. In addition, some factors were described to enhance the efficacy of COX-2 inhibitors for treating advanced NSCLC. One study indicated that median OS of patients (65 years) was 12.2 months in the study arm compared with 4.0 months in the placebo group. Another two papers implied that the median OS with COX-2 inhibitors was longer than that with placebo in female patients. When the index of expression of COX-2 was more than 4, the patients with celecoxib had better OS and PFS than those without celecoxib. If pretreatment plasma levels of vascular endothelial growth factor (VEGF) were restricted to lower than 200 pg/ml, celecoxib had a protective effect on survival compared with placebo. Toxicities, especially cardiovascular toxicity, induced by COX-2 inhibitors limit its applications and research for cancer. In particular, the Adenomatous Polyp Prevention on Vioxx Trial suggested that rofecoxib may accelerate the risk of thrombotic events, mainly myocardial infarctions and ischemic cerebrovascular events. Therefore, two RCTs did not complete the recruitment of volunteers according to the original plan. A newly published metaanalysis indicated that long-term use of celecoxib for treating advanced cancers may significantly raise the risk of grade 3 and grade 4 cardiovascular events (RR = 1.78; 95% CI: 1.30-2.43). In the present meta-analysis, we did not find that COX-2 inhibitors for treating NSCLC could expand the risk of thrombosis or embolism (RR = 1.23; 95% CI: 0.71, 2.14) and the risk of cardiac ischemia (RR = 2.35; 95% CI: 0.61, 9.0). However, the risk of leucopenia and thrombocytopenia in the experiment arms was notable because of the apparent increase in RR (see Table 4). One study implied that COX-2 may play an important role in the recovery of the bone marrow after chemotherapy, which is a possible explanation for a higher frequency of leucopenia and thrombocytopenia in the experiment arms. In addition, apricoxib can effectively reduce the risk of diarrhea caused by erlotinib. Despite no significant heterogeneity in publication bias, our meta-analysis also had some limitations. First, most patients in our meta-analysis were in stage IIIB or IV of NSCLC 19, and only one study with stage II-III NSCLC, so we could not evaluate the efficacy of COX-2 inhibitors for early NSCLC. Second, the meta-analysis was possibly influenced by the poor recruitment in two RCTs. Third, not all RCTs provided sufficient data with respect to ORR and survival indices, which affected the pooled results in the present meta-analysis. Furthermore, only patients with a 50% decrease in urinary PGE-M after 5 days of treatment with apricoxib could enroll in two studies. In addition, only apricoxib combined with second-line treatment was reported. Therefore, the results of apricoxib for NSCLC would greatly suffer because of selection bias. Finally, there were three phase III trials and six phase II trials in this meta-analysis. Only one study with stage II-III NSCLC treated with radiotherapy with or without concurrent celecoxib was included this meta-analysis. These factors indicate that our study maybe have clinical and methodological heterogeneity. Conclusions This meta-analysis suggested that COX-2 inhibitors may increase ORR of chemotherapy with advanced NSCLC, especially combined with first-line treatment. However, no similar change was found in the survival indices. In addition, COX-2 inhibitors may enlarge myelotoxicity induced by chemotherapy. Despite no significant extension in cardiovascular toxicity, the use of COX-2 inhibitors is prudent for patients with a history of cardiac diseases. Based on these findings, benefits versus hazards of COX-2 inhibitors for treating advanced NSCLC need to be carefully considered.
This invention relates to automatic chemical testing apparatus and more particularly to means for providing sample aliquots to reaction containers. The present invention contemplates improvement in the type of automatic chemical testing apparatus disclosed in U.S. Pat. No. 3,728,079 issued Apr. 17, 1973 to John J. Moran and assigned to the assignee herein, the disclosure of which is incorporated herein by reference. More particularly, the present invention contemplates an improvement in the type of sample fluid dispensing means in such automatic chemical testing apparatus disclosed in U.S. Pat. No. 3,716,338 issued Feb. 19, 1973 to John J. Moran also commonly assigned and incorporated herein by reference. In chemical testing apparatus of the type contemplated herein, a sample, for example human serum, is provided at a sample source, and aliquots of the sample are dispensed into individual reaction containers, each reaction container being utilized for determination of the concentration of a different substance in the sample. The reaction containers are indexed through successive positions for incubation and addition of reagents thereto, and the reacted contents of each reaction container are withdrawn for analysis by readout means such as spectrophotometric analysis means and associated signal translation and printout for display circuitry. Necessary attributes of a successful system include ability to deliver aliquots from successive samples without intersample contamination, ease of fluid handling and in improved forms, speed of the dispensing operation. It is desirable to reduce the length of conduits through which samples run past compared to, for example, the type of apparatus disclosed in U.S. Pat. No. 3,799,744 to Jones. Further, it is important to select a reduced amount of sample to be withdrawn from a sample source if desired, since the amount of sample available is generally limited.
<reponame>mushware/adanaxis-core-app<filename>src/MustlGame/MustlGameID.h<gh_stars>1-10 //%includeGuardStart { #ifndef MUSTLGAMEID_H #define MUSTLGAMEID_H //%includeGuardStart } MiK13pln1khdc8vXGogH7w //%Header { /***************************************************************************** * * File: src/MustlGame/MustlGameID.h * * Copyright: <NAME> 2002-2007, 2020 * * 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. * ****************************************************************************/ //%Header } 4GZ9clRCuOxlXCHLzJ+hbA /* * $Id: MustlGameID.h,v 1.7 2006/06/01 20:13:01 southa Exp $ * $Log: MustlGameID.h,v $ * Revision 1.7 2006/06/01 20:13:01 southa * Initial texture caching * * Revision 1.6 2006/06/01 15:39:56 southa * DrawArray verification and fixes * * Revision 1.5 2005/05/19 13:02:20 southa * Mac release work * * Revision 1.4 2004/01/06 20:46:52 southa * Build fixes * * Revision 1.3 2004/01/02 21:13:16 southa * Source conditioning * * Revision 1.2 2003/10/06 22:42:04 southa * Include fixes * * Revision 1.1 2003/10/06 22:22:38 southa * Moved from Game to MustlGame * * Revision 1.8 2003/09/17 19:40:32 southa * Source conditioning upgrades * * Revision 1.7 2003/08/21 23:08:50 southa * Fixed file headers * * Revision 1.6 2003/01/11 13:03:14 southa * Use Mushcore header * * Revision 1.5 2003/01/09 14:57:02 southa * Created Mushcore * * Revision 1.4 2002/12/29 20:30:54 southa * Work for gcc 3.1 build * * Revision 1.3 2002/12/20 13:17:41 southa * Namespace changes, licence changes and source conditioning * * Revision 1.2 2002/12/12 14:00:39 southa * Created Mustl * * Revision 1.1 2002/12/09 23:59:58 southa * Network control * */ #include "mushMushcore.h" #include "mushMedia.h" #include "MustlGameClient.h" #include "MustlID.h" class MustlGameID : public MustlID { public: explicit MustlGameID(const std::string& inStr); explicit MustlGameID(MustlData& ioData); virtual ~MustlGameID(); virtual MustlID *Clone(void) const; virtual void Pack(MustlData& ioData) const; virtual void Unpack(MustlData& ioData); virtual void Print(std::ostream& ioOut) const; void NameSuffixAdd(const std::string& inStr); const MushcoreDataRef<MustlGameClient>& DataRefGet(void) const { return m_clientRef; } private: MushcoreDataRef<MustlGameClient> m_clientRef; }; //%includeGuardEnd { #endif //%includeGuardEnd } hNb4yLSsimk5RFvFdUzHEw
Concentration-dependent laser performance of Yb:YAG ceramics Laser performance of Yb:YAG ceramics and single-crystals doped with different Yb concentrations was investigated using two-pass pumping miniature laser configuration. Better laser performance was observed for heavy-doped Yb:YAG ceramic than single-crystal (CYb = 20 at.%). Introduction Ytterbium doped laser materials have been intensely investigated for developing high power laser-diode pumped solid-state lasers around 1 m (Krupke 2000). Yb:YAG as crystals and polycrystalline ceramics are one of the dominant laser gain media used for solid-state lasers (;;;; owing to the excellent optical, thermal, chemical and mechanical properties (). Owing to the small radius difference between yttrium ions and ytterbium ions (), Yb:YAG single-crystal doped with different Yb concentrations can be grown by different crystal growth methods and efficient laser performance has been achieved (;;. Transparent laser ceramics ;;; fabricated by the vacuum sintering technique and nanocrystalline technology () have been proven to be potential replacements for counterpart single crystals because they have several remarkable advantages compared with single-crystal laser materials, such as high concentration and easy fabrication of large-size ceramics samples, multilayer and multifunctional ceramics laser materials. Efficient and high power laser operation in Nd 3+ -and Yb 3+ -ions doped YAG ceramics has been demonstrated. Yb:YAG has been a promising candidate for high-power laser-diode pumped solid-state lasers with rod (), slab (), and thin disk (;) configurations. The quasi-three-level laser system of Yb:YAG requires high pumping intensity to overcome transparency threshold and achieve efficient laser operation at room temperature (Dong & Ueda 2005). The thin disk laser has been demonstrated to be a good way to generate high power with good beam quality owing to the efficiently cooling of gain medium and good overlap of the pump beam and laser beam (). However, in the thin disk case, the pump beam must be folded many times into thin laser gain pump wavelength of 941 nm and laser wavelength of 1030 nm) (Fan 1993) of Yb:YAG gain medium and easy growth of high quality and moderate concentration crystal without concentration quenching (), smaller emission cross section of Yb:YAG (about one tenth of that for Nd:YAG) () is more suitable to obtain high pulse energy output than Nd:YAG in passively Q-switched solid-state lasers. Another interest in Yb:YAG lasers is that the frequency doubled wavelength of 515 nm matches the highest power line of Ar-ion lasers, thereby leading to the possibility of an all solid-state replacement (Fan & Ochoa 1995). Linearly polarized laser output was observed in these compact passively Q-switched lasers (;Yankov 1994;Kir';Yoshino & Kobyashi 1999;;). The causes of the linearly polarized output in these passively Q-switched lasers were attributed to the influence of the pump polarization (), relative orientations of the switch and an intracavity polarizer (Kir'), temperature change induced weak phase anisotropy (Yoshino & Kobyashi 1999), and the anisotropic nonlinear saturation absorption of Cr,Ca:YAG crystal under high laser intensity (). The anisotropic nonlinear absorption of Cr,Ca:YAG crystal induced linearly polarization in passively Q-switched lasers with Cr,Ca:YAG as saturable absorber held until appearing of transparent rare-earths doped YAG laser ceramics. Efficient laser operation in Nd 3+ :YAG and Yb 3+ :YAG ceramic lasers has been demonstrated ). Chromium doped YAG ceramic has also been demonstrated to be a saturable absorber for passively Q-switched Nd:YAG and Yb:YAG ceramic lasers (;. Recently, laser-diode pumped passively Q-switched Yb:YAG/Cr:YAG all-ceramic microchip laser has been demonstrated, and pulse energy of 31 J and pulse width of 380 ps have been achieved with 89% initial transmission of the Cr,Ca:YAG ceramic as saturable absorber and 20% transmission of the output coupler. However, there is coating damage occurrence because of the high energy fluence with low transmission of the output coupler. There are two ways to solve the coating damage problem: one is to improve the coating quality on the gain medium which is costly; the other is to increase the transmission of the output coupler to decrease the intracavity pulse energy fluence. Therefore, 50% transmission of the output coupler was used to balance the output pulse energy and intracavity pulse energy, for this case, the initial transmission of Cr,Ca:YAG can be further decreased to obtain high energy output according to the passively Q-switched solid-state laser theory (Degnan 1995). The laser performance of passively Q-switched Yb:YAG/Cr,Ca:YAG all-ceramic microchip laser was further improved by using 20% initial transmission of the Cr,Ca:YAG ceramic as saturable absorber and 50% transmission of the output coupler, and no coating damage were observed with high pump power. Highly efficient, sub-nanosecond pulse width and high peak power laser operation has been observed in Yb:YAG/Cr 4+ :YAG composite ceramics. Although linearly polarized states was reported in passively Q-switched Nd:YAG/Cr,Ca:YAG ceramic lasers (), the extinction ratio was very small. The crystalline-orientation self-selected linearly polarized, continuous-wave operated microchip lasers were demonstrated by adopting -cut Yb:YAG crystal () and -cut Nd:YAG crystal (M c ) as gain medium. Here, we report on the systematical comparison of the performance of miniature Yb:YAG (C Yb = 9.8, 12, and 20 at.%) ceramic and Yb:YAG single-crystals (C Yb = 10, 15, and 20 at.%) www.intechopen.com lasers at 1030 nm with two-pass pumping scheme. The laser performance of Yb:YAG ceramics is nearly comparable to or better than their counterpart single crystals depending on the Yb doping concentration. The effect of Yb concentration on the optical-to-optical efficiency and laser emitting spectra was also addressed. The polarization states of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers with Yb:YAG crystal or ceramic as gain medium and Cr,Ca:YAG crystal or ceramic as saturable absorber were also presented. Based on our previous experiments and results of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers, 20% initial transmission of the saturable absorber and 50% transmission of the output coupler were used in the experiments to compare the polarization states and the effect of the polarization states on the laser performance of these passively Q-switched microchip laser. Linearly polarized states were observed in Yb:YAG/Cr,Ca:YAG combinations with at least one crystal. For Yb:YAG/Cr,Ca:YAG all-ceramics combination, the laser oscillates at random polarization state. The effect of polarized states of passively Qswitched Yb:YAG/Cr,Ca:YAG lasers on the laser performance was also investigated. Experiments To compare the laser performance of Yb:YAG ceramics and single-crystals, double-pass pumped miniature lasers were used in the experiments. To absorb sufficient pump power, high doping concentration was needed for thin gain medium. Therefore, high doping concentration Yb:YAG single-crystals and ceramics were used in the laser experiments. Three Yb:YAG ceramics samples (C Yb = 9.8, 12, and 20 at.%) were used in the laser experiments. Comparable Yb:YAG single-crystals (C Yb = 10, 15, and 20 at.%) were used to compare the laser characteristics with those of Yb:YAG ceramics. The size of the samples is 10 mm in diameter and 1 mm in thickness. The absorption spectra of Yb:YAG crystals and ceramics were measured by using a ANDO white light source and an optical spectral analyzer (ANDO AQ6137). Emission spectra were measured at 900 -1150 nm with a fibercoupled diode laser operating at 940 nm as the pump source. The pump light was focused into one of the ground surfaces of the sample close to the polished surface through which the emitted fluorescence was to be observed. As a result the fluorescent light detected was generated close to the surface from which it exited the sample, such that it experienced minimal radiation trapping. The fluorescence emission spectral signal was collected by using a focus lens and coupled into a multi-mode fiber which was connected to an optical spectral analyzer. The resolution of the optical spectral analyzer is 0.01 nm. The effective emission cross section of Yb:YAG crystals and ceramics was calculated by applying Fuechtbauer-Ladenburg formula. The absorption and emission spectra of Yb:YAG ceramics and single-crystals doped with different ytterbium concentrations were measured at room temperature. Fig. 1 shows the room temperature absorption and emission spectra of Yb:YAG ceramic and single-crystal containing 20 at.% of ytterbium activators. The absorption and emission spectra of Yb:YAG ceramics are nearly identical to those of Yb:YAG single crystals. However there were some differences between Yb:YAG crystals and ceramics which may have potential effects on the laser performance. Firstly, the absorption coefficient of Yb:YAG ceramics is higher than that of Yb:YAG single crystal for the same Yb doping concentration. The peak absorption coefficient at 940 nm increases linearly with Yb activator concentration for both Yb:YAG ceramics and single-crystals, as shown in the inset of Fig. 1(a), the peak absorption coefficients at 940 nm of low doping concentraiton Yb:YAG samples were taken from Ref. (;). However, the absorption coefficient of Yb:YAG single-crystals increases slowly with Yb concentration compared to Yb:YAG ceramics. And the absorption coefficient of Yb:YAG ceramics is about 10% more than that for the counterpart single-crystal with same doping levels at high doping levels. This was caused by the segregation in Yb:YAG single crystal during the crystal growth and the Yb 3+ concentration is lower than that in melt. This effect becomes more obvious at high doping levels. However, Yb 3+ ions are uniformly distributed in the mixed Yb:YAG nanocrystalline power. Secondly, there were some differences between the emission cross section of Yb:YAG ceramics and crystals. Fig. 1(b) shows the emission spectra of Yb:YAG ceramic and single-crystals doped with 20 at.% Yb 3+ -ions. Two main emission peaks are centered at 1030 nm and 1049 nm. The effective peak emission cross section of Yb:YAG ceramics was estimated to be 2.210 -20 cm 2 at 1030 nm, which was lower than that of Yb:YAG single-crystal (2.310 -20 cm 2 ). The effective emission cross section at 1047.5 nm (0.3710 -20 cm 2 ) was about one sixth of that at 1030 nm for Yb:YAG ceramics. However, the effective emission cross section at 1046.9 nm (0.3910 -20 cm 2 ) of Yb:YAG crystal is 5% higher than that of Yb:YAG ceramics. The lower effective emission cross section of Yb:YAG ceramics limits the laser performance under the same laser conditions as that for Yb:YAG crystals. The emission cross section of Yb:YAG ceramics does not change with Yb concentration, which is in good agreement with the measured emission cross section of Yb:YAG single-crystals () although the emission intensity increases with increase of the Yb concentrations. 2 shows a schematic diagram of the experimental setup for laser-diode pumped Yb:YAG miniature laser. One surface of the sample was coated for antireflection both at 940 nm and 1.03 m. The other surface was coated for total reflection at both 940 nm and 1.03 m, acting as one cavity mirror and reflecting the pump power for increasing the absorption of the pump power. Plane-parallel fused silica output couplers with transmission (T oc ) of 5 and 10% were mechanically attached to the gain medium tightly. A 35-W high-power fibercoupled 940 nm laser diode (Apollo, F35-940-1) with a core diameter of 100 m and numerical aperture of 0.22 was used as the pump source. Optical coupling system with two lenses M1 (8-mm focal length) and M2 (15-mm focal length) was used to focus the pump beam on the ceramic rear surface and to produce a pump light footprint on the Yb:YAG of about 170 m in diameter. The laser spectrum was analyzed by using an optical spectrum analyzer (ANDO AQ6137) with resolution of 0.01 nm. Output beam profile of these lasers www.intechopen.com was monitored by using a CCD camera, and beam quality factor, M 2, was determined by measuring the beam diameters at different positions along the laser propagation direction. 3 shows a schematic diagram of experimental setup for passively Q-switched Yb:YAG microchip laser with Cr,Ca:YAG as saturable absorber. Two Yb:YAG samples are used as gain media, one is Yb:YAG ceramic doped with 9.8 at.% Yb, the other is -cut Yb:YAG crystal doped with 10 at.% Yb. The thickness of Yb:YAG samples is 1 mm, and the Yb:YAG samples are polished to plane-parallel. One surface of the gain medium was coated for antireflection at 940 nm and total reflection at 1.03 m acting as one cavity mirror. The other surface was coated for high transmission at 1.03 m. Two 1-mm-thick, uncoated Cr,Ca:YAG ceramic and -cut Cr,Ca:YAG crystal with 80% initial transmission, acting as Q-switch, was sandwiched between Yb:YAG sample and a 1.5-mm-thick, plane-parallel fused silica output coupler with 50% transmission. Total cavity length was 2 mm. The initial charge concentration of CaCO 3 and Cr 2 O 3 in growth of Cr,Ca:YAG crystal and fabrication of Cr,Ca:YAG ceramic are 0.2 at.% and 0.1 at.%, respectively. The absorption center of Cr,Ca:YAG sample centered at 1 m is also strongly affected by the annealing process and the exact concentration of this absorption center is difficult to determine, the concentration center of this absorption is roughly about 4% of the initial Cr doping concentration PM (Okhrimchuk & Shestakov 1994). Therefore, the initial transmission of the Cr,Ca:YAG saturable absorber is usually used in comparing the laser performance of passively Qswitched lasers. The initial transmission of Cr,Ca:YAG is governed by the doping concentration and the thickness of the sample, to fully compare laser performance with our previously passively Q-switched Yb:YAG/Cr,Ca:YAG all-ceramic microchip laser and the effect of polarization states on the passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers, 1-mm-thick Cr,Ca:YAG crystal with 80% initial transmission was used in the experiment. It should be noted that the polarization behavior keeps the same if a different modulation depth of Cr,Ca:YAG saturable absorber is used. A high-power fiber-coupled 940 nm laser diode with a core diameter of 100 m and numerical aperture of 0.22 was used as the pump source. Two lenses of 8-mm focal length were used to focus the pump beam on the Yb:YAG rear surface and to produce a pump light footprint on the Yb:YAG of about 100 m in diameter. The laser was operated at room temperature. The Q-switched pulse profiles were recorded by using a fiber-coupled InGaAs photodiode with a bandwidth of 16 GHz, and a 7 GHz Tektronix TDS7704B digital phosphor oscilloscope. The laser spectrum was analyzed by using an optical spectrum analyzer. The laser output beam profile was monitored using a CCD camera both in the near-field and the far-field of the output coupler. Fig. 4 shows the output power of miniature Yb:YAG ceramics and single-crystal lasers as a function of the absorbed pump power for different Yb concentrations and T oc. The absorbed pump power for reaching laser thresholds of Yb:YAG ceramics (C Yb = 9.8, 12, and 20 at.%) were 0.3, 0.33, and 0.64 W for T oc = 5% and 0.33, 0.5, 0.68 W for T oc = 10%. The pump power threshold increases with T oc and Yb concentration for Yb:YAG ceramic lasers. This was caused by the increase of the losses introduced by the large T oc and the increasing reabsorption of Yb 3+ at lasing wavelength with Yb concentrations. For Yb:YAG ceramics doped with different Yb concentrations, the output power increases linearly with absorbed pump power for T oc = 5 and 10%. The slope efficiencies respected to the absorbed pump power for Yb:YAG ceramics (C Yb = 9.8, 12, and 20 at.%) were measured to be 50, 55, and 45% for T oc = 5% and 52, 44, and 38% for T oc = 10%. Slope efficiency increases with T oc for 9.8 at.% Yb:YAG ceramic, however, the slope efficiencies decrease with T oc for Yb:YAG ceramics doped with 12 and 20 at.% Yb 3+ ions. Maximum output power of 2.54 W was measured for T oc = 5% by using 12 at.% Yb:YAG ceramic as gain medium when the absorbed pump power was 5.3 W. The corresponding optical-to-optical efficiency was about 48%. The absorbed pump power for reaching laser thresholds of Yb:YAG single-crystal (C Yb = 10, 15, and 20 at.%) were 0.3, 0.51 and 0.76 W for T oc = 5% and 0.35, 0.55, and 0.84 W for T oc = 10%. The absorbed pump power threshold increases with the T oc and Yb concentrations, the same tendency as that for Yb:YAG ceramics. However, the absorbed pump power thresholds of Yb:YAG single crystals were higher than those of Yb:YAG ceramics. This may be caused by the pump configuration used in the laser experiments and low pump power intensity with pump beam diameter of 170 m. Because the incident pump beam from laserdiode is several degrees away from the normal direction of the laser beam, there is a mismatch between the pump beam and laser beam. From Fig. 4 (b), we can see at low pump power just above absorbed pump power threshold, the laser performance is lower than that high pump power levels, this is normal for the quasi-three-level system; efficient laser performance can be achieved at high pump power density (Dong & Ueda 2005). However, for Yb:YAG ceramics, owing to the random distribution of Yb:YAG crystalline particles, the absorbed pump power threshold can be achieved more easily. Output power increases linearly with absorbed pump power for Yb:YAG single-crystals doped with 10 and 15 at.% Yb. The slope efficiencies of miniature lasers based on Yb:YAG single-crystals doped with 10 and 15 at.% Yb were measured to be 69, 62% for T oc = 5% and 67, 55% for T oc = 10%. The slope efficiencies of Yb:YAG crystals doped with 10 and 15 at.% Yb 3+ were higher than those for Yb:YAG ceramics although the pump power thresholds were higher than those of Yb;YAG ceramics. At higher pump power density, the inversion population excited by the pump beam is well-over the threshold, and the modes matched very well, therefore, the laser oscillates at high slope efficiency, especially for Yb:YAG crystal doped with 10 and 15 at.% Yb. The better laser performance of these crystals compared to their counterpart ceramic suggests that the intacavity loss for Yb:YAG crystal lower than that of Yb:YAG ceramics. For Yb:YAG single-crystal doped with 20 at.% Yb, the output power increases with the absorbed pump power, and tends to increase slowly when the absorbed pump power is higher than a certain value (e.g. 3 W for T oc = 5% and 2.3 W for T oc = 10%), as shown in Fig. 4(b). However, besides the higher absorbed pump power threshold compared to its counterpart Yb:YAG ceramic, the slope efficiencies (45% for T oc = 5% and 32 at.% for T oc = 10%) of 20 at.% Yb:YAG single crystal were lower than those (47% for T oc = 5% and 38 at.% for T oc = 10%) for its counterpart Yb:YAG ceramic. The laser results show that heavy doped Yb:YAG ceramic is better than its single crystal counterpart. The strong segregation of the impurities in Yb:YAG crystal with increase of the Yb concentration during crystal growth is the main reason for the worse laser performance. The other reasons for the less efficient laser operation may be the impurities increases with doping concentration (), the impurities induced concentration quenching effect limit the laser performance of highly doped Yb:YAG crystals. The green emission was observed in the Yb:YAG crystals and ceramics when they were pumped with laser-diodes, and visible intensity increases with Yb concentration up to 15 at.% and then decreases with Yb concentration (). Energy transfer from Yb 3+ ions to Er 3+ and Tm 3+ impurities and cooperative energy transfer between Yb 3+ ions are the causes of these visible luminescence. These are deleterious to the infrared laser operation. However, the distance between Yb 3+ ions and impurities or other quenching centers is decreased with Yb concentration, the cooperative luminescence intensity decreases because the excited ions are more easily quenched by reaching a neighboring defect site. Therefore, the effect of cooperative energy transfer is not a main factor to limit the laser performance of highly doped Yb:YAG crystals. 5 shows the optical-to-optical efficiencies of Yb:YAG lasers as a function of absorbed pump power. Under present laser experimental conditions, there is no saturation effect of Yb:YAG lasers with different output couplings for Yb concentration equal to or less than 15 at.% although the optical efficiency increases slowly with the absorbed pump power. However, for 20 at.% Yb:YAG, there is saturation effect for ceramic lasers with T oc = 5% and for single-crystal lasers with different output couplings. Maximum optical efficiency of 48% was achieved for Yb:YAG ceramic doped with 12 at.% Yb at the absorbed pump power of www.intechopen.com 5.3 W. For single crystal doped with 20 at.% Yb lasants, there is a maximum optical efficiency for all output couplings . The optical-to-optical efficiency decreases with further increase of the pump power. For Yb:YAG ceramics, except the comparable laser performance of 9.8 at.% Yb:YAG with T oc = 5 and 10%, the optical-tooptical efficiency decreases with T oc and Yb concentration. However, for Yb:YAG singlecrystals, the optical-to-optical efficiency decreases with the T oc and Yb concentration under different pump power levels. Optical-to-optical efficiency of Yb:YAG crystal doped with less than 15 at.% Yb is higher than that for Yb:YAG ceramics under certain pump power levels. For 20 at.% Yb:YAG, Yb:YAG ceramic has higher optical-to-optical efficiency than that of crystal under different pump power levels. The decrease of the optical-to-optical efficiency of Yb:YAG lasers with Yb concentration was attributed to the thick samples used for highly doped Yb:YAG samples. The better laser performance can be further improved through optimizing the thicknesses for Yb:YAG samples with different Yb concentrations. The highly efficient microchip lasers has been demonstrated by using the same crystals as those here used. Fig. 6 shows the maximum optical-to-optical efficiency under available pump power of Yb:YAG ceramics and single-crystals lasers as a function of Yb concentrations for different output couplings. For Yb:YAG single crystals, the maximum optical-to-optical efficiency decreases with Yb concentrations, there are 45% and 56% dropping for T oc = 5 and 10% when Yb concentration increases from 10 at.% to 20 at.%. However, for Yb:YAG ceramics, the maximum optical-to-optical efficiency decreases with Yb concentration, the decrease is smaller for Yb:YAG ceramics compared to that for Yb:YAG single crystal. There are 15 and 32% dropping for T oc = 5 and 10% when Yb concentration increases from 9.8 to 20 at.% for Yb:YAG ceramics. Because small different optical properties were observed in Yb:YAG ceramics and single-crystals doped with different Yb concentrations (;, the different laser performance of Yb:YAG ceramics and single-crystals may be caused by the Yb 3+ -ions distribution in YAG host and optical quality of Yb:YAG samples. Although the distribution coefficient of Yb in Yb:YAG is close to unit, there is still concentration gradient observed in Yb:YAG single crystals along the growth axis and radius of the crystal boule (). The Yb 3+ -ion distribution inhomogeneity in Yb:YAG single-crystal becomes server with Yb concentration. The impurities such as Ho 3+, Er 3+ increase with Yb concentration in Yb:YAG crystals because the strong segregation of rareearth ions in YAG crystal was observed. This was observed in the reduced radiative lifetime in highly doped Yb:YAG crystals (Sumida & Fan 1994;;). This concentration quenching effect limits the efficient laser performance of highly doped Yb:YAG crystals. For ceramics, the distribution of Yb ions in the grains and grain boundary is a main factor to determine the optical properties. The gain boundary of YAG ceramics was measured to be less than 0.5 nm (), and sintering temperature is about 200 o C lower than the melt point of Yb:YAG crystal, the segregation of Yb in grain boundary can only be achieved by diffusion or migration, therefore the distribution of Yb in gain and boundary should be close to homogeneous. When Yb ions were doped in YAG ceramics, the segregation of ytterbium ions in the grain boundary, accompanied by a reduction of the acoustic mismatch, leads to increased phonon transmission (). This will be further enhanced by introducing more ytterbium ions. This may be one of the main reasons for the better laser performance of heavy doped Yb:YAG ceramics compared to that of single-crystal with same doping levels. Continuous-wave Yb:YAG miniature lasers Yb concentration (at.%) Fig. 6. Comparison of the maximum optical-to-optical efficiency of Yb:YAG miniature lasers as a function of Yb concentration. The solid lines were used for illustration. Fig. 7 shows the comparison of the laser emitting spectra of 9.8 at.% Yb:YAG ceramic and 10 at.% Yb:YAG single-crystal miniature lasers under different absorbed pump power for T oc = 5, and 10%. Lasers operated at multi-longitudinal modes under different pump levels. The number of longitudinal modes increases with the absorbed pump power because the inversion population provided with pump power can overcome the threshold for low gain away from the highest emission peak of Yb:YAG gain medium. The longitudinal mode oscillation for these miniature Yb:YAG lasers was mainly caused by the etalon effect of plane-parallel Yb:YAG thin plate. The separation of longitudinal modes was measured to be 0.29 nm, which is in good agreement with the free spectral range (0.292 nm) of 1-mm-long cavity filled with gain medium predicted by (Koechner 1999) c = 2 /2L c, where L c is the optical length of the resonator and is the laser wavelength. And the center wavelength of the lasers shifts to longer wavelength with the pump power which is caused by the temperature dependent emission spectra of Yb:YAG crystal (). For T oc = 5%, both Yb:YAG ceramic and crystal lasers are oscillating at longer wavelength comparing to those for T oc = 10%. The cause of the wavelength shift to longer wavelength for T oc = 5% is relating to the change of the intracavity laser intensity () because only the intracavity laser intensity is different for both cases. Intracavity laser intensity for T oc = 5% is about two times higher than that for T oc = 10%, therefore, more longitudinal modes will also be excited for T oc = 5%. Because the better laser performance for 10 at.% Yb:YAG lasers compared to 9.8 at.% Yb:YAG ceramics lasers, the intracavity intensity is higher for crystal laser, therefore Yb:YAG crystal lasers oscillate at longer wavelength than those for Yb:YAG ceramics lasers, especially for T oc = 5%. Strong mode competition and mode hopping in these Yb:YAG ceramic lasers were also observed. When the laser oscillates, the excited Yb 3+ ions jump back to the lower laser level, they always relax to other even-lower energy levels or ground level, this process is rapid compare to the lifetime of Yb 3+ ion in YAG crystal or ceramics. The relaxation of Yb 3+ ions to the lower energy or ground levels causes the lowerlevel population to increase with the lasing intensity, this increases the reabsorption. This enhanced reabsorption provides a negative feedback process for the lasing modes and effective gain profile of Yb:YAG medium. This negative feedback process accompanied with the effects of strong mode competition makes some stronger laser modes eventually faded or quenched. When the intracavity light intensity is high enough, the population distribution at lower energy levels is changed dramatically. At the same time, the effective gain curve of Yb:YAG under lasing condition was altered by the strong reabsorption and temperature rise induced by the absorption pump power. Some initially suppressed modes at longer wavelength governed by the emission spectra can oscillate under changed gain curve, therefore the laser wavelength shifts to longer wavelength and mode hopping was observed. Fig. 8 shows the laser emitting spectra of 20 at% Yb:YAG ceramic and singlecrystal miniature lasers under different pump power levels and output couplings. The lasers oscillate at multi-longitudinal modes. The number of the longitudinal modes increases with the pump power. The laser oscillates at longer wavelength for 20 at.% Yb:YAG lasers compared to that for 10 at.% Yb:YAG lasers for both transmissions of the output couplers (as shown in Fig. 7 and Fig. 8). The red-shift of laser wavelength for T oc = 10% with Yb concentration is smaller than that for T oc = 5% because of the lower intracavity laser intensity Yb:YAG lasers with T oc = 10%. The number of longitudinal modes is larger for T oc = 5% than that for T oc = 10%. This may be related to the gain curve change due to the strong reabsorption under strong intracavity intensity. The output beam transverse intensity profiles were also monitored in all the pump power range. One example of the beam intensity profile at output power of 2.5 W for 12 at.% Yb:YAG ceramics with T oc = 5% was shown in Fig. 9, as well as a horizontal slice through the center. The output beam profile is close to TEM 00 mode. The measured spatial profile can be fitted with Gaussian function very well, as shown in Fig. 9(b). Near-diffraction-limited beam quality with M 2 of less than 1.1 was achieved in these miniature lasers with Yb:YAG ceramics and single-crystals as gain media in the available pump power range. 10 shows the typical polarization states of four combinations. Except for the random oscillation of Yb:YAG/Cr,Ca:YAG all-ceramics combination, other three combinations exhibit linearly polarization output. The extinction ratio of the linearly polarization is greater than 300:1. Some differences between the extinction ratios for different linearly polarization were observed. The extinction ratios of three different linearly polarized combinations are in the order of C1 > C4 > C3. The extinction ratios of three different linearly polarized combinations decrease a little with increase of the pump power, we did not observe significant decrease of the extinction ratio at the maximum pump power used here, this shows that the thermal effect under current available pump power is not strong enough to induce sufficient birefringence and depolarization for Yb:YAG crystals and ceramics. However, we did observe the thermal effect under high pump power level for cw Yb:YAG microchip lasers (), therefore, the thermal effect induced birefringence and depolarization should be considered in high power pumped passively Qswitched Yb:YAG/Cr,Ca:YAG microchip lasers. The different polarization states between all-ceramics combination and three others are due to the random distribution of nanocrystalline particles in ceramics. To fully understand the nature of polarization states in passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers, we measured the polarization states of Yb:YAG crystals and ceramics by removing Cr,Ca:YAG saturable absorber and found that Yb:YAG crystals oscillate at linearly polarization states selected by the crystalline-orientations in the plane () and Yb:YAG ceramic oscillates at unpolarization states. Although there is saturation absorption in Cr,Ca:YAG ceramic, the same as that for Cr,Ca:YAG crystal, owing to the random distribution of Cr,Ca:YAG particles in ceramic, the saturation absorption does not exhibit crystalline-orientation dependent anisotropic properties when the sample is rotated, which is different from the anisotropic saturation absorption of Cr,Ca:YAG crystal when the laser propagate along direction (). Therefore, the polarization states in passively Q-switched microchip lasers with Cr,Ca:YAG as saturable absorber are not only determined by the anisotropic saturation absorption of Cr,Ca:YAG saturable absorber, but also determined by the linearly polarized states of Yb:YAG crystals. The continuous-wave operation of Yb:YAG crystal and ceramic has been investigated previously by using different transmissions of output coupler and found that the laser performance 1-mm-thick Yb:YAG crystal doped with 10 at.% Yb is better than that of 1-mm-thick Yb:YAG ceramic doped with 9.8 at.% Yb. The absorbed pump power thresholds are 0.46 W and 0.54 W for 1-mm-thick Yb:YAG crystal and ceramic, respectively, the slope efficiencies were 49% and 44%, respectively by using 50% transmission of output coupler. The differences of cw laser performance between Yb:YAG crystal and ceramic suggest that the optical quality of ceramic used in the experiments is not as good as that of Yb:YAG crystal, and the slight different doping concentration may be another cause of the difference. Passively Q-switched Here we show the effect of different polarization states of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers on the laser performance. Average output power as a function of absorbed pump power for these four combinations of Yb:YAG and Cr,Ca:YAG microchip lasers was shown in Fig. 11. The absorbed pump power thresholds were about 0.53, 0.66, 0.75, and 0.6 W for combinations C1, C2, C3 and C4. The higher pump power threshold of these passively Q-switched lasers was due to the low initial transmission of Cr,Ca:YAG and high transmission of the output coupler used in the experiments. Average output power increases linearly with absorbed pump power for the four combinations, the slope efficiencies with respect to the absorbed pump power were estimated to be about 39, 36, 36 and 29% for the four combinations of C1, C2, C3 and C4, respectively. The best laser performance (low threshold and high slope efficiency) of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers was obtained with C1 combination because of the enhancement of linearly polarized laser operation due to the combination of linearly www.intechopen.com oscillation of Cr:YAG crystal under high intracavity laser intensity () and the crystalline-orientation selected linearly polarized states of Yb:YAG crystal (). Maximum average output power of 310 mw was obtained with Yb:YAG/Cr,Ca:YAG allcrystal combination when the absorbed pump power was 1.34 W, corresponding to opticalto-optical efficiency of 23%. The optical-to-optical efficiency is 15% with respect to the incident pump power for C1. The optical-to-optical efficiencies with respect to the incident pump power were measured to be 12, 11 and 11% for C2, C3 and C4 respectively. There is no coating damage occurrence with further increase of the pump power owing to decrease of the intracavity energy fluence by using high transmission output coupler. Although linearly polarized laser operation was observed in Yb:YAG/Cr,Ca:YAG combinations with at least one crystal, the effect of linearly polarized states on the laser performance was different. The slope efficiency of C4 is lower than that of C3, however the laser threshold of C4 is lower than that of C3 and the average output power is higher than that of C3 for all the available pump power range, as shown in Fig. 11. The contribution of polarization states from Cr,Ca:YAG crystal and Cr,Ca:YAG ceramic is different, when Cr,Ca:YAG crystal is used as saturable absorber, even with Yb:YAG ceramic as gain medium, the laser threshold is low. For all-ceramics combination, C2, although the laser threshold is higher than those of C1 and C4, the slope efficiency is better those of C4 and C3. These results show that the polarized states have great effect on the laser performance. Even with random polarized states of all-ceramics combination, passively Q-switched Yb:YAG/Cr,Ca:YAG laser has nearly the same laser performance as that of all-crystals combination. The discrepancies between all-crystals (C1) and all-ceramics (C2) combinations were caused by the optical quality of Yb:YAG crystal and Yb:YAG ceramic, the laser performance of Yb:YAG crystal is better than its ceramic counterpart. The discrepancies www.intechopen.com between C3 and C4 were attributed to the linearly polarization, with Cr,Ca:YAG crystal as saturable absorber, the extinction ratio of the polarization is stronger than that of with Cr,Ca:YAG ceramic as saturable absorber, the laser prefers to oscillate more efficiently with orientation selected anisotropic saturbable absorption of Cr,Ca:YAG crystal along <111> direction under high intracavity intensity (). The output beam profile is close to fundamental transverse electro-magnetic mode. Near diffraction-limited output beam quality with Owing to the broad emission spectrum of the Yb:YAG materials around 1.03 m (about 10 nm in FWHM), many longitudinal modes can be excited even for a 1-mm-thick Yb:YAG crystal. Microchip cw Yb:YAG lasers operate in a multi-longitudinal-mode over the whole pump power region. However, single-longitudinal-mode oscillation around 1029.7 nm was observed in passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers when the average output power was kept below 50 mW for different Yb:YAG/Cr,Ca:YAG combinations, the same as that for all-ceramics combinations. Above this value, the laser exhibited two-mode oscillation and three-mode oscillation. A typical example of single-longitudinal-mode and multi-longitudinal-mode oscillations of passively Q-switched Yb:YAG/Cr,Ca:YAG all-ceramic microchip laser under different average output power levels is shown in Fig. 12(a). The separation between first and second modes was measured to be 1.16 nm, which is eight times wider than the free spectral range between the longitudinal modes (0.146 nm) in the laser cavity filled with gain medium predicted by (Koechner 1999) c = 2 /2L c, where L c is the optical length of the resonator and is the laser wavelength. The separation between second and third modes was measured to be 0.3 nm, which is twice of that determined by the laser cavity. The potential output longitudinal modes were selected by the combined etalon effect of the 1mm-thick Cr,Ca:YAG as an intracavity etalon and 1.5-mm-thick fused silica output coupler as a resonant reflector (Koechner 1999). Fig. 12(b) shows the possible selected modes by the combining effect of 1-mm-thick Cr 4+ :YAG and 1.5-mm-thick fused silica. The resonant modes, eight times of free spectral range (0.146 nm) away from the main mode centered at 1029.7 nm, will oscillate preferably because the wavelengths of these modes are very close to the high transmittance of the combined transmittance product. The resonant mode will oscillate at 1030.87 nm due to the asymmetric gain profile centered at 1029.7 nm of Yb:YAG. At high pump power levels, besides the oscillation of the main mode depleting the inversion population and suppressing the oscillation of the resonant modes close to it, the local temperature rise induced by the pump power will change the transmittance of the etalons. The relative gain and loss for different resonant modes will vary and determine the appearance of the third mode and elimination of the second mode. The linewidth of each mode was less than 0.02 nm, limited by the resolution of optical spectra analyzer. The central wavelength of 1029.7 nm shifts to longer wavelength with pump power, which is caused by the temperature dependent emission spectrum of Yb:YAG crystal (). Therefore, stable single-longitudinal-mode oscillation can be maintained by increasing pump beam diameter incident on the laser medium at higher pump power. The polarization states of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers have great effect on the characteristics of the output pulses. Fig. 13 shows the pulse characteristics (pulse repetition rate, pulse width, pulse energy and pulse peak power) of passively Qswitched Yb:YAG/Cr,Ca:YAG microchip lasers as a function of absorbed pump power. For all four combinations of Yb:YAG and Cr,Ca:YAG, the repetition rate of passively Qswitched laser increases linearly with the absorbed pump power. Pulse width (FWHM) of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers decreases with absorbed pump power at low pump power levels and tends to keep constant at high pump power levels. The shortest pulse width of 277 ps was achieved with C4 combination. Pulse widths for the four combinations are in the order of C4 < C1 < C2 < C3. Pulse energy increases with absorbed pump power and tends to keep constant at high pump power levels. The highest pulse energy was achieved with C1 combination. The pulse energy for the four combinations are in the order of C1 > C4 > C2 > C3. Peak power of passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers exhibits the same tendency as those of pulse energy: C1 > C4 > C2 > C3 for the four combinations. Therefore, the overall best laser performance (highest peak power) in passively Q-switched Yb:YAG/Cr,Ca:YAG microchip lasers achieved by using C1 combination. Linearly polarization operation of passively Q-switched all-crystals lasers is more favorable for laser performance. The combination of Yb:YAG/Cr,Ca:YAG microchip lasers with Cr,Ca:YAG crystal as saturable absorber, C4, has better laser pulse characteristics than those of all-ceramics combination, C2 and combination C3. Although linearly polarized state was achieved in combination C3 with Yb:YAG crystal, the linearly polarized states was attributed to the linearly polarization of Yb:YAG crystal, not from the Cr,Ca:YAG ceramic. The contribution of the linearly polarized state from Yb:YAG crystal in C3 combination is less than that from the nonlinear anisotropic absorption of Cr,Ca:YAG crystal, therefore, therefore, the laser performance of combination C3 is less than those of combination C1 and C4. The effect of depolarization effect on the polarization states observed in Yb:YAG crystal () may be another cause to less efficient laser operation in C3 combination at high pump power levels. Conclusions In conclusion, systematic comparison of laser performance was done for Yb:YAG ceramics and single-crystals doped with different concentrations. Although the pump power thresholds of Yb:YAG crystals were higher than their ceramics counterparts due to the pump configuration, the efficient laser operation was obtained by using both Yb;YAG ceramics and single-crystals. The laser performance of 1-mm-thick Yb:YAG ceramics and crystals becomes worse with Yb concentration under present miniature laser configuration. However, the laser performance of Yb:YAG crystals is more sensitive to the Yb concentrations, while the laser performance of Yb:YAG ceramics is less sensitive to the Yb concentrations. The laser performance of low doping Yb:YAG ceramics is worse than those obtaining from Yb:YAG singly crystals. The laser performance of 20 at.% Yb:YAG ceramics is better than its counterpart single crystal. Both Yb:YAG ceramics and crystals miniature lasers oscillate at multi-longitudinal modes, the number of longitudinal-mode increases with absorbed pump power. Strong mode competition and mode hopping were observed in these Yb:YAG lasers. The strong reabsorption and gain curve change under high intracavity laser intensity play important roles on the red-shift of the output laser wavelength. High beam quality lasers with M 2 less than 1.1 were achieved by adopting Yb:YAG ceramics and crystals as gain media. Heavy-doped Yb:YAG ceramic will be a potential candidate for microchip lasers by optimizing the thickness and Yb 3+ concentration. Random polarized oscillation was observed in passively Q-switched Yb:YAG/Cr,Ca:YAG all-ceramic microchip laser while linearly polarized oscillations were observed with at lease one crystal in the Yb:YAG/Cr,Ca:YAG combinations. The polarization states in passively Qswitched Yb:YAG/Cr,Ca:YAG microchip lasers show that the linearly polarization states in passively Q-switched laser are not only resulted from the anisotropic saturation absorption of Cr,Ca:YAG crystal, but also from linearly polarization states of Yb:YAG crystal. High peak power pulses with sub-nanosecond pulse-width and nearly diffraction-limited beam quality were obtained in these lasers. The best laser performance was achieved by using Yb:YAG crystal as gain medium and Cr,Ca:YAG crystal as saturable absorber because of the enhancement of linearly polarized state due to the crystalline-orientation selected polarized states of Yb:YAG crystal and linearly polarized oscillation of Cr,Ca:YAG crystal under high intracavity laser intensity. Other combinations of Yb:YAG and Cr,Ca:YAG have less efficient linearly polarized laser oscillation and also affect the laser performance of passively Qswitched Yb:YAG/Cr,Ca:YAG microchip lasers.
FPGA-based real-time simulation of fault tolerant current controllers for power electronics This paper investigates a FPGA-based Real-Time Simulation of Fault Tolerant Current Controllers (FTCC) algorithm for three phase inverter fed electrical systems. The focus of the proposed method is on the identification of the faulty current sensor in AC machines drives and the actual reconfiguration between two control-sampling times which ensures a safety continuous working of the faulty system. For performances verification, the method is analyzed within a FPGA-based Real-Time Simulator (RTS) of the studied electrical system, based on criteria such as accuracy, execution speed and implementation complexity. For the RTS modeling process, a multi-sampling approach is adopted allowing a real-time functioning with different time-steps. ModelSim simulations and experimental results are presented to emphasize the effectiveness of the proposed method.
<reponame>Zuowei-ZHANG/DCNN<filename>cnn_models/vggmodel.py import torch.nn as nn import torch class VGG(nn.Module): def __init__(self, features, num_classes=5, init_weights=False): super(VGG, self).__init__() self.features = features #32:1 128:4 224:7 self.classifier1 = nn.Sequential( nn.Dropout(p=0.5), nn.Linear(512*1*1, 4096), #32*32 nn.ReLU(True), nn.Dropout(p=0.5), nn.Linear(4096, 4096), nn.ReLU(True), nn.Linear(4096, num_classes) ) self.classifier4 = nn.Sequential( nn.Dropout(p=0.5), nn.Linear(512*4*4, 4096), #128*128 nn.ReLU(True), nn.Dropout(p=0.5), nn.Linear(4096, 4096), nn.ReLU(True), nn.Linear(4096, num_classes) ) self.classifier7 = nn.Sequential( nn.Dropout(p=0.5), nn.Linear(512*7*7, 4096), #224*224 nn.ReLU(True), nn.Dropout(p=0.5), nn.Linear(4096, 4096), nn.ReLU(True), nn.Linear(4096, num_classes) ) if init_weights: self._initialize_weights() def forward(self, x): # N x 3 x 224 x 224 if torch.cuda.is_available(): x = self.features(x.type(torch.cuda.FloatTensor)) else: x = self.features(x) size=list(x.size())[-1] # N x 512 x size x size x = torch.flatten(x, start_dim=1) # N x 512*size*size if size==1: x = self.classifier1(x) if size==4: x = self.classifier4(x) if size==7: x = self.classifier7(x) return x def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') #nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) # nn.init.normal_(m.weight, 0, 0.01) nn.init.constant_(m.bias, 0) def make_features(cfg: list): layers = [] in_channels = 3 for v in cfg: if v == "M": layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) layers += [conv2d, nn.ReLU(True)] in_channels = v return nn.Sequential(*layers) cfgs = { 'VGG11': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG13': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], } def vgg(model_name="VGG16", **kwargs): try: cfg = cfgs[model_name] except: print("Warning: model number {} not in cfgs dict!".format(model_name)) exit(-1) model = VGG(make_features(cfg), **kwargs) return model
Heavy rain and high winds will sweep across the country this weekend, but forecasters say they do not expect the weather to fizzle out firework displays. Today will see a soggy start for most but the rain is expected to clear by the evening, while tomorrow will again be damp, particularly across Scotland. There will be a risk of thunder in places but the Met Office is yet to confirm whether the storms will be potent enough to be the first to bear a human name. The Met Office say most of the rain in the north-east should clear in time for fireworks shows across the region, however it will be a cold one with temperatures set to drop to as low as 1C in places. A Met Office spokesman said: “The last of any rain will clear east to leave a dry night with clear periods. (It is) a colder night than last night with a touch of frost in rural spots sheltered from the strengthening southwesterly wind. “Sunday (will be a) dry, bright morning but turning cloudy. Rain will spread northwards from late morning, heaviest over southern Aberdeenshire. Strong southerly winds reaching gale force, turning westerly later. Maximum Temperature 14°C. John Griffiths, a forecaster for MeteoGroup, said: “There is a big band of rain that’s pushing across the country north and east today. It will be quite heavy rain in place and there is a risk of thunder and fairly strong winds. “There could be gusts of up to 55mph or 60mph in really exposed areas. Snowdon, parts of Cornwall and the west coast could see the highest gusts. It could gust up to 40mph in London which is quite strong for that area. Tomorrow, winds could reach up 70mph in coastal areas of Scotland, he added. “There is another big band of rain that will mainly affect northern England and Scotland. Again it will be quite heavy and there is a risk of thunder. The Met Office said the temperatures on Saturday would peak around 17C during the day and fall to around 7C at night. In September, the Met Office and Met Eireann announced a pilot project to name storms that may be blowing this way this autumn and winter and were inundated with public responses. The winning names included Abigail, Barney, Clodagh, Desmond, Eva and Frank. A storm will be named when it is deemed to have the potential to cause a substantial impact in the UK and/or Ireland.
/** * Generates a Householder transformation from within the part of column c * of a Zmat (altered) extending from rows r1 to r2. The method overwrites * the column with the result of applying the transformation. * * @param A * The matrix from which the transformation is to be generated * (altered) * @param r1 * The index of the row in which the generating column begins * @param r2 * The index of the row in which the generating column ends * @param c * The index of the generating column * @return A Z1 of length r2-r1+1 containing the Householder vector * @exception ZException if anything goes wrong */ public static Z1 genc(Zmat A, int r1, int r2, int c) throws ZException { int i, ru; double norm; double s; Z scale; Z t = new Z(); Z t1 = new Z(); c = c - 1; r1 = r1 - 1; r2 = r2 - 1; ru = r2 - r1 + 1; Z1 u = new Z1(r2 - r1 + 1); for (i = r1; i <= r2; i++) { u.put(i - r1, A.re(i, c), A.im(i, c)); A.setRe(i, c, 0.0); A.setIm(i, c, 0.0); } norm = Norm.fro(u); if (r1 == r2 || norm == 0.0) { A.setRe(r1, c, -u.re[0]); A.setIm(r1, c, -u.im[0]); u.put(0, 1.4142135623730951, 0.0); return u; } scale = new Z(1 / norm, 0.0); if (u.re[0] != 0.0 || u.im[0] != 0.0) { t = u.get(0); scale.times(scale, t.div(t1.conj(t), Z.abs(t))); } A.put(r1 + 1, c + 1, t.minus(t.div(Z.ONE, scale))); for (i = 0; i < ru; i++) { u.times(i, scale); } u.re[0] = u.re[0] + 1.0; u.im[0] = 0.0; s = Math.sqrt(1.0 / u.re[0]); for (i = 0; i < ru; i++) { u.re[i] = s * u.re[i]; u.im[i] = s * u.im[i]; } return u; }
Fibroblast growth factor 21, adiposity, and macronutrient balance in a healthy, pregnant population with overweight and obesity ABSTRACT Aim of the study: The regulation and actions of fibroblast growth factor 21 (FGF21) are responsive to energy status and macronutrient balance, and investigations of FGF21 in normal pregnancy, which could be informative for FGF21 biology, are seldom. The goal of our study was to examine FGF21 levels in a contemporary healthy, pregnant population. Methods: We phenotyped 43 women with overweight and obesity during pregnancy for weight, body composition, and fasting blood. Serum FGF21 was measured during the first and third trimesters. Placentas were collected at delivery. Results: Maternal FGF21 concentrations were positively correlated with body mass index and adiposity, but not lean mass or glucose homeostasis. FGF21 concentrations significantly increased from the first to third trimester of pregnancy (0.105 vs. 0.256 ng/mL, p < 0.0001). Changes in FGF21 concentrations across pregnancy were not associated with changes in body weight or composition but inversely with the change in fasting glucose. FGF21 mRNA levels in placenta were very low and do not likely contribute to FGF21 in the maternal circulation. Conclusions: FGF21 increases throughout pregnancy in our healthy cohort with overweight and obesity, independent of the placenta, and does not appear to be sensing the changes in energy balance (reflected in the change in maternal energy stores), but changes in macronutrient status. Thus, we propose FGF21 may be a potential signal of maternal nutrient status in pregnancy.
#pragma GCC optimize ("O3") #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N = 2e5 + 5; const int mod = 1e9 + 7; struct Matrix { vector<vector<int>> mat; int n, m; Matrix(vector<vector<int>> val): mat(val), n(val.size()), m(val[0].size()){} static Matrix identify_matrix(int n) { vector<vector<int>> iden(n, vector<int>(n, 0)); for(int i = 0;i < n;i++) iden[i][i] = 1; return iden; } Matrix operator *(const Matrix &other) const { vector<vector<int>> res (n, vector<int>(other.m, 0)); for(int i = 0;i < n;i++) for(int j = 0;j < other.m;j++) for(int k = 0;k < m;k++) res[i][j] = (res[i][j] + (1ll * mat[i][k] * other.mat[k][j]) % mod) % mod; return res; } inline bool is_square() const { return n == m; } }; Matrix fp(Matrix x, ll y) { if(y == 0) return Matrix::identify_matrix(x.n); Matrix res = fp(x, y >> 1); res = res * res; if(y & 1) res = res * x; return res; } ll n; int m; int main() { ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); cin >> n >> m; vector<vector<int>> a(1, vector<int>(m, 1)); vector<vector<int>> v(m, vector<int>(m, 0)); for(int i = 0, j = 1;j < m;i++, j++) v[i][j] = 1; v[0][0] = v[m - 1][0] = 1; Matrix A(a), M(v); if(n < m) return cout << a[0][n], 0 ; Matrix ans = A * fp(M, n - m + 1); cout << ans.mat[0][0]; return 0; }
A 100-Year Review: Practical female reproductive management. Basic knowledge of mechanisms controlling reproductive processes in mammals was limited in the early 20th century. Discoveries of physiologic processes and mechanisms made early in the last century laid the foundation to develop technologies and programs used today to manage and control reproduction in dairy cattle. Beyond advances made in understanding of gonadotropic support and control of ovarian and uterine functions in basic reproductive biology, advancements made in artificial insemination (AI) and genetics facilitated rapid genetic progress of economically important traits in dairy cattle. Technologies associated with management have each contributed to the evolution of reproductive management, including hormones to induce estrus and ovulation to facilitate AI programs; pregnancy diagnosis via ultrasonography or by measuring conceptus-derived pregnancy-associated glycoproteins; estrus-detection aids first devised for monitoring only physical activity but that now also quantitate feeding, resting, and rumination times, and ear temperature; sex-sorted semen; computers and computerized record software packages; handheld devices for tracking cow location and retrieving cow records; and genomics for increasing genetic progress of reproductive and other economically important traits. Because of genetic progress in milk yield and component traits, the dairy population in the United States has been stable since the mid 1990s, with approximately 9 to 9.5 million cows. Therefore, many of these technologies and changes in management have been developed in the face of increasing herd size (4-fold since 1990), and changes from pastoral or dry-lot dairies to increased housing of cows in confinement buildings with freestalls and feed-line lockups. Management of groups of "like" cows has become equally important as management of the one. Management teams, including owner-managers, herdsmen, AI representatives, milkers, and numerous consultants dealing with health, feeding, and facilities, became essential to develop working protocols, monitor training and day-to-day chores, and evaluate current trends and revenues. Good management teams inspect and follow through with what is routinely expected of workers. As herd size will undoubtedly increase in the future, practical reproductive management must evolve to adapt to the new technologies that may find more herds being milked robotically and applying technologies not yet conceived or introduced.
/// <reference path='fourslash.ts' /> // @noImplicitAny: true ////function foo([|a, m, x |]) { //// a.b.c; //// //// var numeric = 0; //// numeric = m.n(); //// //// x.y.z //// x.y.z.push(0); //// return x.y.z ////} verify.rangeAfterCodeFix("a: { b: { c: any; }; }, m: { n: () => number; }, x: { y: { z: number[]; }; }", /*includeWhiteSpace*/ undefined, /*errorCode*/ undefined, /*index*/0);
Time Spent Eating, by Immigrant Status, Race/Ethnicity, and Length of Residence in the United States Introduction Time spent eating is associated with obesity and diet-related diseases. We examined the association between time adults spent eating, immigrant status, race/ethnicity, and race/ethnicity among adults in the United States. Methods We used multivariate linear regression to analyze a cross-sectional, nationally representative sample of respondents aged 19 years or older (N = 192,486) from the 2016 American Time Use Survey. The outcome measures were time spent per day on primary eating and drinking and secondary eating. The predictors were immigrant status, race/ethnicity, and years spent living in the United States. Results Multivariate adjusted minutes per day spent on primary eating and drinking were 66.4 for noncitizens, 66.5 for naturalized citizens, and 60.1 for US-born individuals. Multivariate adjusted minutes per day spent on secondary eating were 11.1 for noncitizens, 12.2 for naturalized citizens, and 12.9 for US-born individuals. Minutes per day spent on primary eating and drinking for immigrants by length of residence in the United States was 69.7 minutes for 5 years or less of residence, 67.9 minutes for 6 to 10 years of residence, 63.6 minutes for 11 to 15 years of residence, and 63.6 minutes for more than 15 years of residence. Minutes per day spent on secondary eating for immigrants by length of residence was 5.5 minutes for 5 years or less of residence, 9.7 minutes for 6 to 10 years of residence, 8.4 minutes for 11 to 15 years of residence, and 12.6 minutes for more than 15 years of residence. Conclusion Time spent eating varied by immigrant status and length of residence in the United States. Introduction Time spent eating is associated with obesity and diet-related diseases. An emerging literature suggests several likely pathways in which time spent preparing and eating meals and snacks affects diet quality and energy intake. Meals prepared in the home from scratch tend to have fewer calories and to be generally more nutritious than processed foods and food eaten away from home (eg, restaurant meals). The context in which meals are eaten also matters. Eating while engaging in sedentary behavior such as television viewing has been linked to higher calorie consumption and weight gain. Collectively, data from time use diaries suggest a trend over time toward more pre-prepared or semi-prepared foods and less time eating and drinking but that the association is modified by demographic characteristics, such as race/ethnicity 12). Racial/ethnic disparities in obesity have been linked to time used in meal preparation, food consumption, and snacking during sedentary behavior. Evidence from intervention studies suggests that culturally tailored approaches are more effective at improving nutrition behaviors and improved health outcomes. Obesity risk increases with acculturation and time spent in the United States. Although the dietary patterns of immigrants are nuanced and vary by subgroup, studies have generally found that acculturation and time spent in the United States are negatively associated with diet quality and positively associated with energy intake and consumption of processed foods. Much of the literature investigating the link between acculturation, diet, and obesity has focused on the roles of obesogenic environments. An understudied but possible mechanism to explain the change in diets of immigrants and their offspring during the acculturation process and in increasing time spent in the United States is changes in meal preparation and consumption patterns. Specifically, immigrants may shift toward patterns characterized by less time spent with meal preparation of fresh foods and faster consumption times from pre-prepared or processed foods. Our objective was to understand the association between time spent eating, immigrant status, and race/ethnicity among adults in the United States. Time spent eating was defined by primary eating and drinking, and secondary eating. Primary eating time was defined as time spent on shopping, meal preparation, and consumption of food as the primary activity. Secondary eating was defined as time spent eating while engaged in another activity, such as a sedentary behavior like watching television. Based on the literature of obesity, food behavior, and time use, we hypothesized that acculturation of immigrants would be negatively associated with primary eating time and positively associated with secondary eating time. We also hypothesized that we would find differences in eating time by immigrant status and race/ethnicity. Methods We used cross-sectional, nationally representative data from the 2016 American Time Use Survey (ATUS) provided by the University of Minnesota's Integrated Public Use Microdata Series. ATUS is a time diary telephone survey of the United States that asks 1 noninstitutionalized respondent aged 15 years or older from each sampled household to provide detailed information on the time spent on various activities in a 24-hour period from 4:00 AM the day before the interview to 4:00 AM of the interview day. The ATUS sample is drawn from households that completed the Current Population Survey interview fielded by the US Census Bureau; data include time diary, demographic, labor force participation, and household information. More details about ATUS, including the user's guide, questionnaire, and list of published research papers, can be found on the US Bureau of Labor Statistics website. We used the most recent data available from the ATUS Eating and Health Module, which is collected periodically and sponsored by the Economic Research Service of the US Department of Agriculture. The Eating and Health Module adds supplemental questions to ATUS such as time spent eating and drinking, grocery shopping and fast food purchase, meal preparation, food sufficiency, food assistance, height, weight, general health, and exercise. Sample weights supplied by the US Census Bureau and applied to the individual ATUS and Eating and Health Module respondent data produced nationally representative estimates for an average day in 2016. After listwise deletion of 6,356 respondents with missing data, the final analytic sample size was 192,486 adults aged 19 years or older with complete information on all study variables. The outcome measures were time spent per day in primary eating and drinking and time spent per day in secondary eating measured in minutes. Generally, primary eating and drinking time is the total amount of time during the diary day that the respondent spent in primary eating and drinking, which includes shopping, meal preparation, and meal consumption. This variable is calculated by summing the amount of time in minutes the respondent spent in eating and drinking as a primary activity. Secondary eating is eating that occurred during a primary activity and is calculated as the sum of all time in minutes during the diary day that the respondent spent in secondary eating. The specific question text for primary and secondary eating was as follows: "We're interested in finding out more about how people fit meals and snacks into their schedules. Yesterday, you reported eating or drinking between . Were there any other times you were eating yesterday -for example, while you were doing something else? About how long would you say you were eating while you were ?" The continuous measurement for these outcomes was truncated at 121 minutes per day to normalize the distribution. We used multivariate linear regression models because the outcome measure was measured continuously as minutes per day. We calculated the predicted average number of minutes spent per day in primary and secondary eating by immigrant status and race/ethnicity. All analyses were conducted using Stata version 16 (Stata-Corp LLC) and accounted for survey weights and complex survey design to produce nationally representative estimates. We set 2sided significance at P <.05. We found differences in the proportion of racial/ethnic identification by immigrant status. Among US-born respondents, 77.3% reported their race/ethnicity as White, non-Hispanic; 9.0% reported Hispanic ethnicity; 10.8% reported their race/ethnicity as Black, non-Hispanic; 1.1% reported their race/ethnicity as Asian, non-Hispanic; and 1.7% reported their race/ethnicity as other non-Hispanic race/ethnicity. Among naturalized citizens, 24.8% reported their race/ethnicity as White, non-Hispanic; 36.9% reported Hispanic ethnicity; 15.9% reported their race/ethnicity as Black, non-Hispanic; 21.5% reported their race/ethnicity as Asian, non-Hispanic; and 0.8% reported their race/ethnicity as other non-Hispanic race/ethnicity. Among noncitizens, 14.5% reported their race/ethnicity as White, non-Hispanic; 58.8% reported Hispanic ethnicity; 7.0% reported their race/ethnicity as Black, non-Hispanic; 18.6% reported their race/ethnicity as Asian, non-Hispanic; and 1.0% reported their race/ethnicity as other non-Hispanic race/ethnicity. The average time spent in a day in 2016 on primary eating and drinking was 60.2 minutes for US-born respondents, 67.3 minutes for naturalized citizens, and 64.5 minutes for noncitizens. (The detailed, unadjusted relationship between the outcome measures and immigrant status and race/ethnicity are available on request from the corresponding author.) Results of multivariate linear regression for primary eating and drinking and secondary eating time per day indicated that noncitizens spent, on average, 66.4 minutes (95% CI, 65.6-67.2) compared with 66.5 minutes (95% CI, 65.5-67.4) for naturalized citizens and 60.1 minutes (95% CI, 59.9-60.3) for US-born respondents (Table 2). We found a significant difference in primary eating and drinking time between noncitizens and US-born respondents and between naturalized citizens and US-born respondents. However, we did not find a significant difference between noncitizens and naturalized citizens in primary eating and drinking time. Although the magnitude varied, the pattern of results for the racial/ ethnic identification of immigrants was consistent across immigrant status. Asian non-Hispanic immigrants spent the most time on primary eating and drinking, followed by immigrants who were White, non-Hispanic; Hispanic; other non-Hispanic race/ethnicity; and Black, non-Hispanic. For secondary eating time, noncitizens spent, on average, 11.1 minutes (95% CI, 10.4-11.8) per day compared with 12.2 minutes (95% CI, 11.6-12.8) for naturalized citizens and 12.9 minutes (95% CI, 12.7-13.0) for US-born respondents. We found a significant difference in secondary eating time between noncitizens and US-born respondents but found no significant difference between noncitizens and naturalized citizens or between US-born respondents and naturalized citizens. We found few significant differences by immigrant status and race/ethnicity for secondary eating time. Among US-born respondents and naturalized citizens, Asian non-Hispanic immigrants spent less secondary eating time per day than immigrants who reported other non-Hispanic race/ethnicity. Among noncitizens, we found no significant differences by race/ethnicity for secondary eating time. Results from multivariate linear regression indicated that immigrants who had lived in the United States 5 years or less spent 69.7 (95% CI, 68.1-71.3) minutes per day in primary eating and drinking time, those who lived in the United States for 6 to 10 years spent 67.9 (95% CI, 66.4-69.3) minutes, those who lived in the United States for 11 to 15 years spent 63.6 (95% CI, 62.1-65.1) minutes, and those who lived in the United States for more than 15 years spent 63.6 (95% CI, 63.0-64.2) minutes (Table 3) www.cdc.gov/pcd/issues/2020/20_0122.htm Centers for Disease Control and Prevention fore, we found a difference of 6 minutes per day between immigrants who had lived in the United States 5 years or less and immigrants who had lived in the US for at least 15 years, which when assessed cumulatively results in an approximately 180-minute-permonth difference in primary eating time. For time per day spent in secondary eating, immigrants who lived in the United States for 5 years or less spent 5.5 (95% CI, 4.8-6.3) minutes, those who lived in the United States for 6 to 10 years spent 9.7 (95% CI, 8.7-10.7) minutes, those who lived in the United States for 11 to 15 years spent 8.4 (95% CI, 7.7-9.1) minutes, and those who lived in the United States more than 15 years spent 12.6 (95% CI, 12.2-13.1) minutes. (Full results from the regression analysis are available on request from the corresponding author.) Discussion We examined the association between time spent in primary and secondary eating and immigrant status, race/ethnicity, and years lived in the United States and found that noncitizens spent more time per day in primary eating and less time per day in secondary eating than US-born individuals. We also found that years lived in the United States was negatively associated with time spent eating and drinking. The pattern of results for race/ethnicity and primary eating time was consistent across immigrant status. Asian non-Hispanic immigrants spent the most time on primary eating and drinking, followed by White non-Hispanic, Hispanic, other race/ ethnicity, and Black non-Hispanic respondents. We found limited significant differences in time spent eating by immigrant status and race/ethnicity. Naturalized citizens and US-born respondents who reported their race/ethnicity as Asian, non-Hispanic spent less time in secondary eating compared with other racial/ethnic immigrant groups. However, we found no significant differences to report by race/ethnicity for secondary eating time among noncitizen immigrants. Acculturation has been measured by citizenship, language, and years spent in the United States, all of which are associated with health behaviors 29). Moreover, more time spent in the United States is associated with better access to health care and lower health care use, which may further exacerbate health disparities related to acculturation for recently arrived immigrants. Immigrants may adopt mainstream American health behaviors over time, gradually emulating behaviors of US-born individuals. For example, a higher number of years living in the United States among immigrants has been associated with a decline in consumption of healthy foods such as fruits and vegetables. This decline in consumption has also been linked to language use in the home, with ethnic groups that speak mostly English at home consuming more energy-dense, nonhomemade meals compared with groups that speak the language from their country of origin at home. The mounting evidence suggests that US culture may influence immigrants to adopt unhealthy behaviors and, by extension, be at greater risk of chronic disease. Our study has limitations. Although time diaries have been validated as a measure for time use and the American Time Use Survey is widely used as a source of information on how people spend their time, this measure is limited to a given 24-hour period; if the time diary was collected at a different point, the activities of the person surveyed may differ. Moreover, time diaries are cross-sectional, self-reported data rather than directly measured data of a prospective cohort. ATUS data did not include geographic identifiers to link them to states and counties, which would have enabled us to control for state or county characteristics, an important contextual variable to consider when measuring health effects. Another limitation is that the data did not include a measure on language, which is a well-established measure of acculturation. Finally, the data are a diary of time use rather than a detailed food diary, which may have been helpful for interpreting the time spent in primary and secondary eating time. In conclusion, we found that time spent eating varied by immigrant status and length of residence in the United States. We found limited support for the hypothesis that differences in eating time by immigrant status and race/ethnicity would exist. Immigrants may be shifting toward eating behavior that is characterized by less time spent food shopping, preparing meals, and food consumption as a primary activity and more time spent eating while engaged in other activities such as watching television. Future research should assess randomized controlled interventions that use culturally tailored approaches for immigrants to increase time spent in meal preparation and consumption of freshly prepared foods and reduce time spent in secondary eating of pre-prepared or processed foods. Nutrition and diet-related interventions should tailor interventions by years lived in the United States and the race/ethnicity of immigrant groups. Public health policy and programs should address the negative impact that acculturation has on eating behaviors and the heightened risk for obesity and other dietrelated diseases in the United States.
package org.lanjerry.admin.service.sys.impl; import java.util.List; import org.lanjerry.admin.dto.sys.SysRolePageDTO; import org.lanjerry.admin.dto.sys.SysRoleSaveOrUpdateDTO; import org.lanjerry.admin.mapper.sys.SysPermissionMapper; import org.lanjerry.admin.mapper.sys.SysRoleMapper; import org.lanjerry.admin.service.sys.SysPermissionService; import org.lanjerry.admin.service.sys.SysRolePermissionService; import org.lanjerry.admin.service.sys.SysRoleService; import org.lanjerry.admin.util.AdminConsts; import org.lanjerry.admin.util.CacheUtil; import org.lanjerry.admin.vo.sys.SysRoleInfoVO; import org.lanjerry.admin.vo.sys.SysRolePageVO; import org.lanjerry.admin.vo.sys.SysUserRoleVO; import org.lanjerry.common.core.entity.sys.SysPermission; import org.lanjerry.common.core.entity.sys.SysRole; import org.lanjerry.common.core.entity.sys.SysRolePermission; import org.lanjerry.common.core.enums.sys.SysPermissionTypeEnum; import org.lanjerry.common.core.util.ApiAssert; import org.lanjerry.common.core.util.BeanCopyUtil; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.util.StrUtil; import lombok.AllArgsConstructor; /** * <p> * 系统角色表 服务实现类 * </p> * * @author lanjerry * @since 2019-09-03 */ @Service @AllArgsConstructor public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { private final SysPermissionService permissionService; private final SysRolePermissionService rolePermissionService; @Override public IPage<SysRolePageVO> pageRoles(SysRolePageDTO dto) { IPage<SysRole> page = this.lambdaQuery().orderByDesc(SysRole::getId) .eq(dto.getId() != null, SysRole::getId, dto.getId()) .like(StrUtil.isNotBlank(dto.getName()), SysRole::getName, dto.getName()) .like(StrUtil.isNotBlank(dto.getPermissionTag()), SysRole::getPermissionTag, dto.getName()) .ge(StrUtil.isNotBlank(dto.getCreatedTimeStart()), SysRole::getCreatedTime, dto.getCreatedTimeStart() + AdminConsts.START_TIME) .le(StrUtil.isNotBlank(dto.getCreatedTimeEnd()), SysRole::getCreatedTime, dto.getCreatedTimeEnd() + AdminConsts.END_TIME) .page(new Page<>(dto.getPageNum(), dto.getPageSize())); return BeanCopyUtil.pageCopy(page, SysRole.class, SysRolePageVO.class); } @Override @Transactional(rollbackFor = Exception.class) public void saveRole(SysRoleSaveOrUpdateDTO dto) { ApiAssert.isTrue(this.count(Wrappers.<SysRole>lambdaQuery().eq(SysRole::getName, dto.getName())) == 0, String.format("名称:%s已存在", dto.getName())); SysRole role = BeanCopyUtil.beanCopy(dto, SysRole.class); this.save(role); // 新增角色权限 this.updateRolePermission(role.getId(), dto.getPermissionIds()); } @Override @Transactional(rollbackFor = Exception.class) public void updateRole(int id, SysRoleSaveOrUpdateDTO dto) { SysRole oriRole = this.getById(id); ApiAssert.notNull(oriRole, String.format("角色编号:%s不存在", id)); SysRole role = BeanCopyUtil.beanCopy(dto, SysRole.class); role.setId(id); this.updateById(role); // 修改角色权限 this.updateRolePermission(id, dto.getPermissionIds()); // 清除用户权限缓存数据 CacheUtil.clearUserCache("*"); } @Override @Transactional(rollbackFor = Exception.class) public void removeRoles(Integer[] ids) { for (Integer id : ids) { SysRole oriRole = this.getById(id); ApiAssert.notNull(oriRole, String.format("角色编号:%s不存在", id)); this.removeById(id); // 删除角色权限 this.updateRolePermission(id, null); } // 清除用户权限缓存数据 CacheUtil.clearUserCache("*"); } @Override public SysRoleInfoVO getRole(int id) { SysRole oriRole = this.getById(id); ApiAssert.notNull(oriRole, String.format("角色编号:%s不存在", id)); return BeanCopyUtil.beanCopy(oriRole, SysRoleInfoVO.class); } @Override public List<Integer> getRolePermissionIds(int id) { SysRole oriRole = this.getById(id); ApiAssert.notNull(oriRole, String.format("角色编号:%s不存在", id)); return ((SysPermissionMapper) permissionService.getBaseMapper()).getIdsByRoleId(SysPermissionTypeEnum.BUTTON.getValue(), id); } @Override public List<SysUserRoleVO> listRoles() { return BeanCopyUtil.listCopy(this.list(), SysRole.class, SysUserRoleVO.class); } /** * 更新角色权限 * * @author lanjerry * @since 2019/9/5 16:54 * @param roleId 角色id * @param permissionIds 权限id列表 */ private void updateRolePermission(int roleId, List<Integer> permissionIds) { // 删除角色权限 this.rolePermissionService.remove(Wrappers.<SysRolePermission>lambdaQuery().eq(SysRolePermission::getRoleId, roleId)); // 新增角色权限 if (CollectionUtil.isNotEmpty(permissionIds)) { permissionService.list(Wrappers.<SysPermission>lambdaQuery().in(SysPermission::getId, permissionIds)).forEach(permission -> { SysRolePermission rolePermission = new SysRolePermission(); rolePermission.setRoleId(roleId); rolePermission.setPermissionId(permission.getId()); this.rolePermissionService.save(rolePermission); }); } } }
<filename>katipo/views.py from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django import forms from katipo.models import Run, Url def run_detail(request, object_id): run = get_object_or_404(Run, pk=object_id) # handle requests for URL-lists if 'result' in request.REQUEST: r = request.REQUEST['result'] if r in ('ERROR', 'TIMEOUT', 'GOOD', 'BAD', 'IGNORED', ''): qs = run.urls.filter(result=r) return render_to_response('katipo/_url_table.html', {'urls':qs}) else: raise Http404 class CompareRunForm(forms.Form): compare_run = forms.ModelChoiceField(queryset=run.profile.runs.exclude(pk=run.id), initial=run.profile.get_run_previous()) run_c = None if 'compare_run' in request.REQUEST: compare_list_form = CompareRunForm(request.REQUEST) if compare_list_form.is_valid(): run_c = compare_list_form.cleaned_data['compare_run'] else: compare_list_form = CompareRunForm() ctx = { 'run': run, 'compare_run': run_c, 'compare_list_form': compare_list_form, } return render_to_response('katipo/run_detail.html', ctx) def url_redirect(request, url): u = Url.objects.filter(url=url)[:1] if not len(u): raise Http404() else: return HttpResponseRedirect(u[0].get_absolute_url()) def url_detail(request, run_id): u = get_object_or_404(Url, url=request.GET.get('u'), run=run_id) # handle requests for link-lists if 'links' in request.GET: lt = request.GET['links'] if lt == 'incoming': return render_to_response('katipo/_url_table.html', {'urls':u.incoming_links.all()}) elif lt == 'outgoing': return render_to_response('katipo/_url_table.html', {'urls':u.outgoing_links.all()}) else: raise Http404 run_qs = Url.objects.filter(url=u.url) class RunForm(forms.Form): run = forms.ChoiceField(choices=[(url.id, unicode(url.run)) for url in run_qs], initial=u.id) if 'run' in request.REQUEST: run_form = RunForm(request.REQUEST) if run_form.is_valid(): dest_url = get_object_or_404(Url, pk=run_form.cleaned_data['run']) return HttpResponseRedirect(dest_url.get_absolute_url()) else: run_form = RunForm() ctx = { 'url': u, 'run_form': run_form, } return render_to_response('katipo/url_detail.html', ctx) def url_search(request): if 'u' in request.GET: return url_redirect(request, request.GET['u']) ctx = { 'search': False } status = 200 if 'search' in request.REQUEST: search = request.REQUEST.get('search', '').strip() ctx['search'] = search ctx['urls'] = Url.objects.search(search) ctx['notfound'] = not (ctx['urls']['exact'] or len(ctx['urls']['inexact'])) return render_to_response('katipo/url_search.html', ctx)
/** * A simple airport loader which reads a file from disk and sends entries to the webservice * <p> * TODO: Implement the Airport Loader * * @author code test administrator */ public class AirportLoader { private static final String BASE_URI = "http://localhost:9090"; final static RestTemplate restTemplate = new RestTemplate(); public static void main(String args[]) throws IOException { //args=new String[]{"airports.dat"}; if (args.length < 1) { System.err.println("Please provide us with path of airportDataFile"); System.exit(1); } File airportDataFile = new File(args[0]); if (!airportDataFile.exists() || airportDataFile.length() == 0) { System.err.println(airportDataFile + " is not a valid input"); System.exit(1); } AirportLoader al = new AirportLoader(); try (Stream<String> stream = Files.lines(Paths.get(airportDataFile.getAbsolutePath()))) { upload(stream); } catch (IOException e) { e.printStackTrace(); } } private static void upload(Stream<String> stream) { stream.map(e -> e.split(",")).map(s -> new AirportData(s[1], s[2], s[3], s[4], s[5], Double.parseDouble(s[6]), Double.parseDouble(s[7]), Double.parseDouble(s[8]), Double.parseDouble(s[9]), s[10].charAt(0))).forEach(a -> restTemplate.postForObject(BASE_URI + "/collect/airport", a, Void.class)); } }
. INTRODUCTION Cerebrovascular reactivity (CVR) is the capacity of the cerebral microcirculation to increase cerebral blood flow on vasodilator stimulation. This is reduced in patients with carotid obstruction. The changes in arterial pressure produced whilst carrying out different tests for estimation of the CVR may affect its measurement by transcranial Doppler. OBJECTIVES To evaluate the concordance between the different methods for estimation of the CVR by transcranial Doppler in patients with carotid obstruction and to evaluate the importance of monitoring the arterial pressure during CVR tests. PATIENTS AND METHODS We evaluated 17 patients with internal carotid artery obstruction confirmed on arteriography. The CVR was determined by three different methods: apnea test. Breath-Holding Index (BHI) and intravenous acetazolamide test. RESULTS During the tests of RCV the arterial pressure was monitored. We found that there was a reduction in the average basal rate of flow and of the pulsatile index on the obstructed side, with a statistically significant association in relation to the contralateral side (p < 0.001). There was good concordance between the different tests of CVR, with reduced CVR seen on the obstructed side as compared to the contralateral side (p < 0.001) for the different tests. However, this correlation was not seen in stenosis < 70%. During the apnea test changes in blood pressure occurred, with a tendency to increase in the systolic pressure. However, there were no significant changes in blood pressure during the acetazolamide test. CONCLUSIONS There is good concordance in the CVR between the apnea, BHI and acetazolamide tests in carotid obstruction. Changes in arterial pressure occurred during the apnea and BHI tests. However, the acetazolamide test caused no change in arterial pressure.
Models of pulmonary disease: acute and chronic allergic asthma in the monkey and acute and chronic viral pulmonitis in the mouse. Three models/protocols designed to mimic an inflammation process characteristic of a specific lung disease are described in this unit. Included are a single allergen inhalation in monkeys to model acute asthmatic episodes, repeated allergen inhalations in monkeys to model chronic asthma, and a lower-respiratory viral infection in mice to model acute and chronic viral alveolitis and bronchitis. In each case, alterations in lung functions believed to correlate with symptoms of the respective disease are measured along with pulmonary inflammation.
PMG wants to differentiate itself from the pack of bad media actors. Fort Worth, Texas-based indie agency PMG has rebranded around a new tagline, “Digital Made for Humans,” as it seeks to implement a more personalized strategy to data-fueled media planning and buying. The rebrand comes with a revamped website, logo and new content studio, plus an expanded influencer practice. Glomski said PMG looks to hire between 35 and 40 people in strategy and creative to primarily fill out those areas. Glomski said that through this rebrand, PMG seeks to separate itself from the slew of bad actors in digital media that excessively push unwanted content on consumers. According to PMG, “Digital Made for Humans” is a promise to fuse data, tech and creative together to make deeper connections with real people. To do that, PMG introduced a host of new proprietary technologies, tools and services to better target consumers, including one that uses facial recognition software to track the performance of creative executions. That tool will allow PMG to improve a campaign in real time if it’s not performing well. Glomski said new tools allow his agency to be more hands-on when it comes to delivering ads to people. For example, one tool will track a person looking at hiking sites and who just shared a photo of an influencer on a trail in Denali National Park. Then, it will take all of the instances it records of that person, and instead of simply throwing an ad for hiking boots in the person’s face, it will “make suggestions back to us,” according to Glomski. PMG said its new suite of services is being used across its client roster, which includes Beats by Dre, Sephora, Madewell and J. Crew. Popstefanov founded PMG in Fort Worth seven years ago. Since then, the digital agency has expanded to Austin, Los Angeles and London. The agency claims to boast an average revenue growth of 56 percent, adding that over the last three years it grew its client base by 40 percent.
<reponame>ZechyW/cs-toolkit """ Sets up the customised Admin site for the project. Should only contain abstract classes -- Actual admin site registrations and other concrete actions have to be undertaken from `admin.py` in one of the project's apps. """ from collections import defaultdict from django.apps import apps from django.contrib import admin from django.contrib.admin.apps import AdminConfig from django.http import Http404 from django.template.response import TemplateResponse from django.utils.translation import ugettext_lazy as _ #: Custom ordering for project models based on their names model_order = defaultdict(int) model_order.update( { # Lexicon models "Lexical items": 1, "Feature sets": 2, "Features": 3, "Feature properties": 4, # Grammar models "Generator Descriptions": 0, "Rule descriptions": 1, "Derivation requests": 2, "Derivations": 3, "Derivation steps": 4, "Syntactic objects": 5, "Syntactic object values": 6, } ) class AppAdminSite(admin.AdminSite): """ A customised AdminSite that sorts apps and models according to a specified order, rather than alphabetically. """ site_title = "CS Toolkit" index_title = "Data Management" def get_app_list(self, request): """ Return a sorted list of all the installed apps that have been registered in this site, with custom ordering. """ app_list = super().get_app_list(request) # Sort the models according to the custom ordering. for app in app_list: app["models"].sort(key=lambda m: model_order[m["name"]]) return app_list def app_index(self, request, app_label, extra_context=None): """ Overwrites the default AdminSite behaviour to use custom ordering with the models for individual apps as well. :param request: :param app_label: :param extra_context: :return: """ app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404("The requested admin page does not exist.") # Sort the models alphabetically within each app. app_dict["models"].sort(key=lambda m: model_order[m["name"]]) app_name = apps.get_app_config(app_label).verbose_name context = { **self.each_context(request), "title": _("%(app)s management") % {"app": app_name}, "app_list": [app_dict], "app_label": app_label, **(extra_context or {}), } request.current_app = self.name return TemplateResponse( request, self.app_index_template or ["admin/%s/app_index.html" % app_label, "admin/app_index.html"], context, ) class AppAdminConfig(AdminConfig): default_site = "app.admin.AppAdminSite" class AppModelAdmin(admin.ModelAdmin): """ A ModelAdmin subclass that calls the Model.delete() method even on bulk deletions. """ def delete_queryset(self, request, queryset): """ Given a queryset, deletes it from the database. Calls the `.delete()` method of each element in the queryset individually, since we rely on Model.delete() for change notifications. :param request: :param queryset: :return: """ for obj in queryset: obj.delete()
/******************************************************************************* * ConstrainedPlanningToolbox * Copyright (C) 2019 Algorithmics group, Delft University of Technology * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * *******************************************************************************/ package algorithms.mdp.colgen; import solutions.mdp.MDPAgentSolutionPolicyBased; import solutions.mdp.MDPPolicyDeterministic; import model.CMDP; /** * Finite-horizon value iteration for MDPs, which keeps track of time-dependent value, reward and cost. */ public class ValueIterationFiniteHorizon { public ValueIterationFiniteHorizon() { } /** * Solve for budget constraints * @param cmdp cmdp model * @param T horizon * @param lambda array with lambda for each resource * @return solution */ public MDPAgentSolutionPolicyBased solve(CMDP cmdp, int T, double[] lambda) { int K = lambda.length; // compute the time-dependent value function and time-dependent policy double[][] Vvalue = new double[T][cmdp.getNumStates()]; double[][] Vreward = new double[T][cmdp.getNumStates()]; int[][] pi = new int[T][cmdp.getNumStates()]; for(int t=T-1; t>=0; t--) { for(int s=0; s<cmdp.getNumStates(); s++) { double maxVal = Double.NEGATIVE_INFINITY; double maxReward = 0.0; // this is the total reward corresponding to the max value int maxAction = -1; for(int a : cmdp.getFeasibleActions(t, s)) { double currentVal = 0.0; double currentReward = 0.0; int[] transitionDestinations = cmdp.getTransitionDestinations(t, s, a); double[] transitionProbabilities = cmdp.getTransitionProbabilities(t, s, a); for(int j=0; j<transitionDestinations.length; j++) { int sNext = transitionDestinations[j]; double prob = transitionProbabilities[j]; if(t == T-1) { double val = cmdp.getReward(t, s, a); for(int k=0; k<K; k++) { val += -1.0 * lambda[k] * cmdp.getCost(k, s, a); } currentVal += prob * val; currentReward += prob * cmdp.getReward(t, s, a); } else { double val = cmdp.getReward(t, s, a); for(int k=0; k<K; k++) { val += -1.0 * lambda[k] * cmdp.getCost(k, s, a); } currentVal += prob * (val + Vvalue[t+1][sNext]); currentReward += prob * (cmdp.getReward(t, s, a) + Vreward[t+1][sNext]); } } if(currentVal > maxVal) { maxVal = currentVal; maxReward = currentReward; maxAction = a; } } Vvalue[t][s] = maxVal; Vreward[t][s] = maxReward; pi[t][s] = maxAction; } } // compute time-dependent expected instantaneous reward and cost using a forward pass in the tree double[][] stateProbabilities = new double[T][cmdp.getNumStates()]; double[] expectedInstantaneousReward = new double[T]; double[][] expectedInstantaneousCost = new double[cmdp.getNumCostFunctions()][T]; double[] expectedTotalCost = new double[cmdp.getNumCostFunctions()]; stateProbabilities[0][cmdp.getInitialState()] = 1.0; for(int t=0; t<T; t++) { for(int s=0; s<cmdp.getNumStates(); s++) { int a = pi[t][s]; // compute instantaneous reward and cost expectedInstantaneousReward[t] += stateProbabilities[t][s] * cmdp.getReward(t, s, a); for(int k=0; k<cmdp.getNumCostFunctions(); k++) { expectedInstantaneousCost[k][t] += stateProbabilities[t][s] * cmdp.getCost(k, s, a); expectedTotalCost[k] += stateProbabilities[t][s] * cmdp.getCost(k, s, a); } // compute probabilities for the next iteration if(t<T-1) { int[] transitionDestinations = cmdp.getTransitionDestinations(t, s, a); double[] transitionProbabilities = cmdp.getTransitionProbabilities(t, s, a); for(int j=0; j<transitionDestinations.length; j++) { int sNext = transitionDestinations[j]; double prob = transitionProbabilities[j]; stateProbabilities[t+1][sNext] += stateProbabilities[t][s] * prob; } for(int sNext=0; sNext<cmdp.getNumStates(); sNext++) { if(stateProbabilities[t+1][sNext] < 0.0) stateProbabilities[t+1][sNext] = 0.0; if(stateProbabilities[t+1][sNext] > 1.0) stateProbabilities[t+1][sNext] = 1.0; assert stateProbabilities[t+1][sNext] >= 0.0 && stateProbabilities[t+1][sNext] <= 1.0 : stateProbabilities[t+1][sNext]+""; } } } } return new MDPPolicyDeterministic(pi, Vreward[0][cmdp.getInitialState()], expectedInstantaneousCost, expectedTotalCost); } /** * Solve for instantaneous constraints * @param cmdp cmdp model * @param T horizon * @param lambda lambda for each resource-time combination * @return solution */ public MDPAgentSolutionPolicyBased solve(CMDP cmdp, int T, double[][] lambda) { assert lambda[0].length == T; int K = lambda.length; // compute the time-dependent value function and time-dependent policy double[][] Vvalue = new double[T][cmdp.getNumStates()]; double[][] Vreward = new double[T][cmdp.getNumStates()]; int[][] pi = new int[T][cmdp.getNumStates()]; for(int t=T-1; t>=0; t--) { for(int s=0; s<cmdp.getNumStates(); s++) { double maxVal = Double.NEGATIVE_INFINITY; double maxReward = 0.0; // this is the total reward corresponding to the max value int maxAction = -1; for(int a : cmdp.getFeasibleActions(t, s)) { double currentVal = 0.0; double currentReward = 0.0; int[] transitionDestinations = cmdp.getTransitionDestinations(t, s, a); double[] transitionProbabilities = cmdp.getTransitionProbabilities(t, s, a); for(int j=0; j<transitionDestinations.length; j++) { int sNext = transitionDestinations[j]; double prob = transitionProbabilities[j]; if(t == T-1) { double val = cmdp.getReward(t, s, a); for(int k=0; k<K; k++) { val += -1.0 * lambda[k][t] * cmdp.getCost(k, s, a); } currentVal += prob * val; currentReward += prob * cmdp.getReward(t, s, a); } else { double val = cmdp.getReward(t, s, a); for(int k=0; k<K; k++) { val += -1.0 * lambda[k][t] * cmdp.getCost(k, s, a); } currentVal += prob * (val + Vvalue[t+1][sNext]); currentReward += prob * (cmdp.getReward(t, s, a) + Vreward[t+1][sNext]); } } if(currentVal > maxVal) { maxVal = currentVal; maxReward = currentReward; maxAction = a; } } Vvalue[t][s] = maxVal; Vreward[t][s] = maxReward; pi[t][s] = maxAction; } } // compute time-dependent expected instantaneous reward and cost using a forward pass in the tree double[][] stateProbabilities = new double[T][cmdp.getNumStates()]; double[] expectedInstantaneousReward = new double[T]; double[][] expectedInstantaneousCost = new double[cmdp.getNumCostFunctions()][T]; double[] expectedTotalCost = new double[cmdp.getNumCostFunctions()]; stateProbabilities[0][cmdp.getInitialState()] = 1.0; for(int t=0; t<T; t++) { for(int s=0; s<cmdp.getNumStates(); s++) { int a = pi[t][s]; // compute instantaneous reward and cost expectedInstantaneousReward[t] += stateProbabilities[t][s] * cmdp.getReward(t, s, a); for(int k=0; k<cmdp.getNumCostFunctions(); k++) { expectedInstantaneousCost[k][t] += stateProbabilities[t][s] * cmdp.getCost(k, s, a); expectedTotalCost[k] += stateProbabilities[t][s] * cmdp.getCost(k, s, a); } // compute probabilities for the next iteration if(t<T-1) { int[] transitionDestinations = cmdp.getTransitionDestinations(t, s, a); double[] transitionProbabilities = cmdp.getTransitionProbabilities(t, s, a); for(int j=0; j<transitionDestinations.length; j++) { int sNext = transitionDestinations[j]; double prob = transitionProbabilities[j]; stateProbabilities[t+1][sNext] += stateProbabilities[t][s] * prob; } for(int sNext=0; sNext<cmdp.getNumStates(); sNext++) { if(stateProbabilities[t+1][sNext] < 0.0) stateProbabilities[t+1][sNext] = 0.0; if(stateProbabilities[t+1][sNext] > 1.0) stateProbabilities[t+1][sNext] = 1.0; assert stateProbabilities[t+1][sNext] >= 0.0 && stateProbabilities[t+1][sNext] <= 1.0 : stateProbabilities[t+1][sNext]+""; } } } } return new MDPPolicyDeterministic(pi, Vreward[0][cmdp.getInitialState()], expectedInstantaneousCost, expectedTotalCost); } }
def english_integer(val): if val < 0: return 'negative ' + english_integer(-val) elif val < 20: return ZERO_TO_19[val] elif val < 100: return TWENTY_UP[val / 10] + HYPHEN_ONES[val % 10] elif val < 1000: name = HYPHEN_ONES[val / 100][1:] + ' hundred' if val % 100 > 0: name += ' and ' + english_integer(val % 100) return name name = '' step = 0 while val > 0: current = val % 1000 if current > 0: name = english_integer(current) + THOUSAND_UP[step] + ' ' + name val = val / 1000 step += 1 name = name.strip() return name
A hepatic stem cell vaccine is superior to an embryonic stem cell vaccine in the prophylaxis and treatment of murine hepatocarcinoma. Stem cells and cancer cells express a common subset of antigens called oncofetal antigens. Theoretically, vaccination with stem cells is effective at boosting the preexisting anticancer immune response. Herein we describe the efficacy of two stem cell-based vaccines in the prophylaxis and treatment of subcutaneous hepatic tumors transplanted into mice. C57BL/6j mice were vaccinated weekly with either hepatic stem cells (HSCs) or embryonic stem cells (ESCs) for three weeks, followed by a subcutaneous challenge with Hepa 1-6 cells at one week (group 1) or four weeks (group 2) after vaccination. No tumor formation was observed in HSC-vaccinated mice when challenged within one week after vaccination (group 1), but tumors formed in 10% of mice in the ESC-vaccinated group and in 60% of mice in the unvaccinated group. When the long-term memory response was examined (group 2), only 10% of HSC-vaccinated mice and 20% of ESC-vaccinated mice developed macroscopic hepatocarcinomas compared to 60% of the unvaccinated mice. Besides their function as prophylactic vaccines, administration of either HSC or ESC could be a potential treatment for cancer. In mice with subcutaneous hepatocarcinomas, complete clearance of tumor burden was observed in 80% of mice receiving HSC vaccination, but 40% of ESC-vaccinated mice presented with tumors that did not increase in size over time. These data support that HSC is a superior vaccine candidate for durable antitumor protection in this hepatocarcinoma model.
// Test that readResponse closes the socket and returns an error if the read // fails. TEST_F(MockSocketTest, readResponse_err) { XmlRpcClientForTest a("localhost", 42); a.setfd(7); a._connectionState = XmlRpcClientForTest::READ_RESPONSE; a._response = ""; a._contentLength = 114; ASSERT_EQ(114u, response.length()); Expect_nbRead(7, "", false, false); Expect_getError(ENOTCONN); Expect_close(7); EXPECT_FALSE(a.readResponse()); EXPECT_EQ(XmlRpcClientForTest::NO_CONNECTION, a._connectionState); CheckCalls(); }
<reponame>ipfans/components-contrib<gh_stars>0 // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation and Dapr Contributors. // Licensed under the MIT License. // ------------------------------------------------------------ package eventhubs import ( "context" "errors" "fmt" "os" "os/signal" "strconv" "syscall" "time" eventhub "github.com/Azure/azure-event-hubs-go/v3" "github.com/Azure/azure-event-hubs-go/v3/eph" "github.com/Azure/azure-event-hubs-go/v3/storage" "github.com/Azure/azure-storage-blob-go/azblob" "github.com/Azure/go-autorest/autorest/azure" "github.com/dapr/components-contrib/bindings" "github.com/dapr/kit/logger" ) const ( // metadata connectionString = "connectionString" // required by subscriber consumerGroup = "consumerGroup" storageAccountName = "storageAccountName" storageAccountKey = "storageAccountKey" storageContainerName = "storageContainerName" // optional partitionKeyName = "partitionKey" partitionIDName = "partitionID" // errors missingConnectionStringErrorMsg = "error: connectionString is a required attribute" missingStorageAccountNameErrorMsg = "error: storageAccountName is a required attribute" missingStorageAccountKeyErrorMsg = "error: storageAccountKey is a required attribute" missingStorageContainerNameErrorMsg = "error: storageContainerName is a required attribute" missingConsumerGroupErrorMsg = "error: consumerGroup is a required attribute" // Event Hubs SystemProperties names for metadata passthrough sysPropSequenceNumber = "x-opt-sequence-number" sysPropEnqueuedTime = "x-opt-enqueued-time" sysPropOffset = "x-opt-offset" sysPropPartitionID = "x-opt-partition-id" sysPropPartitionKey = "x-opt-partition-key" sysPropIotHubDeviceConnectionID = "iothub-connection-device-id" sysPropIotHubAuthGenerationID = "iothub-connection-auth-generation-id" sysPropIotHubConnectionAuthMethod = "iothub-connection-auth-method" sysPropIotHubConnectionModuleID = "iothub-connection-module-id" sysPropIotHubEnqueuedTime = "iothub-enqueuedtime" ) func readHandler(e *eventhub.Event, handler func(*bindings.ReadResponse) ([]byte, error)) error { res := bindings.ReadResponse{Data: e.Data, Metadata: map[string]string{}} if e.SystemProperties.SequenceNumber != nil { res.Metadata[sysPropSequenceNumber] = strconv.FormatInt(*e.SystemProperties.SequenceNumber, 10) } if e.SystemProperties.EnqueuedTime != nil { res.Metadata[sysPropEnqueuedTime] = e.SystemProperties.EnqueuedTime.Format(time.RFC3339) } if e.SystemProperties.Offset != nil { res.Metadata[sysPropOffset] = strconv.FormatInt(*e.SystemProperties.Offset, 10) } // According to azure-event-hubs-go docs, this will always be nil. if e.SystemProperties.PartitionID != nil { res.Metadata[sysPropPartitionID] = strconv.Itoa(int(*e.SystemProperties.PartitionID)) } // The following metadata properties are only present if event was generated by Azure IoT Hub if e.SystemProperties.PartitionKey != nil { res.Metadata[sysPropPartitionKey] = *e.SystemProperties.PartitionKey } if e.SystemProperties.IoTHubDeviceConnectionID != nil { res.Metadata[sysPropIotHubDeviceConnectionID] = *e.SystemProperties.IoTHubDeviceConnectionID } if e.SystemProperties.IoTHubAuthGenerationID != nil { res.Metadata[sysPropIotHubAuthGenerationID] = *e.SystemProperties.IoTHubAuthGenerationID } if e.SystemProperties.IoTHubConnectionAuthMethod != nil { res.Metadata[sysPropIotHubConnectionAuthMethod] = *e.SystemProperties.IoTHubConnectionAuthMethod } if e.SystemProperties.IoTHubConnectionModuleID != nil { res.Metadata[sysPropIotHubConnectionModuleID] = *e.SystemProperties.IoTHubConnectionModuleID } if e.SystemProperties.IoTHubEnqueuedTime != nil { res.Metadata[sysPropIotHubEnqueuedTime] = e.SystemProperties.IoTHubEnqueuedTime.Format(time.RFC3339) } _, err := handler(&res) return err } // AzureEventHubs allows sending/receiving Azure Event Hubs events type AzureEventHubs struct { hub *eventhub.Hub metadata *azureEventHubsMetadata logger logger.Logger } type azureEventHubsMetadata struct { connectionString string consumerGroup string storageAccountName string storageAccountKey string storageContainerName string partitionID string partitionKey string } func (m azureEventHubsMetadata) partitioned() bool { return m.partitionID != "" } // NewAzureEventHubs returns a new Azure Event hubs instance func NewAzureEventHubs(logger logger.Logger) *AzureEventHubs { return &AzureEventHubs{logger: logger} } // Init performs metadata init func (a *AzureEventHubs) Init(metadata bindings.Metadata) error { m, err := parseMetadata(metadata) if err != nil { return err } a.metadata = m hub, err := eventhub.NewHubFromConnectionString(a.metadata.connectionString) // Create partitioned sender if the partitionID is configured if a.metadata.partitioned() { hub, err = eventhub.NewHubFromConnectionString(a.metadata.connectionString, eventhub.HubWithPartitionedSender(a.metadata.partitionID)) } if err != nil { return fmt.Errorf("unable to connect to azure event hubs: %v", err) } a.hub = hub return nil } func parseMetadata(meta bindings.Metadata) (*azureEventHubsMetadata, error) { m := &azureEventHubsMetadata{} if val, ok := meta.Properties[connectionString]; ok && val != "" { m.connectionString = val } else { return m, errors.New(missingConnectionStringErrorMsg) } if val, ok := meta.Properties[storageAccountName]; ok && val != "" { m.storageAccountName = val } else { return m, errors.New(missingStorageAccountNameErrorMsg) } if val, ok := meta.Properties[storageAccountKey]; ok && val != "" { m.storageAccountKey = val } else { return m, errors.New(missingStorageAccountKeyErrorMsg) } if val, ok := meta.Properties[storageContainerName]; ok && val != "" { m.storageContainerName = val } else { return m, errors.New(missingStorageContainerNameErrorMsg) } if val, ok := meta.Properties[consumerGroup]; ok && val != "" { m.consumerGroup = val } else { return m, errors.New(missingConsumerGroupErrorMsg) } if val, ok := meta.Properties[partitionKeyName]; ok { m.partitionKey = val } if val, ok := meta.Properties[partitionIDName]; ok { m.partitionID = val } return m, nil } func (a *AzureEventHubs) Operations() []bindings.OperationKind { return []bindings.OperationKind{bindings.CreateOperation} } // Write posts an event hubs message func (a *AzureEventHubs) Invoke(req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) { event := &eventhub.Event{ Data: req.Data, } // Send partitionKey in event if a.metadata.partitionKey != "" { event.PartitionKey = &a.metadata.partitionKey } else { partitionKey, ok := req.Metadata[partitionKeyName] if partitionKey != "" && ok { event.PartitionKey = &partitionKey } } err := a.hub.Send(context.Background(), event) if err != nil { return nil, err } return nil, nil } // Read gets messages from eventhubs in a non-blocking fashion func (a *AzureEventHubs) Read(handler func(*bindings.ReadResponse) ([]byte, error)) error { if !a.metadata.partitioned() { if err := a.RegisterEventProcessor(handler); err != nil { return err } } else { if err := a.RegisterPartitionedEventProcessor(handler); err != nil { return err } } // close Event Hubs when application exits exitChan := make(chan os.Signal, 1) signal.Notify(exitChan, os.Interrupt, syscall.SIGTERM) <-exitChan a.hub.Close(context.Background()) return nil } // RegisterPartitionedEventProcessor - receive eventhub messages by partitionID func (a *AzureEventHubs) RegisterPartitionedEventProcessor(handler func(*bindings.ReadResponse) ([]byte, error)) error { ctx := context.Background() runtimeInfo, err := a.hub.GetRuntimeInformation(ctx) if err != nil { return err } callback := func(c context.Context, event *eventhub.Event) error { if event != nil { return readHandler(event, handler) } return nil } ops := []eventhub.ReceiveOption{ eventhub.ReceiveWithLatestOffset(), } if a.metadata.consumerGroup != "" { a.logger.Infof("eventhubs: using consumer group %s", a.metadata.consumerGroup) ops = append(ops, eventhub.ReceiveWithConsumerGroup(a.metadata.consumerGroup)) } if contains(runtimeInfo.PartitionIDs, a.metadata.partitionID) { a.logger.Infof("eventhubs: using partition id %s", a.metadata.partitionID) _, err := a.hub.Receive(ctx, a.metadata.partitionID, callback, ops...) if err != nil { return err } } return nil } func contains(arr []string, str string) bool { for _, a := range arr { if a == str { return true } } return false } // RegisterEventProcessor - receive eventhub messages by eventprocessor // host by balancing partitions func (a *AzureEventHubs) RegisterEventProcessor(handler func(*bindings.ReadResponse) ([]byte, error)) error { cred, err := azblob.NewSharedKeyCredential(a.metadata.storageAccountName, a.metadata.storageAccountKey) if err != nil { return err } leaserCheckpointer, err := storage.NewStorageLeaserCheckpointer(cred, a.metadata.storageAccountName, a.metadata.storageContainerName, azure.PublicCloud) if err != nil { return err } processor, err := eph.NewFromConnectionString(context.Background(), a.metadata.connectionString, leaserCheckpointer, leaserCheckpointer, eph.WithNoBanner(), eph.WithConsumerGroup(a.metadata.consumerGroup)) if err != nil { return err } _, err = processor.RegisterHandler(context.Background(), func(c context.Context, e *eventhub.Event) error { return readHandler(e, handler) }) if err != nil { return err } err = processor.StartNonBlocking(context.Background()) if err != nil { return err } return nil }
A Land Cover Background-Adaptive Framework for Large-Scale Road Extraction Background: Road network data are crucial in various applications, such as emergency response, urban planning, and transportation management. The recent application of deep neural networks has significantly boosted the efficiency and accuracy of road network extraction based on remote sensing data. However, most existing methods for road extraction were designed at local or regional scales. Automatic extraction of large-scale road datasets from satellite images remains challenging due to the complex background around the roads, especially the complicated land cover types. To tackle this issue, this paper proposes a land cover background-adaptive framework for large-scale road extraction. Method: A large number of sample image blocks are selected from six different countries of a wide region as the dataset. OpenStreetMap (OSM) is automatically converted to the ground truth of networks, and Esri 2020 Land Cover Dataset is taken as the background land cover information. A fuzzy C-means clustering algorithm is first applied to cluster the sample images according to the proportion of certain land use types that obviously negatively affect road extraction performance. Then, the specific model is trained on the images clustered as abundant with that certain land use type, while a general model is trained based on the rest of the images. Finally, the road extraction results obtained by those general and specific modes are combined. Results: The dataset selection and algorithm implementation were conducted on the cloud-based geoinformation platform Google Earth Engine (GEE) and Google Colaboratory. Experimental results showed that the proposed framework achieved stronger adaptivity on large-scale road extraction in both visual and statistical analysis. The C-means clustering algorithm applied in this study outperformed other hard clustering algorithms. Significance: The promising potential of the proposed background-adaptive network was demonstrated in the automatic extraction of large-scale road networks from satellite images as well as other object detection tasks. This search demonstrated a new paradigm for the study of large-scale remote sensing applications based on deep neural networks.
<filename>lightcrafts/src/com/lightcrafts/templates/TemplateDatabase.java /* Copyright (C) 2005-2011 <NAME> */ package com.lightcrafts.templates; import static com.lightcrafts.templates.Locale.LOCALE; import com.lightcrafts.image.metadata.ImageMetadata; import com.lightcrafts.image.types.RawImageType; import com.lightcrafts.platform.Platform; import com.lightcrafts.utils.file.FileUtil; import com.lightcrafts.utils.xml.XMLException; import com.lightcrafts.utils.xml.XmlDocument; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.LinkedList; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; /** * Read and write XmlDocuments from and to Preferences using user-provided * String keys. Also, inspect the current set of key Strings. */ public class TemplateDatabase { /** * Any failure in the backing store mechanism for templates causes this * exception to be thrown. */ public static class TemplateException extends Exception { TemplateException(String message) { super(message); } TemplateException(String message, Throwable cause) { super(message, cause); } } // The namespace that indicates a camera default Template. final static String CameraDefaultNamespace = "CameraDefault"; // A namespace assigned to legacy Templates without a namespace. final static String DefaultNamespace = LOCALE.get("DefaultTemplateNamespace"); static File TemplateDir; private static LinkedList<TemplateDatabaseListener> listeners = new LinkedList<TemplateDatabaseListener>(); private static Preferences Prefs = Preferences.userNodeForPackage(TemplateDatabase.class); /** * This class provides a static utility and cannot be constructed. */ private TemplateDatabase() { } public static void addListener(TemplateDatabaseListener listener) { listeners.add(listener); } public static void removeListener(TemplateDatabaseListener listener) { listeners.remove(listener); } public static void deployFactoryTemplates() { TemplateDeployer.deploy(); notifyListeners(); } public static List<TemplateKey> getTemplateKeys() throws TemplateException { checkTemplateDir(); FileFilter filter = new FileFilter() { public boolean accept(File file) { if (file.isFile()) { String name = file.getName().toLowerCase(); return name.endsWith(".lzt"); } return false; } }; File[] files = FileUtil.listFiles(TemplateDir, filter, false); if (files == null) { throw new TemplateException( "Couldn't read Template names from " + TemplateDir.getAbsolutePath() ); } List<TemplateKey> keys = new ArrayList<TemplateKey>(); for (File file : files) { TemplateKey key = new TemplateKey(file); keys.add(key); } Collections.sort(keys); return keys; } public static XmlDocument getTemplateDocument(TemplateKey key) throws TemplateException { try { checkTemplateDir(); File file = key.getFile(); if (file == null) { throw new TemplateException( "No Template named \"" + key + "\" exists in " + TemplateDir.getAbsolutePath() ); } InputStream in = new FileInputStream(file); XmlDocument doc = new XmlDocument(in); in.close(); return doc; } catch (XMLException e) { throw new TemplateException( "Template \"" + key + "\" in " + TemplateDir.getAbsolutePath() + " is malformed: " + e.getMessage(), e ); } catch (IOException e) { throw new TemplateException( "Couldn't access Template \"" + key + "\" in " + TemplateDir.getAbsolutePath() + ": " + e.getMessage(), e ); } } public static void addTemplateDocument( XmlDocument doc, TemplateKey key, boolean force ) throws TemplateException { try { checkTemplateDir(); File file = key.getFile(); if (file.exists() && (! force)) { throw new TemplateException( "A Template named \"" + key + "\" already exists in " + TemplateDir.getAbsolutePath() ); } OutputStream out = new FileOutputStream(file); doc.write(out); out.close(); } catch (IOException e) { throw new TemplateException( "Couldn't add Template \"" + key + "\" in " + TemplateDir.getAbsolutePath(), e ); } notifyListeners(); } public static void removeTemplateDocument(TemplateKey key) throws TemplateException { checkTemplateDir(); File file = key.getFile(); boolean deleted = file.delete(); if (! deleted) { throw new TemplateException( "Couldn't delete Template \"" + key + "\" in " + TemplateDir.getAbsolutePath() ); } notifyListeners(); } public static void setDefaultTemplate(ImageMetadata meta, TemplateKey key) throws TemplateException { String camera = meta.getCameraMake(true); if (camera != null) { if (key != null) { XmlDocument xml = getTemplateDocument(key); TemplateKey defaultKey = new TemplateKey(CameraDefaultNamespace, camera); addTemplateDocument(xml, defaultKey, true); } else { key = new TemplateKey(CameraDefaultNamespace, camera); removeTemplateDocument(key); } } } public static TemplateKey getDefaultTemplate(ImageMetadata meta) { boolean isRaw = (meta.getImageType() instanceof RawImageType); if (isRaw) { String camera = meta.getCameraMake(true); if (camera != null) { // A default template is a template with the camera's name // in the special namespace: TemplateKey key = new TemplateKey(CameraDefaultNamespace, camera); XmlDocument xml = null; try { xml = getTemplateDocument(key); } catch (TemplateException e) { // Counts as a missing template. System.err.println("Template error: " + e.getMessage()); } if (xml == null) { // Compatibility for users of the LightZone 2 beta: // search for default templates in preferences. return getDefaultFromPrefs(meta); } return key; } } return null; } // Legacy preferences-based default mechanism. private static TemplateKey getDefaultFromPrefs(ImageMetadata meta) { String camera = meta.getCameraMake(true); if (camera != null) { String name = Prefs.get(camera, null); if (name != null) { // Make sure the template has not been removed: XmlDocument xml = null; TemplateKey key = new TemplateKey(CameraDefaultNamespace, name); try { xml = getTemplateDocument(key); } catch (TemplateException e) { // Counts as a missing template. System.err.println( "Default template not found: " + e.getMessage() ); } if (xml == null) { // The template's gone, so remove the camera key also: Prefs.remove(camera); return null; } return key; } } return null; } private static void notifyListeners() { for (TemplateDatabaseListener listener : listeners) { listener.templatesChanged(); } } private static void checkTemplateDir() throws TemplateException { if (TemplateDir == null) { TemplateDir = new File( Platform.getPlatform().getLightZoneDocumentsDirectory(), "Templates" ); if (! TemplateDir.isDirectory()) { boolean success = TemplateDir.mkdirs(); if (! success) { String path = TemplateDir.getAbsolutePath(); TemplateDir = null; throw new TemplateException( "Couldn't initialize Template directory at " + path ); } } if (System.getProperty("lightcrafts.debug") == null) { if (! TemplateDeployer.hasDeployed()) { TemplateDeployer.deploy(); } } // Backwardsompatibility measures: // migrate templates from preferences into files. migratePrefsTemplates(); // migrate templates from an old folder to the correct folder: migrateTemplateFolders(); // migrate old templates with no namespace to a default namespace: migrateTemplateNamespace(); } } // In early pre-release versions of LightZone 2, Templates were stored in // Preferences. This method is called at initialization and attempts to // copy any Templates from preferences into files. If the copy is // successful, the preferences are erased. private static void migratePrefsTemplates() { try { List<String> names = getPrefsTemplateNames(); for (String name : names) { try { XmlDocument doc = getPrefsTemplateDocument(name); TemplateKey newKey = new TemplateKey("", name); addTemplateDocument(doc, newKey, false); removePrefsTemplateDocument(name); System.out.println( "Migrated old-style template " + name ); } catch (TemplateException e) { System.err.println( "Failed to migrate old-style template " + name ); } } } catch (TemplateException e) { System.err.println( "Couldn't access old-style templates" ); } } // In later pre-release versions of LightZone 2, Templates on Windows were // stored as files under "Application Data\LightZone\Templates", instead // of "My Documents\LightZone\Templates". This method copies templates // from the old folder to the new one. private static void migrateTemplateFolders() { if (Platform.getType() != Platform.Windows) { // Only on Windows did we move the template folder. return; } String home = System.getProperty("user.home"); String oldPath = "Application Data\\LightZone\\Templates"; File oldTemplateDir = new File(home, oldPath); if (oldTemplateDir.isDirectory()) { File[] oldFiles = FileUtil.listFiles(oldTemplateDir); if (oldFiles != null) { boolean copySucceeded = true; for (File oldFile : oldFiles) { File newFile = new File(TemplateDir, oldFile.getName()); try { FileUtil.copyFile(oldFile, newFile); System.out.println( "Copied a template from " + oldFile + " to " + newFile ); boolean deleted = oldFile.delete(); if (deleted) { System.out.println( "Deleted an old template at " + oldFile ); } else { System.out.println( "Failed to delete an old template at " + oldFile ); } } catch (IOException e) { System.out.println( "Failed to migrate a template from " + oldFile + " to " + newFile + ": " + e.getClass().getName() + " " + e.getMessage() ); copySucceeded = false; } } if (copySucceeded) { // All files in the old folder were successfully copied. boolean deleted = oldTemplateDir.delete(); if (deleted) { System.out.println( "Deleted old template folder " + oldTemplateDir.getAbsolutePath() ); } else { System.out.println( "Failed to delete old template folder " + oldTemplateDir.getAbsolutePath() ); } } } } } // Older templates have no namespace. Find templates whose namespace is // the empty string, and put them in a default namespace. private static void migrateTemplateNamespace() { try { List<TemplateKey> keys = TemplateDatabase.getTemplateKeys(); for (TemplateKey key : keys) { String namespace = key.getNamespace(); if (namespace.equals("")) { try { XmlDocument xml = TemplateDatabase.getTemplateDocument(key); String name = key.getName(); TemplateKey newKey = new TemplateKey(DefaultNamespace, name); TemplateDatabase.addTemplateDocument(xml, newKey, false); TemplateDatabase.removeTemplateDocument(key); } catch (TemplateException e) { // Skip this one and continue. System.out.println( "Template migration failed for " + key ); e.printStackTrace(); } } } } catch (TemplateException e) { // OK, just allow some templates with the empty namespace System.out.println("Failed to migrate template namespaces"); } } // To help migrate LightZone 2 beta templates into files. private static List<String> getPrefsTemplateNames() throws TemplateException { try { String[] keys = Prefs.keys(); ArrayList<String> names = new ArrayList<String>(); for (String key : keys) { String name = getNameFromPrefsKey(key); if (name != null) { names.add(name); } } Collections.sort(names); return names; } catch (BackingStoreException e) { throw new TemplateException("Couldn't read template names", e); } } // To help migrate LightZone 2 beta templates into files. private static XmlDocument getPrefsTemplateDocument(String name) throws TemplateException { try { String key = getPrefsKeyFromName(name); String text = Prefs.get(key, null); if (text == null) { throw new TemplateException( "No template named \"" + name + "\"" ); } byte[] bytes = text.getBytes(); InputStream in = new ByteArrayInputStream(bytes); XmlDocument doc = new XmlDocument(in); return doc; } catch (IOException e) { throw new TemplateException( "Couldn't access template \"" + name + "\"", e ); } } private static void removePrefsTemplateDocument(String name) { String key = getPrefsKeyFromName(name); Prefs.remove(key); } private static String getPrefsKeyFromName(String name) { return "Template_" + name; } private static String getNameFromPrefsKey(String key) { if (key.startsWith("Template_")) { return key.replaceFirst("Template_", ""); } return null; } }
package com.woshidaniu.drdcsj.drsj.action; import java.util.HashMap; import org.springframework.stereotype.Controller; import com.woshidaniu.common.action.BaseAction; import com.woshidaniu.security.algorithm.DesBase64Codec; /** * * <p> * <h3>niutal框架<h3> * 说明:TODO * <p> * @author <a href="#">xiaokang[1036]<a> * @version 2016年8月3日下午5:47:36 */ @Controller("drOutAction") public class OutAction extends BaseAction{ private static final long serialVersionUID = 4434097970993600063L; //输入参数 private String param; //仅导入模块使用; private String drmkdm; /** * 单点登录,参数param, * 解密后多个参数以&相连,参数名=参数值 * yhm用户名;gnbh功能编号;timestamp时间戳 * @return */ public String login() { DesBase64Codec dbEncrypt = new DesBase64Codec(); String yhm = null,gnbh = null; try { if(param == null){ this.getValueStack().set(DATA, "调用外部登陆失败,参数错误!"); return DATA; } String accessParam = dbEncrypt.decrypt(param.getBytes()); String[] params = accessParam.split("&"); HashMap<String,String> paramMap = new HashMap<String, String>(); for (int i = 0; i < params.length; i++) { if(params != null){ String[] paramsArr = params[i].split("="); if(paramsArr != null && paramsArr.length > 1){ paramMap.put(paramsArr[0], paramsArr[1]); } } } //用户名参数 yhm = paramMap.get("yhm"); //功能编号参数 gnbh = paramMap.get("gnbh"); //导入模块代码(仅导入模块使用) drmkdm = paramMap.get("drmkdm"); return gnbh; } catch (Exception e) { this.getValueStack().set(DATA, "用户参数:[" + yhm + "] 非法:无法获取用户信息!"); return DATA; } } /** * 系统初始化 */ public void initialize() { } public String getParam() { return param; } public void setParam(String param) { this.param = param; } public String getDrmkdm() { return drmkdm; } public void setDrmkdm(String drmkdm) { this.drmkdm = drmkdm; } }
<filename>src/SortExecutor.java public class SortExecutor implements Runnable { // Simple class that allows me to move the processing to a new thread so the UI doesn't lag. // Also lets me test the algorithms speed private Sort sort; private Thread sortingThread; private long start_time; @Override public void run() { synchronized (this) { while (true) { if (isSorting()) { VisualizationBase.VISUALIZATION_GUI.setAccessCounter(sort.array.counter.getAccesses()); VisualizationBase.VISUALIZATION_GUI.setCompareCounter(sort.array.counter.getCompares()); VisualizationBase.VISUALIZATION_GUI.setSetCounter(sort.array.counter.getSets()); long intermiediate_time = System.currentTimeMillis(); VisualizationBase.VISUALIZATION_GUI.setRunTimeCounter(intermiediate_time - start_time); } try { wait(100); // So we could write a method in Sort to lock this thread until running is true, but I don't feel like writing it lol // So the result is to poll this method every 100 ms and check if it is sorting and just set it every 'tick' } catch (InterruptedException e) {} } } } public void runSort(ElementArray inputArray, Sort.algorithms sortingAlgorithm) { synchronized (this) { if (sort != null) { if (sort.isRunning()) { if (!sort.isPaused()) { sort.pause(); } else { sort.unpause(); } } else { inputArray.counter.resetCounters(); sort = VisualizationBase.CURRENT_ALGORITHM.sort(inputArray); start_time = System.currentTimeMillis(); sortingThread = new Thread(sort); sortingThread.start(); this.notify(); } } else { sort = VisualizationBase.CURRENT_ALGORITHM.sort(inputArray); start_time = System.currentTimeMillis(); sortingThread = new Thread(sort); sortingThread.start(); this.notify(); } } } @SuppressWarnings("deprecation") public void stopSort() { if (sort != null) { sort.stopSorting(); sortingThread.stop(); } } public boolean isSorting() { if (sort != null) { return sort.isRunning(); } return false; } }
/** * Informs the plugin system about gui termination. **/ protected void destroy() { if (fPlugin != null) { fPlugin.notifyGuiClosed(this); fPlugin = null; } }
def _get_tg_vars(): tgl = tg.request_local.context._current_obj() req = tgl.request conf = tgl.config tmpl_context = tgl.tmpl_context app_globals = tgl.app_globals translator = tgl.translator response = tgl.response session = tgl.session helpers = conf['helpers'] try: validation = req.validation except AttributeError: validation = {} tg_vars = Bunch( config=tg.config, flash_obj=tg.flash, quote_plus=quote_plus, url=tg.url, identity = req.environ.get('repoze.who.identity'), session = session, locale = req.plain_languages, errors = validation and validation.errors, inputs = validation and validation.values, request = req, auth_stack_enabled = 'repoze.who.plugins' in req.environ, predicates = predicates) root_vars = Bunch( c=tmpl_context, tmpl_context=tmpl_context, response=response, request=req, config=conf, app_globals=app_globals, g=app_globals, session=session, url=tg.url, helpers=helpers, h=helpers, tg=tg_vars, translator=translator, ungettext=tg.i18n.ungettext, _=tg.i18n.ugettext, N_=tg.i18n.gettext_noop) tmpl_context.identity = tg_vars['identity'] variable_provider = conf.get('variable_provider', None) if variable_provider: root_vars.update(variable_provider()) return root_vars
A lifeline in the dark: Breaking through the stigma of veteran mental health and treating America's combat veterans. For generations, veterans have answered the call to service and served their country honorably and with distinction. Unfortunately, the consequences of combat cause many veterans to struggle with life after the military and with readjustment/reintegration into civilian life. Today more than ever, there are a multitude of resources, education, and treatment options for combat veterans. For mental and physical health providers, business leaders, and other professionals who work with veterans, it is of the upmost importance that they learn about programs around them that are successful in treating veterans. The current article reviews two U.S. Department of Veterans Affairs nationwide programs-the Readjustment Counseling Service/Vet Center and Veteran Cultural Competence Training-designed to decrease mental health stigma for veterans and to increase veteran engagement with mental health services. These programs highlight the importance of being aware of the culture within military systems, being aware of personal biases, and fostering an environment of genuineness, safety, and nonjudgmental empathy. In doing so, these programs are successful in reducing the unspoken power of stigmatization; they effectively reach out to veterans in need, providing a lifeline in the dark.
package com.vk.api.sdk.objects.groups; import com.google.gson.annotations.SerializedName; import com.vk.api.sdk.objects.base.BoolInt; import com.vk.api.sdk.objects.places.PlaceMin; import java.util.List; import java.util.Objects; /** * GroupSettings object */ public class GroupSettings { /** * Community title */ @SerializedName("title") private String title; /** * Community description */ @SerializedName("description") private String description; /** * Community's page domain */ @SerializedName("address") private String address; @SerializedName("place") private PlaceMin place; /** * Wall settings */ @SerializedName("wall") private Integer wall; /** * Photos settings */ @SerializedName("photos") private Integer photos; /** * Video settings */ @SerializedName("video") private Integer video; /** * Audio settings */ @SerializedName("audio") private Integer audio; /** * Docs settings */ @SerializedName("docs") private Integer docs; /** * Topics settings */ @SerializedName("topics") private Integer topics; /** * Wiki settings */ @SerializedName("wiki") private Integer wiki; /** * Information whether the obscene filter is enabled */ @SerializedName("obscene_filter") private BoolInt obsceneFilter; /** * Information whether the stopwords filter is enabled */ @SerializedName("obscene_stopwords") private BoolInt obsceneStopwords; /** * The list of stop words */ @SerializedName("obscene_words") private String obsceneWords; /** * Community access settings */ @SerializedName("access") private Integer access; /** * Community subject ID */ @SerializedName("subject") private Integer subject; @SerializedName("subject_list") private List<SubjectItem> subjectList; /** * URL of the RSS feed */ @SerializedName("rss") private String rss; /** * Community website */ @SerializedName("website") private String website; @SerializedName("events") private Integer events; public String getTitle() { return title; } public String getDescription() { return description; } public String getAddress() { return address; } public PlaceMin getPlace() { return place; } public Integer getWall() { return wall; } public Integer getPhotos() { return photos; } public Integer getVideo() { return video; } public Integer getAudio() { return audio; } public Integer getDocs() { return docs; } public Integer getTopics() { return topics; } public Integer getWiki() { return wiki; } public boolean isObsceneFilter() { return obsceneFilter == BoolInt.YES; } public boolean isObsceneStopwords() { return obsceneStopwords == BoolInt.YES; } public String getObsceneWords() { return obsceneWords; } public Integer getAccess() { return access; } public Integer getSubject() { return subject; } public List<SubjectItem> getSubjectList() { return subjectList; } public String getRss() { return rss; } public String getWebsite() { return website; } public Integer getEvents() { return events; } @Override public int hashCode() { return Objects.hash(title, description, address, place, wall, photos, video, audio, docs, topics, wiki, obsceneFilter, obsceneStopwords, obsceneWords, access, subject, subjectList, rss, website, events); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupSettings that = (GroupSettings) o; return Objects.equals(title, that.title) && Objects.equals(description, that.description) && Objects.equals(address, that.address) && Objects.equals(place, that.place) && Objects.equals(wall, that.wall) && Objects.equals(photos, that.photos) && Objects.equals(video, that.video) && Objects.equals(audio, that.audio) && Objects.equals(docs, that.docs) && Objects.equals(topics, that.topics) && Objects.equals(wiki, that.wiki) && obsceneFilter == that.obsceneFilter && obsceneStopwords == that.obsceneStopwords && Objects.equals(obsceneWords, that.obsceneWords) && Objects.equals(access, that.access) && Objects.equals(subject, that.subject) && Objects.equals(subjectList, that.subjectList) && Objects.equals(rss, that.rss) && Objects.equals(website, that.website) && Objects.equals(events, that.events); } @Override public String toString() { final StringBuilder sb = new StringBuilder("GroupSettings{"); sb.append("title='").append(title).append('\''); sb.append(", description='").append(description).append('\''); sb.append(", address='").append(address).append('\''); sb.append(", place=").append(place); sb.append(", wall=").append(wall); sb.append(", photos=").append(photos); sb.append(", video=").append(video); sb.append(", audio=").append(audio); sb.append(", docs=").append(docs); sb.append(", topics=").append(topics); sb.append(", wiki=").append(wiki); sb.append(", obsceneFilter=").append(obsceneFilter); sb.append(", obsceneStopwords=").append(obsceneStopwords); sb.append(", obsceneWords='").append(obsceneWords).append('\''); sb.append(", access=").append(access); sb.append(", subject=").append(subject); sb.append(", subjectList=").append(subjectList); sb.append(", rss='").append(rss).append('\''); sb.append(", website='").append(website).append('\''); sb.append(", events=").append(events); sb.append('}'); return sb.toString(); } }
The doctors’ union are warning the real scale of consultant vacancies in NHS Scotland is more than double the number listed in the official figures and includes enough doctors to staff a large hospital. A Freedom of Information (FOI) request by BMA Scotland has revealed the actual vacancy rate is 13.9 percent compared to the already high 6.8 percent figure reported by the Information Services Division (ISD) which is used by the Scottish Government. According to BMA Scotland the difference is the equivalent of around 375 whole time equivalent vacancies that are not being recorded by offcial data. The number of “hidden” consultant vacancies was last night described as “staggering” by Scottish Lib Dems health spokesperson Alex Cole-Hamilton. The news came on a day when the number of GPs in training sunk to a five-year low and over 2,000 nursing and midwifery posts remain unfilled with the number of vacancies lying empty for three or more months topping the 1,000 mark. The BMA say many boards are no longer trying to actively recruit to over a fifth of the vacant consultant posts which are ‘likely to be hard to fill posts where attempts to recruit have not been successful’. These unfilled vacancies can be removed temporarily from the overall figure along with posts not yet cleared for advert - which are also excluded. The doctors’ union also highlight the problem of locums being used to fill posts with nearly 40 percent of vacancies being covered in this way. They say that filling vacancies with locums is a temporary solution and does not provide long term sustainability. Another concern in this context is the rising number of posts in the official figures which are vacant for 6 months or more, which is up by 1.7 percent on the same time last year – again demonstrating posts are hard to fill. Four years ago, the BMA conducted similar research, which also reflected concern that vacancy rates were being underestimated and offered to work with the Scottish Government to allow a more complete picture of consultant vacancies to be compiled. Dr Simon Barker, Chair of BMA Scotland’s Consultant Committee said: "Our members often tell us that the published consultant vacancy figures don’t reflect the reality of the huge challenges of working on the frontline of Scotland’s NHS. The new data from our FOI suggests they are absolutely right to feel that way. “This analysis shows that by not including certain categories of vacancy, the official statistics simply don’t provide the full picture of the scale of consultant vacancies in our NHS. “For example, vacant posts that go unfilled are then removed from official figures. Our FOI data suggests that when these are added back in, and few would argue that these aren’t real vacancies, the actual vacancy rate is substantially higher than boards report. Collectively, that means there are potentially around 375 vacancies on top of those counted by official figures - the equivalent of a large hospital empty of its senior doctors. “We welcome efforts made to increase the consultant workforce in recent years, and of course this is a complex and difficult issue. But we simply won’t make any progress in making sure we have a properly staffed NHS if we continue to work off incomplete figures or rely complacently on increases in the overall headcount. That simply isn’t good enough – for patients or doctors." He added: “That’s because, behind these figures are senior doctors who are pushed into covering the work of these vacant posts. "These are professionals doing their absolute best, but under these conditions we risk burnout and stretching people beyond their limits. Inevitably this leads to more people leaving the profession early and the high standard of care for patients that we all strive for, not being achieved. The BMA stated that they are not suggesting the official figures are inaccurate, rather they don't capture the full picture of consultant vacancies across the country and its impact on the service. Alex Cole-Hamilton said: "The apparent extent of hidden consultant vacancies is staggering. There’s no way the Scottish Government can take effective action to counter shortages if they’re working off wildly wrong numbers.
<gh_stars>1-10 package org.folio.auth.authtokenmodule; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertThat; import org.apache.logging.log4j.Level; import org.junit.Test; import org.junit.runner.RunWith; import com.nimbusds.jose.JOSEException; import io.vertx.core.Vertx; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; @RunWith(VertxUnitRunner.class) public class MainVerticleTest { @Test public void deployAndUndeploy(TestContext context) { Vertx vertx = Vertx.vertx(); vertx.deployVerticle(MainVerticle.class.getName(), context.asyncAssertSuccess(run -> vertx.close(context.asyncAssertSuccess()))); } @Test public void failStartOnInvalidAlgorithm(TestContext context) { class MainVerticleInvalidAlgorithm extends MainVerticle { @Override TokenCreator getTokenCreator() throws JOSEException { TokenCreator tokenCreator = super.getTokenCreator(); tokenCreator.setJweHeader(null); return tokenCreator; } } Vertx.vertx().deployVerticle(new MainVerticleInvalidAlgorithm(), context.asyncAssertFailure(fail -> assertThat(fail.getMessage(), containsString("TokenCreator")))); } @Test public void setLogLevel(TestContext context) { Level old = MainVerticle.setLogLevel(Level.ERROR); MainVerticle.setLogLevel("info"); Level last = MainVerticle.setLogLevel(old); context.assertEquals(Level.INFO, last); } }
Encouraging smoking cessation among disadvantaged groups: a qualitative study of the financial aspects of cessation. INTRODUCTION AND AIMS This study aimed to explore perceptions about financial aspects of smoking cessation among a group of disadvantaged welfare agency clients and their carers. DESIGN AND METHODS Qualitative focus groups and in-depth interviews were supplemented with participant exit surveys about preferred smoking cessation strategies. Each discussion was audiotaped, transcribed and analysed using a thematic analysis. The setting was six non-government community welfare service organisations operating in New South Wales, Australia. Eleven social services offered by these organisations participated. Thirty two clients participated in six client focus groups, 35 staff participated in six staff focus groups and eight manager telephone interviews were conducted. RESULTS Clients indicated that the cost of nicotine replacement therapy was a barrier to its use and that financial incentives were acceptable. Of the 16 possible strategies listed in the exit survey, the three selected as the most preferred by clients incorporated financial or non-financial assistance. By contrast, staff and managers selected financial and non-financial incentives as the least preferred and least feasible strategies. DISCUSSION AND CONCLUSIONS The study found high acceptance of incentives as a smoking cessation strategy among a disadvantaged group of non-government welfare service clients. The comparatively low level of desirability and feasibility from the perspective of service staff and managers suggests implementation of such an approach within the community service setting requires careful further testing.
The Non-Erythropoietic EPO Analogue Cibinetide Inhibits Osteoclastogenesis In Vitro and Increases Bone Mineral Density in Mice The two erythropoietin (EPO) receptor forms mediate different cellular responses to erythropoietin. While hematopoiesis is mediated via the homodimeric EPO receptor (EPOR), tissue protection is conferred via a heteromer composed of EPOR and CD131. In the skeletal system, EPO stimulates osteoclast precursors and induces bone loss. However, the underlying molecular mechanisms are still elusive. Here, we evaluated the role of the heteromeric complex in bone metabolism in vivo and in vitro by using Cibinetide (CIB), a non-erythropoietic EPO analogue that exclusively binds the heteromeric receptor. CIB is administered either alone or in combination with EPO. One month of CIB treatment significantly increased the cortical (~5.8%) and trabecular (~5.2%) bone mineral density in C57BL/6J WT female mice. Similarly, administration of CIB for five consecutive days to female mice that concurrently received EPO on days one and four, reduced the number of osteoclast progenitors, defined by flow cytometry as Lin−CD11b−Ly6Chi CD115+, by 42.8% compared to treatment with EPO alone. In addition, CIB alone or in combination with EPO inhibited osteoclastogenesis in vitro. Our findings introduce CIB either as a stand-alone treatment, or in combination with EPO, as an appealing candidate for the treatment of the bone loss that accompanies EPO treatment. Introduction Erythropoietin (EPO) is a glycoprotein hormone that is produced mainly by the kidneys and plays a crucial role in regulating erythropoiesis. The secreted hormone acts by binding to the EPO receptor (EPOR) on erythroid progenitor cells in the bone marrow (BM), and stimulates their proliferation, differentiation, and survival. Recombinant human EPO (rHuEPO) is administered clinically for the treatment of anemia that is secondary to chronic kidney disease, or for certain hematological malignancies. In addition to hematopoietic cells, EPOR has also been detected in many other cell types and is associated with cytoprotective effects in these non-hematopoietic tissues. While erythropoiesis is mediated by the canonical EPOR homodimer, the tissue protective effects of EPO are thought to act through the heteromeric innate repair receptor (IRR), which is composed of EPOR and the -common receptor subunit (cR, CD131). This subunit is also used for signaling by other type 1 cytokine receptors, such as GM-CSF, IL-3, and IL-5. A number of non-hematopoietic EPO analogs have now been developed that selectively activate the IRR and confer tissue protection without a measurable effect on the EPOR-EPOR homodimer and, consequently, without eliciting erythropoiesis or the potential associated adverse effects. One promising candidate is Cibinetide (pHBSP; ARA 290) which is an 11-amino acid peptide that is modeled from the three-dimensional structure of helix B of the EPO molecule. Cibinetide interacts with the IRR and has demonstrated efficacy in a number of animal models of angiogenic potential, autoimmune diseases, neuropathy, and organ transplantation. Bone is a highly dynamic tissue that undergoes continuous remodeling throughout life in a process involving the concerted actions of monocyte-derived osteoclasts that resorb mineralized tissue, and mesenchymal osteoblasts that deposit new bone. The tight regulation of the osteoblastic and osteoclastic lineages is thus crucial for the control of bone turnover. The discovery that EPO has pleiotropic roles in non-hematopoietic tissues has prompted an investigation of the role of EPO in bone homeostasis. This is due to the proximity of the bone and hematopoietic cells in the bone marrow milieu as well as the documented crosstalk between the hematopoietic and skeletal systems. In that respect, we, and others, have shown that high EPO levels (both exogenously administered as well as a result of over-expression) lead to a dramatic bone loss in mouse models. In accordance with these results, a growing body of evidence now links high EPO levels to bone loss in humans. Monocyte differentiation into osteoclasts is driven by the receptor activator for nuclear factor kappa B (RANK)/RANK ligand (RANKL)/osteoprotegerin (OPG) system, and macrophage colony stimulating factor (M-CSF, CD115). In the bone marrow, these preosteoclast macrophages express EPOR and recent studies from our lab indicate that EPO stimulates osteoclastogenesis by acting directly on osteoclast precursors. However, the underlying molecular mechanism that is responsible for EPO-induced bone loss is still unknown. This study was designed to investigate the role of the EPO-R forms in bone metabolism. For this purpose, we used the non-erythropoietic EPO analog Cibinetide, which acts exclusively on the EPOR/CD131 complex. Here we present data suggesting that Cibinetide treatment in murine models is associated with a bone-preserving effect when injected as a single agent. Moreover, Cibinetide counteracts the stimulatory effect of EPO on preosteoclasts, making it a very promising anti resorptive agent, either when given alone or in combination with EPO. Cibinetide (CIB) Inhibits Osteoclastogenesis In Vitro, in a Dose Dependent Manner, without Cytotoxic Effects As the first step, we examined the effect of Cibinetide on the differentiation of bone marrow derived macrophages (BMDM) into osteoclasts as mediated by M-CSF and RANKL, which are both essential for osteoclast differentiation. TRAP staining was used to evaluate the area that was covered by osteoclasts, with treatment with EPO as the positive control for increased osteoclastogenesis. Cibinetide suppressed osteoclastogenesis in a dosedependent manner. At low Cibinetide levels (3 M), osteoclastogenesis was similar to that which was observed in the control (M-CSF and RANKL only) cultures (Figure 1a,b). To exclude the possibility that inhibition of osteoclastogenesis by Cibinetide was due to the reduced viability of the osteoclast precursors, we examined the viability by MTT assay. The RANKL only) cultures (Figure 1a,b). To exclude the possibility that inhibition of osteoclastogenesis by Cibinetide was due to the reduced viability of the osteoclast precursors, we examined the viability by MTT assay. The results confirmed that Cibinetide has no cytotoxic effects at concentrations that effectively inhibited osteoclast differentiation (Figure 1c). (3,30, 300 M). After 48 h, MTT reagent was added to each well and the absorbance was measured at 560 nm. Data from at least three independent experiments are shown as mean ± SEM. * p < 0.05, **** p < 0.0001. Cibinetide (CIB) Exerts Its Inhibitory Effects in the Early Stages of Osteoclastogenesis To determine the stage at which Cibinetide inhibits osteoclastogenesis, BMDM that were previously cultured with M-CSF only were also supplemented with RANKL at Day 0, and were treated with Cibinetide (150 M) at different times between days 0 and 4, as shown in the schematic representation ( Figure 2a). Inhibition of osteoclastogenesis was most effective when Cibinetide was introduced into the cultures at day 0. Reduction of osteoclastogenesis by Cibinetide was far less pronounced when the compound was added at a later time point. These findings support the notion that the anti-osteoclastogenic effect of Cibinetide is manifested most strongly in the initial stages of osteoclast differentiation (Figure 2b,c). (3,30, 300 M). After 48 h, MTT reagent was added to each well and the absorbance was measured at 560 nm. Data from at least three independent experiments are shown as mean ± SEM. * p < 0.05, **** p < 0.0001. Cibinetide (CIB) Exerts Its Inhibitory Effects in the Early Stages of Osteoclastogenesis To determine the stage at which Cibinetide inhibits osteoclastogenesis, BMDM that were previously cultured with M-CSF only were also supplemented with RANKL at Day 0, and were treated with Cibinetide (150 M) at different times between days 0 and 4, as shown in the schematic representation ( Figure 2a). Inhibition of osteoclastogenesis was most effective when Cibinetide was introduced into the cultures at day 0. Reduction of osteoclastogenesis by Cibinetide was far less pronounced when the compound was added at a later time point. These findings support the notion that the anti-osteoclastogenic effect of Cibinetide is manifested most strongly in the initial stages of osteoclast differentiation (Figure 2b,c). Cibinetide (CIB) Suppresses the Expression of Osteoclast-Related Genes To further examine the inhibitory effects of Cibinetide on osteoclastogenesis in response to RANKL, we examined the expression of the well-known osteoclast-related genes, Cathepsin K (CTSK), OSCAR, OC-STAMP, DC-STAMP, and NFATC1. The results ( Figure 3) indicated that Cibinetide significantly inhibited the expression of all these osteoclast marker genes. These results are in accordance with the inhibitory effect of Cibinetide on osteoclastogenesis, as presented in Figures 1 and 2. Collectively, these results confirm that Cibinetide suppresses osteoclastogenesis in vitro. Cibinetide (CIB) Suppresses the Expression of Osteoclast-Related Genes To further examine the inhibitory effects of Cibinetide on osteoclastogenesis in response to RANKL, we examined the expression of the well-known osteoclast-related genes, Cathepsin K (CTSK), OSCAR, OC-STAMP, DC-STAMP, and NFATC1. The results ( Figure 3) indicated that Cibinetide significantly inhibited the expression of all these osteoclast marker genes. These results are in accordance with the inhibitory effect of Cibinetide on osteoclastogenesis, as presented in Figures 1 and 2. Collectively, these results confirm that Cibinetide suppresses osteoclastogenesis in vitro.. Cibinetide (CIB) downregulates osteoclast-specific genes' expression. PCR analysis of osteoclast-specific gene expression in BMDMs stimulated with MCSF + RANKL for five days with or without Cibinetide (150 M). The expression of Cathepsin K(CTSK), OSCAR, DC-STAMP, OC-STAMP, and NFATC1 were normalized to the housekeeping gene HPRT and then to the mean of the control group. The data are expressed as mean ± SEM of three independent experiments. * p < 0.05, ** p < 0.01, *** p < 0.001, and **** p < 0.0001. Cibinetide (CIB) Overrides the Pro-Osteoclastogenic Effects of LPS and EPO To determine whether the anti osteoclastogenesis effect of Cibinetide can counter enhanced osteoclastogenesis, such as that which is conferred by EPO or LPS, Cibinetide was added to BMDM together with EPO or LPS as follows: BMDMs were treated with M-CSF and RANKL (50 ng/mL) together with EPO (10 U/mL) and/or Cibinetide (150 M). On the second day, LPS (10 ng/mL) was introduced to the RANKL+M-CSF or to the RANKL+M-CSF+ Cibinetide cultures. On the fourth day, multinucleated osteoclasts were stained for TRAP. The results demonstrate that Cibinetide inhibits osteoclastogenesis even in the presence of LPS or EPO (Figure 4a. Cibinetide (CIB) downregulates osteoclast-specific genes' expression. PCR analysis of osteoclast-specific gene expression in BMDMs stimulated with MCSF + RANKL for five days with or without Cibinetide (150 M). The expression of Cathepsin K(CTSK), OSCAR, DC-STAMP, OC-STAMP, and NFATC1 were normalized to the housekeeping gene HPRT and then to the mean of the control group. The data are expressed as mean ± SEM of three independent experiments. * p < 0.05, ** p < 0.01, *** p < 0.001, and **** p < 0.0001. Cibinetide (CIB) Overrides the Pro-Osteoclastogenic Effects of LPS and EPO To determine whether the anti osteoclastogenesis effect of Cibinetide can counter enhanced osteoclastogenesis, such as that which is conferred by EPO or LPS, Cibinetide was added to BMDM together with EPO or LPS as follows: BMDMs were treated with M-CSF and RANKL (50 ng/mL) together with EPO (10 U/mL) and/or Cibinetide (150 M). On the second day, LPS (10 ng/mL) was introduced to the RANKL+M-CSF or to the RANKL+M-CSF+ Cibinetide cultures. On the fourth day, multinucleated osteoclasts were stained for TRAP. The results demonstrate that Cibinetide inhibits osteoclastogenesis even in the presence of LPS or EPO (Figure 4a Cibinetide (CIB) Increases Tissue Mineral Density (TMD) in Both Cortical and Trabecular Bone To investigate the effect of Cibinetide on bone density, we injected 12-week-old female C57BL/6J mice with Cibinetide (120 g/kg 3/week for 4 weeks). At the end of the fourth week, hemoglobin levels were measured and the femurs were analyzed by CT. As expected, Cibinetide treatment did not have any effect on hemoglobin levels ( Figure 5a). However, it did cause a 5.8% increase in the cortical TMD and a 5.2% increase in the trabecular TMD, while the trabecular bone fraction (BV/TV) was unchanged (Figure 5b,c). To gain more insight into the effect of Cibinetide on bone, we analyzed the expression level of OPG and RANKL in the whole bones of Cibinetide-treated and untreated mice. In line with the observed increase in TMD, Cibinetide treatment resulted in a significant 52.4% increase in the expression of OPG in the whole bone, with no change in the expression of RANKL (Figure 5d). Cibinetide (CIB) Increases Tissue Mineral Density (TMD) in Both Cortical and Trabecular Bone To investigate the effect of Cibinetide on bone density, we injected 12-week-old female C57BL/6J mice with Cibinetide (120 g/kg 3/week for 4 weeks). At the end of the fourth week, hemoglobin levels were measured and the femurs were analyzed by CT. As expected, Cibinetide treatment did not have any effect on hemoglobin levels ( Figure 5a). However, it did cause a 5.8% increase in the cortical TMD and a 5.2% increase in the trabecular TMD, while the trabecular bone fraction (BV/TV) was unchanged (Figure 5b,c). To gain more insight into the effect of Cibinetide on bone, we analyzed the expression level of OPG and RANKL in the whole bones of Cibinetide-treated and untreated mice. In line with the observed increase in TMD, Cibinetide treatment resulted in a significant 52.4% increase in the expression of OPG in the whole bone, with no change in the expression of RANKL (Figure 5d). Cibinetide (CIB) Modulates Alkaline Phosphatase (ALP) and CD115 Expression on CD11b − Bone Marrow Cells As the next stage, we assessed the effect of Cibinetide on the percentage of preosteoblasts (CD11b − ALP + ) as well as preosteoclasts (CD11b − CD115 + ) in the bone marrow. The results (Figure 6a), indicate that Cibinetide treatment did not affect the percentage of these two cell populations in the bone marrow. Importantly, Cibinetide treatment resulted in a 25.59% increase in ALP expression and a 17.79% decrease in CD115 expression on the surface of the CD11b − bone marrow cells (Figure 6b,c). These results further support a Cibinetide-mediated increase in osteoblast mineralizing activity and a decrease in the potential for osteoclast differentiation and are in accordance with our findings that are presented in Figure 5. Cibinetide (CIB) Modulates Alkaline Phosphatase (ALP) and CD115 Expression on CD11b -Bone Marrow Cells As the next stage, we assessed the effect of Cibinetide on the percentage of preosteoblasts (CD11b -ALP + ) as well as preosteoclasts (CD11b -CD115 + ) in the bone marrow. The results (Figure 6a), indicate that Cibinetide treatment did not affect the percentage of these two cell populations in the bone marrow. Importantly, Cibinetide treatment resulted in a 25.59% increase in ALP expression and a 17.79% decrease in CD115 expression on the surface of the CD11b -bone marrow cells (Figure 6b,c). These results decrease in the potential for osteoclast differentiation and are in accordance with our findings that are presented in Figure 5. Cibinetide (CIB) Overrides the Pro-Osteoclastogenic Effects of EPO In Vivo To evaluate the capacity of Cibinetide to counteract the effect of EPO on osteoclasts in vivo, we performed a short-term experiment in which 13-week-old female mice were administered Cibinetide (300 g/kg) for 5 consecutive days, with 2 injections of 120 U EPO on days 1 and 4. These mice were compared to mice that were receiving either Cibinetide or EPO and also to untreated control mice. Flow cytometry analysis revealed an 81.06% increase in the number of osteoclast progenitors, defined as Lin − CD11b − Ly6C hi CD115 +, in the EPO injected mice. However, this was reduced by 42.8% in the EPO + Cibinetide-injected mice compared to the EPO-injected mice, without any change in the numbers of osteoblast precursors (Figure 7a). Moreover, Cibinetide treatment downregulated CD115 expression on the osteoclast precursors both when given alone and in combination with EPO, while EPO had no effect (Figure 7b). As the next step, we performed an ex vivo osteoclastogenesis assay where a fixed number of BM cells that were collected from mice in each treatment group were cultured in the presence of M-CSF + RANKL. The number of osteoclasts that were measured in this assay reflects the proportion of osteoclast progenitors in the mice at the end of the treatment. The results indicated that cultures that were derived from the EPO-treated mice exhibited a higher degree of osteoclastogenesis than the control cultures, although the difference did not reach statistical significance. Of note, a single injection of EPO at a higher dose (180 U) resulted in an increase both in the proportion of osteoclast progenitors and in the level of CD115 surface expression, as measured after 48 h (Supplementary Materials, Figure S1)). Importantly, the level of osteoclastogenesis in cells from the Cibinetide and EPO + Cibinetide-injected mice was significantly lower than that from either the control or EPO groups (Figure 7c). Cibinetide (CIB) Overrides the Pro-Osteoclastogenic Effects of EPO In Vivo To evaluate the capacity of Cibinetide to counteract the effect of EPO on osteoclasts in vivo, we performed a short-term experiment in which 13-week-old female mice were administered Cibinetide (300 g/kg) for 5 consecutive days, with 2 injections of 120 U EPO on days 1 and 4. These mice were compared to mice that were receiving either Cibinetide or EPO and also to untreated control mice. Flow cytometry analysis revealed an 81.06% increase in the number of osteoclast progenitors, defined as Lin -CD11b -Ly6C hi CD115 +, in the EPO injected mice. However, this was reduced by 42.8% in the EPO + Cibinetide-injected mice compared to the EPO-injected mice, without any change in the numbers of osteoblast precursors (Figure 7a). Moreover, Cibinetide treatment downregulated CD115 expression on the osteoclast precursors both when given alone and in combination with EPO, while EPO had no effect (Figure 7b). As the next step, we performed an ex vivo osteoclastogenesis assay where a fixed number of BM cells that were collected from mice in each treatment group were cultured in the presence of M-CSF + RANKL. The number of osteoclasts that were measured in this assay reflects the proportion of osteoclast progenitors in the mice at the end of the treatment. The results indicated that cultures that were derived from the EPO-treated mice exhibited a higher degree of osteoclastogenesis than the control cultures, although the difference did not reach statistical significance. Of note, a single injection of EPO at a higher dose (180 U) resulted in an increase both in the proportion of osteoclast progenitors and in the level of CD115 surface expression, as measured after 48 h (Supplementary Materials, Figure S1)). Importantly, the level of osteoclastogenesis in cells from the Cibinetide and EPO + Cibinetide-injected mice was significantly lower than that from either the control or EPO groups (Figure 7c). With this short-term treatment, no changes in the bone parameters were detected by CT in any of the treatment groups (Supplementary Materials, Figure S2). With this short-term treatment, no changes in the bone parameters were detected by CT in any of the treatment groups (Supplementary Materials, Figure S2). EPO Maintains Erythropoietic Activity in the Presence of Cibinetide (CIB) To exclude the possibility that Cibinetide antagonizes the erythropoietic effects of EPO on erythroid cells, we measured hemoglobin levels and spleen weights. In addition, we evaluated the levels of TER119 + erythroid progenitor cells in the spleen and bone marrow by flow cytometry. As expected, the EPO treatment resulted in a significant increase in all these parameters and none of the erythropoietic changes that were mediated by EPO were affected by Cibinetide (Figure 8). EPO Maintains Erythropoietic Activity in the Presence of Cibinetide (CIB) To exclude the possibility that Cibinetide antagonizes the erythropoietic effects of EPO on erythroid cells, we measured hemoglobin levels and spleen weights. In addition, we evaluated the levels of TER119 + erythroid progenitor cells in the spleen and bone marrow by flow cytometry. As expected, the EPO treatment resulted in a significant increase in all these parameters and none of the erythropoietic changes that were mediated by EPO were affected by Cibinetide (Figure 8). Discussion While the beneficial anti-inflammatory effects of Cibinetide, a selective IRR agonist, have been well-documented in multiple systems for over a decade now, there is no record of the effect on the skeletal system, which is one of the most studied targets of EPO. This study is the first to address the in vitro and in vivo effects of Cibinetide on bone metabolism, either alone or in combination with EPO. Our results reveal that Cibinetide can counteract the stimulatory effects of EPO on the monocytic-lineage by decreasing the pool of osteoclast precursors that were defined as Lin − CD11b − Ly6C hi CD115 + in the bone marrow, and by further decreasing the expression of CD115 in this population. The observation that this is achieved without interference with the erythropoietic activity of EPO, reflects the specificity of the effect on osteoclast progenitors in the bone marrow. The finding that Cibinetide acts in the early stages of osteoclast differentiation is evidenced by the downregulation of the key transcription factor NFATC1, as well as suppression of the osteoclast differentiation-related genes CTSK, OSCAR, DC-STAMP, and OC-STAMP. Interestingly, EPO has previously been reported by us and others to have an osteoclast stimulatory effect. These seemingly opposing effects of the two EPOR ligands on preosteoclasts in vitro motivated us to examine the interplay between the two ligands during osteoclastogenesis. Importantly, the results revealed that the inhibitory effect of Cibinetide could negate the stimulatory effect that was induced by EPO. Considering the potent anti-inflammatory activities of Cibinetide in LPS-activated macrophages, and the fact that LPS is a potent inducer of inflammation and inflammatory bone loss, our finding that Cibinetide mitigates LPS-induced osteoclastogenesis may have significant clinical applications, for example in inflammation-induced osteolysis (e.g., ). It should be noted that the components of the heteromeric EPOR and CD131 complex are usually intracellular in the non-inflammatory state and typically are not expressed by healthy tissues although they are rapidly induced under stress conditions. The robust in vitro anti-osteoclastogenic effects of Cibinetide (in the presence of RANKL and M-CSF), prompted us to investigate whether Cibinetide can also confer a bone preserving effect in vivo, in healthy mice. The administration of Cibinetide to wild-type female mice resulted in a significant increase in TMD, which is an important contributor to bone mineral density (BMD) in cortical and trabecular bone, while the BV/TV remained unchanged after Cibinetide treatment. TMD is a measure of the mineral content inside the trabecular and cortical bone whereas BV/TV measures the amount of trabecular and cortical bone over the total volume of the region of interest. At the resolution that was employed here (10 m), TMD will thus reflect the mineral density as well as the microscopic porosity (pores of <10-15 m) as the measured bone volume will include these small voids that cannot be detected due to the resolution. This microscopic porosity includes osteocyte lacunae. In our study, the Cibinetide-induced increase in TMD may result from increased mineralization of the bone tissue and/or narrowing of the osteocyte lacunae. BMD combines both TMD and BV/TV. It should be noted that despite the seemingly low increase in TMD (~5%), this is a clinically relevant finding since a 5-10% decline is associated with approximately 50-100% higher fracture rates. Interestingly, the Cibinetide results are very different from the effect that was observed after exogenous EPO administration in mice, where a massive decrease in trabecular bone fraction is evident albeit with no effect on TMD (data not shown). The increased expression levels of OPG in the bone tissue of Cibinetide treated mice, are a possible mechanism for the reduced osteoclastogenesis, reduced bone resorption and increased TMD. This assumption is further supported by a recent study reporting that EPOR regulates OPG expression in osteo-progenitors and regulates osteoblast function and osteoblastmediated osteoclastogenesis via the RANKL/OPG axis. The question of whether EPO acts on osteoblasts via the EPOR/CD131 heterodimer remains to be addressed. Despite the similar proportions of preosteoblasts and preosteoclasts in the bone marrow of Cibinetide-injected mice, we found an increased surface expression of alkaline phosphatase, an early osteogenic marker of bone formation and mineralization on preosteoblasts. In addition, there was a decrease in the expression of CD115, one of the receptors for osteoclastogenic factors which acts as a potent stimulator of RANK expression on preosteoclasts. In line with these findings, the downregulation, blockade, or depletion of CD115 has been shown to suppress the formation and activity of osteoclasts and to attenuate the pathological bone resorption that is seen in inflammatory bone destruction and osteoporosis. Similarly, TLR ligands mediate the downregulation of CD115 from the cell surface and suppress osteoclastogenesis. Taken together, our data provide evidence that Cibinetide acts on preosteoblasts to increase bone formation and also reduces bone resorption capacity by suppressing the differentiation of preosteoclasts to osteoclasts. Another cytokine receptor that shares the chain (CD131) of the heteromeric complex is IL-3. In one study, IL-3 was shown to decrease the expression of CD115 glycoprotein and mRNA in a murine myeloid precursor cell line and in another study, it was found to inhibit human osteoclastogenesis and bone resorption through downregulation of CD115 and diverting the cells to the dendritic cell lineage. These findings raise certain questions regarding the role of the CD131 subunit in bone remodeling. In this context, it is interesting that CD131 knockout mice exhibit normal development, although they develop pulmonary peribronchovascular lymphoid infiltrates and areas resembling alveolar proteinosis, and the numbers of eosinophils are reduced in the peripheral blood and bone marrow. Notably, the tissue-protective properties of EPO do not function in these animals although they display normal hematopoiesis. In another study, the very challenging conditional deletion of CD131 in a specific subpopulation through the myeloid lineage CCR2 + Ly6C hi was achieved and used to study experimental autoimmune encephalomyelitis (EAE). In the future, we predict that a similar approach of generating osteoclast-specific and osteoblast-specific conditional CD131 knockout may strengthen our conclusion that the heteromer EPOR/CD131 mediates the effects of EPO and Cibinetide in these bone cells. The current study used only a short-term treatment of the combination of Cibinetide and EPO. Our choice of a five-day treatment regimen was based on our findings of a very early and rapid increase in osteoclast progenitors two days after a single EPO injection (2.25-fold increase vs. untreated). With our short duration of treatment, we could not detect any changes in bone microarchitecture in any of the treated groups, but we did observe significant differences in the osteoclast lineage, in line with the skeletal effects of CIB that were observed ( Figure 5). The findings that are reported here add more complexity to the notion that the two ligands induce similar tissue protective activities and differ only in their erythropoietic capacity. To our knowledge, this is the first scenario in which Cibinetide and EPO have opposing effects. Whether this is due to different pharmacokinetics or to diverging signaling pathways remains to be elucidated. In this context, it should be noted that although Cibinetide has a short plasma half-life (~2 min), it has sustained biological effects, even when injected with EPO, which is a molecule with a long half-life (4-6 h). In light of the fact that all of the currently used anti-resorptive drugs for the treatment of osteoporosis have adverse side effects, an intense focus has been directed toward developing new therapeutic agents that can inhibit bone resorption and enhance bone formation. Our data introduce Cibinetide as an appealing candidate for the treatment of bone loss either as a stand-alone therapy for osteolytic pathologies ranging from cancer to rheumatoid arthritis and osteoporosis, or in combination with EPO for patients with anemia or cancer. The results that are presented here suggest that treatment with Cibinetide and EPO may prevent or attenuate bone loss while preserving the erythropoietic actions of EPO. Materials Alpha-MEM and fetal bovine serum (FBS), were purchased from Rhenium (Modiin, Israel) and culture plates were from Corning (New York, NY, USA). LPS from the E. coli strain 0127:B8 (Sigma) was reconstituted in sterile double distilled water (DDW) as a 1 mg/mL stock solution and kept at −20 C. Dulbecco's Phosphate Buffered Saline (DPBS) was purchased from Biological Industries. As a source of M-CSF, we used supernatant from CMG 14-12 cells containing 1.3 g/mL M-CSF. RANKL was purchased from R&D Systems, Minneapolis, MN, USA. The peptide Cibinetide was kindly provided by Araim Pharmaceuticals, Inc. (Ossining, NY, USA). Erythropoietin (EPO) was obtained from GMP-manufactured sterile syringes containing rHuEPO (Epoetin alfa, Eprex ® ) as used for patient care. These were kindly provided by Janssen Cilag, Israel, and were employed throughout this study. Animals Female wild-type mice of the inbred strain C57BL/6J-RccHsd, aged 8-13 weeks, were purchased from Envigo (Jerusalem, Israel) and housed at the Tel-Aviv University animal facility. Animal care and all procedures were in accordance with, and with the approval of, the Tel Aviv University Institutional Animal Care and Use Committee (Permit number 01-19-032). Cell Culture In vitro osteoclastogenesis: Bone marrow cells were harvested from the femurs and tibias of 8-to 13-week-old female mice. The cells were seeded on tissue-culture treated plates in standard medium (-MEM supplemented with 10% fetal bovine serum). On the following day, the non-adherent cells were seeded in non-tissue culture-treated plates in standard medium supplemented with 100 ng/mL M-CSF, which induces cell proliferation and differentiation into preosteoclasts. For the osteoclastogenesis assay, preosteoclasts were plated in 96-well plates (8000 cells per well) with standard medium that was supplemented with 20 ng/mL M-CSF and 50 ng/mL RANKL (R&D Systems), which was replaced every 2 days. Treatments in culture (EPO, Cibinetide, LPS) were added together with RANKL, as indicated. On the 4-5th day, the multinucleated osteoclasts were stained using a tartrate-resistant acid phosphatase (TRAP) kit (Sigma-Aldrich, St Louis, MO, USA) and the relative TRAP-positive surface was measured using ImageJ software. Ex vivo osteoclastogenesis: The bone marrow cells were harvested from the femurs and tibias of 13-week-old female mice and were then seeded into tissue culture-treated plates in standard medium and allowed to attach overnight. Non-adherent cells were plated into 96 well plates in standard medium that was supplemented with M-CSF (in the form of 2% v/v culture supernatant from CMG 14-12 cells), and 50 ng/mL recombinant murine RANKL. The medium was replaced every other day. After 6-7 days, the cells were stained for tartrate-resistant acid phosphatase (TRAP) and the relative TRAP-positive surface was measured using ImageJ software. Microcomputed Tomography (microCT) The femurs (one per mouse) were examined using the CT50 system (Scanco Medical AG, Wangen-Brttisellen, Switzerland). Briefly, scans were performed at a 10 m resolution, 90 kV energy, 114 mA intensity, and 1100 msec integration time. The mineralized tissues were segmented by a global thresholding procedure following Gaussian filtration of the stacked tomographic images. Trabecular bone parameters were measured in the secondary spongiosa of the distal femoral metaphysis. Cortical parameters were determined in a 1 mm height ring in the mid-diaphyseal region. Hemoglobin Levels Hemoglobin (Hgb) levels were measured in venous blood (that was drawn from the facial vein) by means of a "Mission Plus" hemoglobin/hematocrit meter (Acon, San Diego, CA, USA). MTT (3-(4,5-Dimethylthiazol-2-yl)-2,5-Diphenyltetrazolium Bromide) Assay Cell viability was determined using an MTT assay, essentially as described previously. The bone marrow-derived macrophages (BMDM) were seeded into 96-well plates (1 10 4 cells/well) and then incubated with 100 ng/mL M-CSF in the presence of various concentrations of Cibinetide. After 48 h of incubation, MTT (0.5 mg/mL) was added to each well for 3 h. At the end of the incubation, the insoluble formazan products were dissolved in acidic isopropanol, and absorbance at 560 nm was measured to assess the number of viable cells (proliferation and cytotoxicity). Flow Cytometry The bone marrow (BM) cells were flushed from the femurs or tibias, and the red blood cells were lysed using ACK lysis buffer (Quality Biological, Gaithersburg, MD). The cells were then stained for 20 min at 4 C with conjugated anti-mouse antibodies (see Table 1 for a list of the antibodies that were used). After this time, cells were washed with PBS containing 1% FBS and analyzed by either Gallios or Cytoflex flow cytometers and Kaluza or CytExpert software (all from Beckman Coulter, Indianapolis, Indiana 46268, USA). Real-Time RT PCR Total RNA was extracted from BMDM using the TriRNA Pure kit (Cat#TRPD200, Geneaid, New Taipei City, Taiwan) and cDNA was synthesized using the qScript cDNA synthesis kit (Quantabio, MA, USA). "Real-time" quantitative PCR (RQ-PCR) was performed on a StepOnePlus instrument using the SYBR Green reagent (both from Applied Biosystems, CA, USA). The relative gene expression was calculated using the ∆∆CT method following normalization to the expression of HPRT as a housekeeping gene. The primers that were used for PCR were as follows: Statistical Analysis The values are expressed as mean ± SEM (standard error of the mean). A Student's t-test was used for calculating the statistical significance when comparing two groups of variables. In experiments with >2 groups of variables, a one-way ANOVA was applied. The
package de.shoppinglist.android.adapter; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import de.shoppinglist.android.R; import de.shoppinglist.android.bean.Store; import de.shoppinglist.android.helper.ProcessColorHelper; public class StoreAdapter extends ArrayAdapter<Store> { @SuppressWarnings("unused") private final Context context; private final List<Store> values; public StoreAdapter(final Context context, final List<Store> values) { super(context, R.layout.list_row, values); this.context = context; this.values = values; } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { final TextView textView = (TextView) super.getView(position, convertView, parent); final Store storeToBeShown = this.values.get(position); final int colorToUse = ProcessColorHelper.getColorForProcess(storeToBeShown.getAlreadyCheckedProducts(), storeToBeShown.getCountProducts()); textView.setText(storeToBeShown.toString()); textView.setTextColor(colorToUse); return textView; } }
But in recent years, quantum computing has caught the attention of the corporate world. Microsoft established a significant quantum computing research effort in 2006, creating the Station Q research group at the University of California, Santa Barbara. Since then, I.B.M., Northrop Grumman and BBN Technologies have also begun quantum computing research focused on earlier efforts to create qubits based on measuring the spin of an electron or the polarization of a photon. While scientists have created individual qubits, they are extremely fragile, and creating the arrays of hundreds or thousands of circuits necessary to build a useful quantum computer has proved daunting. D-Wave Systems, a Canadian company that has had support from NASA, Google and Lockheed Martin, has made claims that it has been able to speed up some computing problems based on what it describes as “the first commercial quantum computer.” On Thursday, however, an independent group of scientists reported in the journal Science that they had so far found no evidence of the kind of speedup that is expected from a quantum computer in tests of a 503 qubit D-Wave computer. The company said through a spokesman that the kinds of problems the scientists evaluated would not benefit from the D-Wave design. Microsoft’s topological approach is generally perceived as the most high-risk by scientists, because the type of exotic anyon particle needed to generate qubits has not been definitively proved to exist. That may change soon. The company has been spending heavily and is contributing to 10 of the roughly 20 academic research groups exploring a long-hypothesized class of subatomic particles known as Majorana fermions. Beyond being a scientific advance, proving the existence of the Majorana would mean that it was likely they could be used to form qubits for this new form of quantum computing. Microsoft supported research, led by the physicist Leo Kouwenhoven at the Kavli Institute of Nanoscience at the Delft University of Technology in the Netherlands, that in 2012 produced the strongest evidence that the long-predicted particles exist.
<filename>research/slim/nets/mobilenet/conv_blocks.py<gh_stars>1-10 # Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Convolution blocks for mobilenet.""" import contextlib import functools import tensorflow as tf slim = tf.contrib.slim def _fixed_padding(inputs, kernel_size, rate=1): """Pads the input along the spatial dimensions independently of input size. Pads the input such that if it was used in a convolution with 'VALID' padding, the output would have the same dimensions as if the unpadded input was used in a convolution with 'SAME' padding. Args: inputs: A tensor of size [batch, height_in, width_in, channels]. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. rate: An integer, rate for atrous convolution. Returns: output: A tensor of size [batch, height_out, width_out, channels] with the input, either intact (if kernel_size == 1) or padded (if kernel_size > 1). """ kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1), kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)] pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1] pad_beg = [pad_total[0] // 2, pad_total[1] // 2] pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]] padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg[0], pad_end[0]], [pad_beg[1], pad_end[1]], [0, 0]]) return padded_inputs def _make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v def _split_divisible(num, num_ways, divisible_by=8): """Evenly splits num, num_ways so each piece is a multiple of divisible_by.""" assert num % divisible_by == 0 assert num / num_ways >= divisible_by # Note: want to round down, we adjust each split to match the total. base = num // num_ways // divisible_by * divisible_by result = [] accumulated = 0 for i in range(num_ways): r = base while accumulated + r < num * (i + 1) / num_ways: r += divisible_by result.append(r) accumulated += r assert accumulated == num return result @contextlib.contextmanager def _v1_compatible_scope_naming(scope): if scope is None: # Create uniqified separable blocks. with tf.variable_scope(None, default_name='separable') as s, \ tf.name_scope(s.original_name_scope): yield '' else: # We use scope_depthwise, scope_pointwise for compatibility with V1 ckpts. # which provide numbered scopes. scope += '_' yield scope @slim.add_arg_scope def split_separable_conv2d(input_tensor, num_outputs, scope=None, normalizer_fn=None, stride=1, rate=1, endpoints=None, use_explicit_padding=False): """Separable mobilenet V1 style convolution. Depthwise convolution, with default non-linearity, followed by 1x1 depthwise convolution. This is similar to slim.separable_conv2d, but differs in tha it applies batch normalization and non-linearity to depthwise. This matches the basic building of Mobilenet Paper (https://arxiv.org/abs/1704.04861) Args: input_tensor: input num_outputs: number of outputs scope: optional name of the scope. Note if provided it will use scope_depthwise for deptwhise, and scope_pointwise for pointwise. normalizer_fn: which normalizer function to use for depthwise/pointwise stride: stride rate: output rate (also known as dilation rate) endpoints: optional, if provided, will export additional tensors to it. use_explicit_padding: Use 'VALID' padding for convolutions, but prepad inputs so that the output dimensions are the same as if 'SAME' padding were used. Returns: output tesnor """ with _v1_compatible_scope_naming(scope) as scope: dw_scope = scope + 'depthwise' endpoints = endpoints if endpoints is not None else {} kernel_size = [3, 3] padding = 'SAME' if use_explicit_padding: padding = 'VALID' input_tensor = _fixed_padding(input_tensor, kernel_size, rate) net = slim.separable_conv2d( input_tensor, None, kernel_size, depth_multiplier=1, stride=stride, rate=rate, normalizer_fn=normalizer_fn, padding=padding, scope=dw_scope) endpoints[dw_scope] = net pw_scope = scope + 'pointwise' net = slim.conv2d( net, num_outputs, [1, 1], stride=1, normalizer_fn=normalizer_fn, scope=pw_scope) endpoints[pw_scope] = net return net def expand_input_by_factor(n, divisible_by=8): return lambda num_inputs, **_: _make_divisible(num_inputs * n, divisible_by) def split_conv(input_tensor, num_outputs, num_ways, scope, divisible_by=8, **kwargs): """Creates a split convolution. Split convolution splits the input and output into 'num_blocks' blocks of approximately the same size each, and only connects $i$-th input to $i$ output. Args: input_tensor: input tensor num_outputs: number of output filters num_ways: num blocks to split by. scope: scope for all the operators. divisible_by: make sure that every part is divisiable by this. **kwargs: will be passed directly into conv2d operator Returns: tensor """ b = input_tensor.get_shape().as_list()[3] if num_ways == 1 or min(b // num_ways, num_outputs // num_ways) < divisible_by: # Don't do any splitting if we end up with less than 8 filters # on either side. return slim.conv2d(input_tensor, num_outputs, [1, 1], scope=scope, **kwargs) outs = [] input_splits = _split_divisible(b, num_ways, divisible_by=divisible_by) output_splits = _split_divisible( num_outputs, num_ways, divisible_by=divisible_by) inputs = tf.split(input_tensor, input_splits, axis=3, name='split_' + scope) base = scope for i, (input_tensor, out_size) in enumerate(zip(inputs, output_splits)): scope = base + '_part_%d' % (i,) n = slim.conv2d(input_tensor, out_size, [1, 1], scope=scope, **kwargs) n = tf.identity(n, scope + '_output') outs.append(n) return tf.concat(outs, 3, name=scope + '_concat') @slim.add_arg_scope def expanded_conv(input_tensor, num_outputs, expansion_size=expand_input_by_factor(6), stride=1, rate=1, kernel_size=(3, 3), residual=True, normalizer_fn=None, split_projection=1, split_expansion=1, split_divisible_by=8, expansion_transform=None, depthwise_location='expansion', depthwise_channel_multiplier=1, endpoints=None, use_explicit_padding=False, padding='SAME', inner_activation_fn=None, depthwise_activation_fn=None, project_activation_fn=tf.identity, depthwise_fn=slim.separable_conv2d, expansion_fn=split_conv, projection_fn=split_conv, scope=None): """Depthwise Convolution Block with expansion. Builds a composite convolution that has the following structure expansion (1x1) -> depthwise (kernel_size) -> projection (1x1) Args: input_tensor: input num_outputs: number of outputs in the final layer. expansion_size: the size of expansion, could be a constant or a callable. If latter it will be provided 'num_inputs' as an input. For forward compatibility it should accept arbitrary keyword arguments. Default will expand the input by factor of 6. stride: depthwise stride rate: depthwise rate kernel_size: depthwise kernel residual: whether to include residual connection between input and output. normalizer_fn: batchnorm or otherwise split_projection: how many ways to split projection operator (that is conv expansion->bottleneck) split_expansion: how many ways to split expansion op (that is conv bottleneck->expansion) ops will keep depth divisible by this value. split_divisible_by: make sure every split group is divisible by this number. expansion_transform: Optional function that takes expansion as a single input and returns output. depthwise_location: where to put depthwise covnvolutions supported values None, 'input', 'output', 'expansion' depthwise_channel_multiplier: depthwise channel multiplier: each input will replicated (with different filters) that many times. So if input had c channels, output will have c x depthwise_channel_multpilier. endpoints: An optional dictionary into which intermediate endpoints are placed. The keys "expansion_output", "depthwise_output", "projection_output" and "expansion_transform" are always populated, even if the corresponding functions are not invoked. use_explicit_padding: Use 'VALID' padding for convolutions, but prepad inputs so that the output dimensions are the same as if 'SAME' padding were used. padding: Padding type to use if `use_explicit_padding` is not set. inner_activation_fn: activation function to use in all inner convolutions. If none, will rely on slim default scopes. depthwise_activation_fn: activation function to use for deptwhise only. If not provided will rely on slim default scopes. If both inner_activation_fn and depthwise_activation_fn are provided, depthwise_activation_fn takes precedence over inner_activation_fn. project_activation_fn: activation function for the project layer. (note this layer is not affected by inner_activation_fn) depthwise_fn: Depthwise convolution function. expansion_fn: Expansion convolution function. If use custom function then "split_expansion" and "split_divisible_by" will be ignored. projection_fn: Projection convolution function. If use custom function then "split_projection" and "split_divisible_by" will be ignored. scope: optional scope. Returns: Tensor of depth num_outputs Raises: TypeError: on inval """ conv_defaults = {} dw_defaults = {} if inner_activation_fn is not None: conv_defaults['activation_fn'] = inner_activation_fn dw_defaults['activation_fn'] = inner_activation_fn if depthwise_activation_fn is not None: dw_defaults['activation_fn'] = depthwise_activation_fn # pylint: disable=g-backslash-continuation with tf.variable_scope(scope, default_name='expanded_conv') as s, \ tf.name_scope(s.original_name_scope), \ slim.arg_scope((slim.conv2d,), **conv_defaults), \ slim.arg_scope((slim.separable_conv2d,), **dw_defaults): prev_depth = input_tensor.get_shape().as_list()[3] if depthwise_location not in [None, 'input', 'output', 'expansion']: raise TypeError('%r is unknown value for depthwise_location' % depthwise_location) if use_explicit_padding: if padding != 'SAME': raise TypeError('`use_explicit_padding` should only be used with ' '"SAME" padding.') padding = 'VALID' depthwise_func = functools.partial( depthwise_fn, num_outputs=None, kernel_size=kernel_size, depth_multiplier=depthwise_channel_multiplier, stride=stride, rate=rate, normalizer_fn=normalizer_fn, padding=padding, scope='depthwise') # b1 -> b2 * r -> b2 # i -> (o * r) (bottleneck) -> o input_tensor = tf.identity(input_tensor, 'input') net = input_tensor if depthwise_location == 'input': if use_explicit_padding: net = _fixed_padding(net, kernel_size, rate) net = depthwise_func(net, activation_fn=None) net = tf.identity(net, name='depthwise_output') if endpoints is not None: endpoints['depthwise_output'] = net if callable(expansion_size): inner_size = expansion_size(num_inputs=prev_depth) else: inner_size = expansion_size if inner_size > net.shape[3]: if expansion_fn == split_conv: expansion_fn = functools.partial( expansion_fn, num_ways=split_expansion, divisible_by=split_divisible_by, stride=1) net = expansion_fn( net, inner_size, scope='expand', normalizer_fn=normalizer_fn) net = tf.identity(net, 'expansion_output') if endpoints is not None: endpoints['expansion_output'] = net if depthwise_location == 'expansion': if use_explicit_padding: net = _fixed_padding(net, kernel_size, rate) net = depthwise_func(net) net = tf.identity(net, name='depthwise_output') if endpoints is not None: endpoints['depthwise_output'] = net if expansion_transform: net = expansion_transform(expansion_tensor=net, input_tensor=input_tensor) # Note in contrast with expansion, we always have # projection to produce the desired output size. if projection_fn == split_conv: projection_fn = functools.partial( projection_fn, num_ways=split_projection, divisible_by=split_divisible_by, stride=1) net = projection_fn( net, num_outputs, scope='project', normalizer_fn=normalizer_fn, activation_fn=project_activation_fn) if endpoints is not None: endpoints['projection_output'] = net if depthwise_location == 'output': if use_explicit_padding: net = _fixed_padding(net, kernel_size, rate) net = depthwise_func(net, activation_fn=None) net = tf.identity(net, name='depthwise_output') if endpoints is not None: endpoints['depthwise_output'] = net if callable(residual): # custom residual net = residual(input_tensor=input_tensor, output_tensor=net) elif (residual and # stride check enforces that we don't add residuals when spatial # dimensions are None stride == 1 and # Depth matches net.get_shape().as_list()[3] == input_tensor.get_shape().as_list()[3]): net += input_tensor return tf.identity(net, name='output') @slim.add_arg_scope def squeeze_excite(input_tensor, divisible_by=8, squeeze_factor=3, inner_activation_fn=tf.nn.relu, gating_fn=tf.sigmoid, squeeze_input_tensor=None, pool=None): """Squeeze excite block for Mobilenet V3. Args: input_tensor: input tensor to apply SE block to. divisible_by: ensures all inner dimensions are divisible by this number. squeeze_factor: the factor of squeezing in the inner fully connected layer inner_activation_fn: non-linearity to be used in inner layer. gating_fn: non-linearity to be used for final gating function squeeze_input_tensor: custom tensor to use for computing gating activation. If provided the result will be input_tensor * SE(squeeze_input_tensor) instead of input_tensor * SE(input_tensor). pool: if number is provided will average pool with that kernel size to compute inner tensor, followed by bilinear upsampling. Returns: Gated input_tensor. (e.g. X * SE(X)) """ with tf.variable_scope('squeeze_excite'): if squeeze_input_tensor is None: squeeze_input_tensor = input_tensor input_size = input_tensor.shape.as_list()[1:3] pool_height, pool_width = squeeze_input_tensor.shape.as_list()[1:3] stride = 1 if pool is not None and pool_height >= pool: pool_height, pool_width, stride = pool, pool, pool input_channels = squeeze_input_tensor.shape.as_list()[3] output_channels = input_tensor.shape.as_list()[3] squeeze_channels = _make_divisible( input_channels / squeeze_factor, divisor=divisible_by) pooled = tf.nn.avg_pool(squeeze_input_tensor, (1, pool_height, pool_width, 1), strides=(1, stride, stride, 1), padding='VALID') squeeze = slim.conv2d( pooled, kernel_size=(1, 1), num_outputs=squeeze_channels, normalizer_fn=None, activation_fn=inner_activation_fn) excite_outputs = output_channels excite = slim.conv2d(squeeze, num_outputs=excite_outputs, kernel_size=[1, 1], normalizer_fn=None, activation_fn=gating_fn) if pool is not None: # Note: As of 03/20/2019 only BILINEAR (the default) with # align_corners=True has gradients implemented in TPU. excite = tf.image.resize_images( excite, input_size, align_corners=True) result = input_tensor * excite return result
Improving the personalisation of care in a district nursing team: a service improvement project. Service users can benefit in a variety of ways from a personalised approach to care. This service improvement project aimed to improve personalisation for patients being cared for by a community nursing team in the south of England. A plan, study, do, act (PDSA) approach to the project was undertaken with a community nursing team. Both quantitative and qualitative data showed improvement once the focus on personalisation had been improved. Patient and staff satisfaction scores improved and a documentation audit showed the focus on personalisation had increased. Qualitative data suggested that personalisation had also saved staff time, although this measurement was not included in the project. A focus on personalisation can be beneficial for staff and service users.
/** * Created by freeway on 16/7/18. */ public class OrderServiceImpl extends BaseServiceImpl implements OrderService { private final static String ORDER_ELEME_ORDER_ID_STATUS = "/order/${eleme_order_id}/status/"; private final static String ORDER_ELEME_ORDER_ID = "/order/${eleme_order_id}/"; private final static String ORDER_ELEME_ORDER_ID_AGREE_REFUND = "/order/${eleme_order_id}/agree_refund/"; private final static String ORDER_ELEME_ORDER_ID_DISAGREE_REFUND = "/order/${eleme_order_id}/disagree_refund/"; private final static String ORDER_NEW = "/order/new/"; private final static String ORDERS_BATCH_GET = "/orders/batch_get/"; private final static String ORDER_DELIVERY = "/order/delivery/"; public OrderServiceImpl(OkHttpClient client, ElemeConfigStorage configStorage, LogListener logListener) { super(client, configStorage, logListener); } @Override public Order get(Long elemeOrderId) throws ElemeErrorException { if (elemeOrderId == null) { throw new ElemeErrorException(-1, "eleme_order_id is required."); } JSONObject jsonObject = execute(HTTP_METHOD_GET, ORDER_ELEME_ORDER_ID, new HashMap<String, String>() {{ put("eleme_order_id", String.valueOf(elemeOrderId)); put("tp_id", "1"); }}); return TypeUtils.castToJavaBean(jsonObject, Order.class); } @Override public void cancel(Long elemeOrderId, String reason) throws ElemeErrorException { if (elemeOrderId == null) { throw new ElemeErrorException(-1, "eleme_order_id is required."); } execute(HTTP_METHOD_PUT, ORDER_ELEME_ORDER_ID_STATUS, new HashMap<String, String>() {{ put("eleme_order_id", String.valueOf(elemeOrderId)); put("status", String.valueOf(OrderStatus.STATUS_CODE_INVALID)); put("reason", reason); }}); } @Override public void confirm(Long elemeOrderId) throws ElemeErrorException { if (elemeOrderId == null) { throw new ElemeErrorException(-1, "eleme_order_id is required."); } execute(HTTP_METHOD_PUT, ORDER_ELEME_ORDER_ID_STATUS, new HashMap<String, String>() {{ put("eleme_order_id", String.valueOf(elemeOrderId)); put("status", String.valueOf(OrderStatus.STATUS_CODE_PROCESSED_AND_VALID)); }}); } @Override public void complete(Long elemeOrderId) throws ElemeErrorException { if (elemeOrderId == null) { throw new ElemeErrorException(-1, "eleme_order_id is required."); } execute(HTTP_METHOD_PUT, ORDER_ELEME_ORDER_ID_STATUS, new HashMap<String, String>() {{ put("eleme_order_id", String.valueOf(elemeOrderId)); put("status", String.valueOf(OrderStatus.STATUS_CODE_FINISHED)); }}); } @Override public List<Long> getNewOrderIds() throws ElemeErrorException { return getNewOrderIdsByRestaurantId(null); } @Override public List<Long> getNewOrderIdsByRestaurantId(Long restaurantId) throws ElemeErrorException { Map<String, String> params = new HashMap<String, String>(); if (restaurantId != null) { params.put("restaurant_id", String.valueOf(restaurantId)); } return execute(HTTP_METHOD_GET, ORDER_NEW, params).getJSONArray("order_ids") .stream().map(s -> Long.valueOf(s.toString())).collect(Collectors.toList()); } @Override public List<Long> getOrderIdsByStatus(Long restaurantId, String day, Set<Short> statuses) throws ElemeErrorException { if (restaurantId == null) { throw new ElemeErrorException(-1, "restaurantId is required."); } if (day == null) { throw new ElemeErrorException(-1, "day is required."); } if (statuses == null || statuses.isEmpty()) { throw new ElemeErrorException(-1, "statuses is required."); } Map<String, String> params = new HashMap<String, String>(); params.put("restaurant_id", String.valueOf(restaurantId)); params.put("day", day); params.put("statuses", StringUtils.join(statuses.stream().map(String::valueOf).collect(Collectors.toList()), ",")); return execute(HTTP_METHOD_GET, ORDERS_BATCH_GET, params).getJSONArray("order_ids") .stream().map(s -> Long.valueOf(s.toString())).collect(Collectors.toList()); } @Override public void agreeRefund(Long elemeOrderId) throws ElemeErrorException { if (elemeOrderId == null) { throw new ElemeErrorException(-1, "eleme_order_id is required."); } execute(HTTP_METHOD_POST, ORDER_ELEME_ORDER_ID_AGREE_REFUND, new HashMap<String, String>() {{ put("eleme_order_id", String.valueOf(elemeOrderId)); }}); } @Override public void disagreeRefund(Long elemeOrderId, String reason) throws ElemeErrorException { if (elemeOrderId == null) { throw new ElemeErrorException(-1, "eleme_order_id is required."); } execute(HTTP_METHOD_POST, ORDER_ELEME_ORDER_ID_DISAGREE_REFUND, new HashMap<String, String>() {{ put("eleme_order_id", String.valueOf(elemeOrderId)); if (reason != null) { put("reason", reason); } }}); } @Override public List<OrderDelivery> getOrderDeliveriesByOrderIds(List<Long> elemeOrderIds) throws ElemeErrorException { if (elemeOrderIds == null || elemeOrderIds.isEmpty()) { return Collections.emptyList(); } JSONArray jsonArray = executeToJSONArray(HTTP_METHOD_GET, ORDER_DELIVERY, new HashMap<String, String>() {{ put("eleme_order_ids", StringUtils.join(elemeOrderIds, ",")); }}); return jsonArray.stream().map(s->TypeUtils.castToJavaBean(s, OrderDelivery.class)) .filter(s->s.getEleme_order_id()!=null).collect(Collectors.toList()); } }
<filename>src/main/java/com/caoccao/javet/exceptions/JavetV8LockConflictException.java<gh_stars>1-10 /* * Copyright (c) 2021. caoccao.com <NAME> * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.caoccao.javet.exceptions; import java.text.MessageFormat; public class JavetV8LockConflictException extends JavetException { public JavetV8LockConflictException(String message) { super(message); } public static JavetV8LockConflictException threadIdMismatch(long lockedThreadId, long currentThreadId) { return new JavetV8LockConflictException(MessageFormat.format( "V8 runtime lock conflict is detected with locked thread ID {0} and current thread ID {1}", Long.toString(lockedThreadId), Long.toString(currentThreadId))); } }
Rural banking in India Government of India promoted Regional Rural Banks (RRBs) through the RRBs Act of 1976 to bridge the gap in the flow of credit to the rural poor. The RRBs have a special place in the multi-agency approach adopted to provide agricultural and rural credit in India. These banks are state-sponsored, regionally-based and ruraloriented. Besides the RRBs, commercial and co-operative banks have been catering to the credit requirements of the rural sector.
<reponame>elastisys/autoscaler<gh_stars>1-10 package com.elastisys.autoscaler.core.prediction.impl.standard.capacitylimit; import static com.elastisys.autoscaler.core.prediction.impl.standard.capacitylimit.CapacityLimitTestUtils.config; import static com.elastisys.autoscaler.core.prediction.impl.standard.capacitylimit.CapacityLimitTestUtils.configs; import static com.elastisys.autoscaler.core.prediction.impl.standard.capacitylimit.CapacityLimitTestUtils.maxLimitEvent; import static com.elastisys.autoscaler.core.prediction.impl.standard.capacitylimit.CapacityLimitTestUtils.minLimitEvent; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.Optional; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.elastisys.scale.commons.eventbus.EventBus; import com.elastisys.scale.commons.eventbus.Subscriber; import com.elastisys.scale.commons.util.time.UtcTime; /** * Verifies that the {@link CapacityLimitRegistry} posts the proper * min/max-activation events on the event bus. */ public class TestCapacityLimitRegistryEventing { static Logger logger = LoggerFactory.getLogger(TestCapacityLimitRegistryEventing.class); private EventBus eventBus = mock(EventBus.class); /** Object under test. */ private CapacityLimitRegistry limitRegistry; @Before public void onSetup() { // Note: to see what events are posted on the bus, replace the mocked // eventbus with a real one and register this object as a listener. // this.eventBus = new // AsyncEventBus(Executors.newSingleThreadExecutor()); // this.eventBus.register(this); this.limitRegistry = new CapacityLimitRegistry(logger, this.eventBus); } @Subscriber public void onEvent(Object event) { logger.debug("event: " + event); } @Test public void checkPostedMinMaxLimitEvents() { this.limitRegistry.configure(configs(config("l1", 1, "* * * * * ? *", 2, 4), config("l2", 2, "* * 10-21 ? * FRI *", 5, 10), config("l3", 3, "* * 12-13 ? * FRI *", 7, 14))); Optional<Double> prediction1 = Optional.of(1.0); // baseline (l1) rule should be active DateTime monday = UtcTime.parse("2013-01-07T12:00:00.000Z"); assertThat(this.limitRegistry.limit(prediction1, monday).get(), is(2)); verify(this.eventBus).post(minLimitEvent(2, monday, "l1")); verify(this.eventBus).post(maxLimitEvent(4, monday, "l1")); reset(this.eventBus); // friday rule (l2) should be active DateTime fridayNight = UtcTime.parse("2013-01-04T20:00:00.000Z"); assertThat(this.limitRegistry.limit(prediction1, fridayNight).get(), is(5)); verify(this.eventBus).post(minLimitEvent(5, fridayNight, "l2")); verify(this.eventBus).post(maxLimitEvent(10, fridayNight, "l2")); reset(this.eventBus); // friday noon rule (l3) should be active DateTime fridayNoon = UtcTime.parse("2013-01-04T12:00:00.000Z"); assertThat(this.limitRegistry.limit(prediction1, fridayNoon).get(), is(7)); verify(this.eventBus).post(minLimitEvent(7, fridayNoon, "l3")); verify(this.eventBus).post(maxLimitEvent(14, fridayNoon, "l3")); verifyNoMoreInteractions(this.eventBus); } /** * No min-/max- limit activation should be reported when prediction is * absent (and no capacity limit needs to be applied). */ @Test public void checkPostedEventsWhenPredictionIsEmpty() { this.limitRegistry.configure(configs(config("l1", 1, "* * * * * ? *", 2, 4))); Optional<Double> absent = Optional.empty(); Optional<Integer> limit = this.limitRegistry.limit(absent, UtcTime.now()); assertThat(limit.isPresent(), is(false)); // no events should be posted in this case verifyNoMoreInteractions(this.eventBus); } /** * No min-/max- limit activation should be reported when no capacity limits * are configured. */ @Test public void checkPostedEventsWhenNoLimitRulesAreConfigured() { this.limitRegistry.configure(configs()); Optional<Double> prediction = Optional.of(2.0); Optional<Integer> limit = this.limitRegistry.limit(prediction, UtcTime.now()); assertThat(limit.isPresent(), is(true)); assertThat(limit.get(), is(2)); // no events should be posted in this case verifyNoMoreInteractions(this.eventBus); } }
The present invention relates to metal office furniture, and more particularly to decorative covers for metal office furniture. Metal office furniture is one of the backbones of the office environment. Exemplary pieces include file cabinets, desks, and drawer pedestals. Metal office furniture is fabricated of steel and then painted, making it both functional and durable. Several negative issues are related to metal office furniture. First, the appearance of such furniture typically is regarded as tolerable rather than attractive. For example, a large bank of filing cabinets presents a sea of uniform color, such as beige or gray. Second, the colors with which the furniture is painted go out of style. To change color, it is necessary either to purchase new furniture or to repaint existing furniture. The first option is undesirably expensive, and the second option is undesirably inconvenient. Third, the finishes of metal furniture occasionally are scratched or otherwise marred, so that they are unsightly. In such cases, it is necessary to replace the furniture (or at least the damaged components) or to repaint the furniture (or at least the damaged components). Fourth, when an office buys additional or replacement office furniture, one challenge is matching the color of the new office furniture to the existing furniture. The new office furniture may be made by a different manufacturer offering different colors, or may be made by the same manufacturer no longer offering the old colors. Even if a color is still made by the previous manufacturer, the new office furniture may not match the existing furniture due to fading, different dye runs of paint, or changes in the manufacturing process, such as switching from a wet paint to a powdercoat.
<reponame>rpenco/hattrick-scoreboard package org.hattrick.constants; /** * @author Khips * @since 14 aot 2014 */ public class HCupLevel { public static int NATIONAL_OR_DIVISIONAL = 1; public static int CHALLENGER = 2; public static int CONSOLATION = 3; }
The Impact of Oil Prices on the Banking System in the GCC This paper examines the links between global oil price movements and macroeconomic and financial developments in the GCC. Using a range of multivariate panel approaches, including a panel vector autoregression approach, it finds strong empirical evidence of feedback loops between oil price movements, bank balance sheets, and asset prices. Empirical evidence also suggests that bank capital and provisioning have behaved countercyclically through the cycle.
""" Read both MCMC summaries from the Joint less and more runs, and compile them into a LaTeX table. """ import arviz as az import corner import exoplanet as xo import matplotlib.pyplot as plt import pymc3 as pm import pandas as pd import os import twa.data as d from twa.constants import * from twa.plot_utils import efficient_autocorr, efficient_trace from twa import joint from pathlib import Path p = Path(os.getenv("TWA_ANALYSIS_ROOT")) df_less = pd.read_csv(p / "joint" / "rv_astro_disk_less" / "chains" / "current.csv") df_more = pd.read_csv(p / "joint" / "rv_astro_disk_more" / "chains" / "current.csv") # calculate rp for both cases for df in [df_less, df_more]: df["rp"] = df["aOuter"] * (1 - df["eOuter"]) # au # Assign table label with chain keyword and format precision for sampled and derived parameters. # assemble into a block and then insert into template. class Row: def __init__(self, key, label, precision=None, transformation=None, null=False): self.key = key # mc label self.label = label # row name in latex if precision is not None: self.precision = precision # format string else: self.precision = "{:.2f}" if transformation is not None: self.transformation = transformation else: self.transformation = lambda x: x self.null = null def get_vals(self, df): """ Calculate the mean and std off of the transformed variables. """ samples = self.transformation(df[self.key]) return (np.mean(samples), np.std(samples)) def __call__(self, df1, df2): """ Args: df : the DataFrame Output the LaTeX, applying the appropriate transformation. """ if self.null: return ( self.label + "& \\nodata\\tablenotemark{c} & \\nodata\\tablenotemark{c}\\\\" ) else: return self.label + ( " & $" + self.precision + " \pm " + self.precision + "$ & $" + self.precision + " \pm " + self.precision + "$\\\\" ).format(*self.get_vals(df1), *self.get_vals(df2)) # # sample pars # [ # "mparallax", # "aAngInner", # "logPInner", # "eInner", # "omegaInner", # "OmegaInner", # "cosInclInner", # "MAb", # "tPeriastronInner", # "logPOuter", # "omegaOuter", # "OmegaOuter", # "phiOuter", # "cosInclOuter", # "eOuter", # "gammaOuter", # "MB", # "offsetKeck", # "offsetFeros", # "offsetDupont", # "logjittercfa", # "logjitterkeck", # "logjitterferos", # "logjitterdupont", # "logRhoS", # "logThetaS", # "iDisk", # "OmegaDisk", # ] tdeg = lambda x: x / deg tOout = lambda x: x / deg + 360.0 texp = lambda x: np.exp(x) tyr = lambda x: x / yr tjd = lambda x: x + jd0 - 2450000 sampled_rows = [ Row("PInner", r"$P_\mathrm{inner}$ [days]", precision="{:.3f}"), Row("aAngInner", r"$a_\mathrm{inner}$ [mas]"), Row("MAb", r"$M_\mathrm{Ab}$ [$M_\odot$]"), Row("eInner", r"$e_\mathrm{inner}$"), Row( "inclInner", r"$i_\mathrm{inner}$ [\degr]", transformation=tdeg, precision="{:.1f}", ), Row( "omegaInner", r"$\omega_\mathrm{Aa}$\tablenotemark{a} [\degr]", transformation=tdeg, precision="{:.0f}", ), Row( "OmegaInner", r"$\Omega_\mathrm{inner}$\tablenotemark{b} [\degr]", transformation=tdeg, precision="{:.0f}", ), Row( "tPeriastronInner", r"$T_{0,\mathrm{inner}}$ [JD - 2,450,000]", transformation=tjd, ), Row("POuter", r"$P_\mathrm{outer}$ [yrs]", transformation=tyr, precision="{:.0f}"), Row("MB", r"$M_\mathrm{B}$ [$M_\odot$]"), Row("eOuter", r"$e_\mathrm{outer}$", precision="{:.1f}"), Row( "inclOuter", r"$i_\mathrm{outer}$ [\degr]", transformation=tdeg, precision="{:.0f}", ), Row( "omegaOuter", r"$\omega_\mathrm{A}$\tablenotemark{a} [\degr]", transformation=tOout, precision="{:.0f}", null=True, ), Row( "OmegaOuter", r"$\Omega_\mathrm{outer}$\tablenotemark{b} [\degr]", transformation=tdeg, precision="{:.0f}", null=True, ), Row( "tPeriastronOuter", r"$T_{0,\mathrm{outer}}$ [JD - 2,450,000]", transformation=tjd, precision="{:.0f}", null=True, ), Row("mparallax", r"$\varpi$ [$\arcsec$]"), Row( "logRhoS", r"$\sigma_\rho$ [$\arcsec$]", precision="{:.3f}", transformation=texp ), Row( "logThetaS", r"$\sigma_\theta$ [$\degr$]", precision="{:.3f}", transformation=texp, ), Row("jitCfa", r"$\sigma_\mathrm{CfA}$ [km s${}^{-1}$]", precision="{:.1f}"), Row("jitKeck", r"$\sigma_\mathrm{Keck}$ [km s${}^{-1}$]", precision="{:.1f}"), Row("jitFeros", r"$\sigma_\mathrm{FEROS}$ [km s${}^{-1}$]", precision="{:.1f}"), Row("jitDupont", r"$\sigma_\mathrm{du\;Pont}$ [km s${}^{-1}$]", precision="{:.1f}"), Row("offsetKeck", r"(Keck - CfA) [km s${}^{-1}$]", precision="{:.1f}"), Row("offsetFeros", r"(FEROS - CfA) [km s${}^{-1}$]", precision="{:.1f}"), Row("offsetDupont", r"(du Pont - CfA) [km s${}^{-1}$]", precision="{:.1f}"), ] derived_rows = [ Row("MAa", r"$M_\mathrm{Aa}$ [$M_\odot$]"), Row("MA", r"$M_\mathrm{A}$ [$M_\odot$]"), Row("aInner", r"$a_\mathrm{inner}$ [au]", precision="{:.3f}"), Row("aOuter", r"$a_\mathrm{outer}$ [au]", precision="{:.0f}"), Row("rp", r"$r_{p,\mathrm{outer}}$ [au]", precision="{:.0f}"), ] sampled = "\n".join([row(df_more, df_less) for row in sampled_rows]) derived = "\n".join([row(df_more, df_less) for row in derived_rows]) template = """\\begin{{deluxetable}}{{lcc}} \\tablecaption{{Orbital parameters \\label{{tab:orbits}}.}} \\tablehead{{\\colhead{{Parameter}} & \\colhead{{primary solution}} & \\colhead{{alternate solution}}}} \\startdata \\cutinhead{{Sampled}} {sampled:} \\cutinhead{{Derived}} {derived:} \\enddata \\tablenotetext{{a}}{{The argument of periastron of the primary. $\\omega_\\mathrm{{secondary}} = \\omega_\\mathrm{{primary}} + \\pi$.}} \\tablenotetext{{b}}{{The ascending node is identified as the point where the secondary body crosses the sky plane \\emph{{receding}} from the observer.}} \\tablenotetext{{c}}{{Posterior is non-Gaussian; see Figure~\\ref{{fig:corner}}}} \\end{{deluxetable}} """ with open("table.tex", "w") as f: f.write(template.format(sampled=sampled, derived=derived)) # # all pars # [ # "mparallax", # "MAb", # "logPOuter", # "offsetKeck", # "offsetFeros", # "offsetDupont", # "logRhoS", # "logThetaS", # "parallax", # "aAngInner", # "aInner", # "logPInner", # "PInner", # "eInner", # "omegaInner", # "OmegaInner", # "cosInclInner", # "inclInner", # "tPeriastronInner", # "MA", # "MAa", # "POuter", # "omegaOuter", # "OmegaOuter", # "phiOuter", # "tPeriastronOuter", # "cosInclOuter", # "inclOuter", # "eOuter", # "gammaOuter", # "MB", # "Mtot", # "aOuter", # "aAngOuter", # "logjittercfa", # "logjitterkeck", # "logjitterferos", # "logjitterdupont", # "jitCfa", # "jitKeck", # "jitFeros", # "jitDupont", # "iDisk", # "OmegaDisk", # "thetaDiskInner", # "thetaInnerOuter", # "thetaDiskOuter", # ]
<filename>libs/thunder/groups/ui/src/lib/private-navbar/navbar.spec.todo.tsx // import { render } from '@testing-library/react'; // import { ThemeProvider } from 'styled-components'; // import { Navbar } from './navbar'; // describe('Navbar', () => { // it('should render successfully', () => { // const { baseElement } = render( // <ThemeProvider theme={DarkTheme}> // <Navbar title={'hello'} /> // </ThemeProvider> // ); // expect(baseElement).toBeTruthy(); // }); // });
. The activated dexamethasone--receptor complex from rat liver cell cytoplasm and from Zajdela ascite hepatoma cell cytoplasm is bound to Sepharose-immobilized native DNA containing different numbers of recurrent sequences. The DNA-bound hormonereceptor complex is eluted as three peaks by varying concentrations of NaCl. The binding in independent of the number of DNA recurrent sequences and of the source of the cytoplasmic complex used.
Tarsal Tunnel Syndrome: Diagnosis, Surgical Technique, and Functional Outcome* During a 10-year period, 47 patients underwent surgical management for tarsal tunnel syndrome (TTS). Of these, 34 (36 feet) were available for complete retrospective analysis by record review, questionnaire, and physical examination. An additional 10 patients were evaluated by record review alone. The mean age was 38 years (range, 1265 years). Overall, average follow-up was 35 months (range, 15102 months). All patients had nonsurgical care for an average of 16 months before surgery (range, 172 months). The symptom triad of pain, paresthesias, and numbness was the most common clinical presentation. All had a positive Tinel's sign and nerve compression test (NCT) at the tarsal tunnel. Electrodiagnostic studies were abnormal in 38 feet (81%). Two-point discrimination was diminished significantly by an average of 6.7 mm. At a follow-up examination two-point discrimination improved by an average of 3.8 mm (P < 0.001). Eighteen feet continued to have a positive Tinel's sign and had a residual NCT. Subjectively, patients were satisfied with the surgical outcome in 72% of the cases. Postoperative improvement in the median Symptom Severity Score and the Functional Foot Score reflected this satisfaction. The perioperative complication rate was 30%. We conclude that the diagnosis of TTS is made primarily on history and clinical evaluation with electrodiagnostic studies supporting the diagnosis in 81%. Surgical treatment is warranted after nonsurgical management has failed. Division of the deep portion of the abductor hallucis fascia is important to ensure a complete release.
An Impact of Grid Integrated Hybrid Systems under Fault Analysis. This study examines how the grid-integrated hybrid system responds to a grid fault caused by a lag in the inverter's closed loop control time. Modeling of the hybrid renewable energy system with solar PV, Doubly Fed Induction Generator incorporated wind power, and the subsequent connection to the AC grid for providing energy to the three-phase load with Closed Loop control scheme of the VSI is presented in detail. This system incorporates solar PV and wind power. An MPPT approach is utilised in conjunction with a DC-DC boost converter in the Solar PV system. The wind power conversion system is combined with VSI's output to produce a hybrid system. The closed-loop controlled VSI's output is evaluated with a delay and while it's running normally. Closed loop control delay has a significant impact on grid output, and an effective real-time control solution for the VSI is therefore required.
Duplex strand joining reactions catalyzed by vaccinia virus DNA polymerase Vaccinia virus DNA polymerase catalyzes duplex-by-duplex DNA joining reactions in vitro and many features of these recombination reactions are reprised in vivo. This can explain the intimate linkage between virus replication and genetic recombination. However, it is unclear why these apparently ordinary polymerases exhibit this unusual catalytic capacity. In this study, we have used different substrates to perform a detailed investigation of the mechanism of duplex-by-duplex recombination catalyzed by vaccinia DNA polymerase. When homologous, blunt-ended linear duplex substrates are incubated with vaccinia polymerase, in the presence of Mg2+ and dNTPs, the appearance of joint molecules is preceded by the exposure of complementary single-stranded sequences by the proofreading exonuclease. These intermediates anneal to form a population of joint molecules containing hybrid regions flanked by nicks, 15 nt gaps, and/or short overhangs. The products are relatively resistant to exonuclease (and polymerase) activity and thus accumulate in joining reactions. Surface plasmon resonance (SPR) measurements showed the enzyme has a relative binding affinity favoring blunt-ended duplexes over molecules bearing 3-recessed gaps. Recombinant duplexes are the least favored ligands. These data suggest that a particular combination of otherwise ordinary enzymatic and DNA-binding properties, enable poxvirus DNA polymerases to promote duplex joining reactions. INTRODUCTION Poxviruses are large double-stranded DNA viruses that, similar to many other virus and bacteriophage, are subjected to very high frequencies of genetic recombination during viral replication. Although our understanding of the recombination systems used by most phage and virus is still incomplete, many of these infectious agents encode exonucleases and the activity of these enzymes can play a key role in production of virus recombinants. For example bacteriophage lambda encodes the Red system (comprising a DNA binding protein and 5 0 -3 0 exonuclease encoded by bet and exo genes, respectively), and it is the Red enzymes that catalyze most of the phage general homologous recombination detected in replication-permitted crosses. HSV-1 encodes an alkaline exonuclease that seems to serve a similar role in herpes virus recombination and the reverse transcriptase ribonuclease H activity (although not strictly an exonuclease) plays a key role in catalyzing retroviral reverse transcription and recombination. Exonucleases are critically important enzymes in most recombination pathways, but where duplicated sequences exist they play a central role in catalyzing what are broadly called 'single-strand annealing' (SSA) reactions. This is a non-conservative and widely employed method for producing recombinants. In the simplest form of an SSA reaction, an exonuclease first attacks the exposed ends of broken double-stranded DNAs, exposing complementary regions on substrate molecules that can then anneal through Watson-Crick base pairing. This produces heteroduplex spanning the joint and the recombination of sequences flanking the site of hybrid formation. The simplicity of such systems stands in stark contrast to the more complex and often redundant recombination pathways employed by cellular organisms. However, these systems serve other functions in conservative processes such as meiotic recombination and DNA repair that may not be quite so critical for virus biology. Poxvirus recombination reactions show all the molecular genetic hallmarks of simple SSA reactions including the transient production of abundant hybrid DNA and evidence of processing of joint regions by a 3 0 -5 0 exonuclease. Poxviruses replicate in the cytoplasm of infected cells and are generally viewed as encoding most or all of the machinery necessary for virus DNA replication. Thus it is notable that the only exonuclease encoded by Chordopoxvirus genomes is that which comprises the 3 0 -5 0 proofreading activity of poxvirus DNA polymerases. Nevertheless this seems to suffice to meet the needs of virus biology, and highly purified vaccinia virus DNA polymerase will catalyze singlestrand-by-duplex and duplex-by-duplex joining reactions in vitro. This enzyme can also repair small gaps and excise 3 0 ended single-stranded tails from model joint molecules in vitro. These observations show that poxvirus DNA polymerases are endowed with the enzymatic capacity needed to form and (where necessary) repair joint molecules. These non-covalently linked reaction products can then by converted into fully duplex recombinants by the subsequent activity of enzymes like poxvirus or cellular DNA ligases. What is still unclear is what are the special biochemical properties of poxvirus DNA polymerases that create the capacity to catalyze duplex-by-duplex strand joining. These are seemingly typical B-family DNA polymerases, endowed with 3 0 -5 0 proofreading and 5 0 -3 0 DNA synthetic activities. To our knowledge these are the only members of the B-family of DNA polymerases that can catalyze recombination-like reactions. In this study we have examined this question using, as enzymatic substrates and binding partners, small oligonucleotide duplexes. This permits a fine scale analysis of the kinetics of excision and repair as it relates to the concurrent formation to joint molecules. We have also used surface plasmon resonance methods (SPR) to investigate the binding affinities exhibited by the enzyme towards these substrates and putative reaction products. Our results suggest that the 3 0 -5 0 proofreading exonuclease has a reduced enzymatic preference or binding affinity for the products of these reactions (joint molecules bearing simple nicks or 1-2 nt gaps) relative to the blunt-ended duplexes that are used as substrates. These particular enzymatic properties can do much to explain how poxvirus DNA polymerases could serve a dual role as viral 'recombinases'. Recombinant protein Vaccinia virus DNA polymerase (>95% purity) was prepared using the procedure of McDonald and Traktman. The method removes the A20R processivity factor and the protein is thus expected to interact with DNA in a distributive manner. Radioactive labeling of oligonucleotides Oligonucleotides were purchased from Sigma-Genosys (Mississauga, Canada) or the DNA core facility, University of Alberta. These DNAs were 5 0 end-labeled and purified as described previously. Figure 2 illustrates the sequences and structures of the DNAs used in these experiments. The 25mer and 30mer size markers have the same DNA sequence as the predicted products of a 3 0 -exonuclease attack on labeled 45 and 50mer strands, thus ensuring better accuracy in assigning the sizes of reaction products. Only one of the two 3 0 ends on each of these duplex substrates encodes the homology required by a SSA reaction. To suppress exonucleolytic attack on the other 3 0 ended strands, the substrates permit incorporation of a cidofovir residue into these other 3 0 ends. The cidofovir addition reaction contained the DNA duplexes described above, 20 U of MMLV reverse transcriptase (Invitrogen), 0.1 M dithiothreitol, 100 mM cidofovir diphosphate (synthesized by Trilink Technologies, San Diego), and 50 mM dATP or dTTP (Invitrogen). The reaction was incubated at 37 C overnight, heated to 70 C for 10 min, and the DNA was purified by passage through a Sephadex-25 spin column. In control experiments we noted that this treatment did not completely block exonuclease attack, but served the necessary purpose if reactions were limited to times <30 min (data not shown). Biotinylated oligonucleotides were prepared in the same way except we substituted 40 mM N 4 -modified biotin-14-dCTP (Invitrogen) for cidofovir diphosphate. Strand joining reactions Each 0.13 ml reaction normally contained 0.1 nmol of each duplex substrate, 230 ng vaccinia virus DNA polymerase ($2 pmol), 15 mM dATP, 15 mM dCTP, 5 mM dGTP, 10 mM TTP, 30 mM Tris-HCl (pH 7.9), 5 mM MgCl 2, 70 mM NaCl, 1.8 mM DTT and 80 mg/ml acetylated BSA. These starting concentrations of dNTPs were chosen because they are thought to reflect the in vivo concentrations in vaccinia-infected cells. The reaction was incubated at 37 C with periodic sampling. Each aliquot was mixed with twice-concentrated gel loading buffer to stop the reaction. The reaction products were separated by non-denaturing electrophoresis in 10% polyacrylamide gels, the gels were dried, and the distribution of the label determined using a Storm phosphoimager and ImageQuant software (Amersham). To test what effect the dNTP concentration has on the efficiency of strand joining we used our original agarosebased gel assay. Plasmid pBluescript II KS(+) DNAs were cut with XhoI and HindIII (which creates molecules sharing 21 bp of overlapping homology), and equimolar quantities of DNA incubated with the polymerase and singlestrand binding proteins in the presence of different concentrations of dNTPs. Substrates and products were separated by agarose gel electrophoresis. These controls showed that higher concentrations of dNTPs inhibit strand joining, but this effect can be suppressed using longer incubation times ( Figure 1). Under the simplified conditions used in this study Second dimension analysis Gels containing the separated products of the joining reaction were stained with methylene blue to visualize the DNA. The lane corresponding to each time point was cut from the gel, sliced into sections, and the DNA extracted by crushing each slice in 200 ml of 0.3 M sodium acetate in 10 mM Tris-HCl, 1 mM EDTA and shaking overnight. The acrylamide was removed by centrifugation through aerosolresistant pipet tips (Axygen) and the DNA precipitated using glycogen and three volumes of 95% ethanol. The precipitated DNA was washed once with 70% ethanol, dried and resuspended in 10 ml TE. Each sample was mixed with 10 ml of loading buffer . The samples were then denatured by heating to 56 C and fractionated through a 10% polyacrylamide gel containing 8 M urea and a 19:1 ratio of acrylamide to bisacrylamide. The gel was fixed with 10% (v/v) acetic acid and 20% (v/v) methanol in water, dried on Whatman paper, and subjected to phosphorimager analysis. Surface plasmon resonance analysis Measurements were taken on a Biacore 2000 SPR instrument using control software version 3.1. The sensor surface Figure 1. Effects of dNTP concentration and reaction time on DNA joining reactions. Standard reactions were prepared as described previously containing an equimolar mixture of XhoI-and HindIII-cut pBluescript II DNAs, vaccinia single-strand binding protein, and vaccinia DNA polymerase. The reactions were supplemented with the indicated amounts of dNTPs. The reactions were incubated for 20 or 60 min and the products separated by agarose gel electrophoresis (upper panel) and quantified using ethidium fluorescence (lower panel). The reaction midpoints are seen at 5 and 50 mM dNTP for 20 and 60 min reactions, respectively. consisted of a CM5 sensor chip to which a low level of streptavidin had been amine coupled. Biotinylated oligo complexes (FC1, FC3 and FC5) were bound to flow cells 2, 3 and 4 of the sensor chip, respectively, at a density of 50-100 RU. All remaining streptavidin sites were blocked by injection of 5 mM D-biotin, including flow cell 1 (the reference flow cell). Samples were diluted from an enzyme stock into polymerase buffer containing 80 mg/ml bovine serum albumin and stored in a chilled (4 C) sample block prior to injection. Concentrations of 100, 75, 50, 40, 30, 20, 10, 5, 1 and 0.1 nM were injected in duplicate in random order for 2.5 min at a flow rate of 20 ml/min. Regeneration was with 1 M NaCl between cycles. Responses from a control flow cell containing biotin-blocked streptavidin, and a blank injection with polymerase buffer, were subtracted from each dataset to control for bulk refractive index changes. Datasets were aligned, the reference subtracted, and fit to an equilibriumbinding model using Scrubber version 1.1g, BIAevaluation 4.1, or Prism software. The data report standard errors. Figure 2A shows the assay used to monitor duplex strand joining ('fusion') reactions catalyzed by vaccinia virus DNA polymerase. These assays originally used linearized plasmid DNAs and/or PCR amplicons , but in this study we have substituted synthetic oligonucleotide duplexes because using smaller DNAs facilitates high-resolution analysis of the fusion process. We prepared two double-stranded substrates , which share 20 bp of sequence homology ( Figure 2B, boldface text), and should be processed into a 75 bp recombinant product under strand joining conditions. In order to limit the degradation of the duplex substrates to just the ends encoding homologous sequences, the 3 0 ends located distal to the regions of homology were protected from exonuclease attack by filling in those ends with molecules of cidofovir (see Materials and Methods). We have previously shown that the polymerase and exonuclease activities of vaccinia DNA polymerase are greatly inhibited by cidofovir located at the penultimate 3 0 end of the primer strand. Figure 3 shows the kinetics of conversion of these substrates into recombinant products. Equal amounts of 32 P-labeled FC1 and FC2 were incubated with vaccinia DNA polymerase in the presence of physiological concentrations of dNTPs in vaccinia virus infected cells (15 mM dATP, 15 mM dCTP, 5 mM dGTP and 10 mM TTP). The initial stages of the reaction are slow, with little visible change in the migration of the two substrates. A trace quantity of labeled residual single-stranded DNA was, however, degraded immediately. Continued processing of FC1 and FC2 was indicated by an increase in the mobility of the two substrates, followed by the label being chased into larger recombinant products. Between 16 and 24 min, the total amount of DNA migrating as a product was approximately constant, while the amount present as precursors declined by 50% as judged by phosphorimager analysis. During this time, analysis of the phosphorimager signal also showed that $20% of the input label was maximally converted into recombinant products under these particular conditions. The gradual blurring and eventual disappearance of these molecules seemed to correlate with the timing of a slow exonuclease attack on the unlabelled, cidofovir-containing, strand. During the later stages of the reaction, all of the DNAs were converted into what appeared to be a limit digest composed of a mixture of di-and tri-nucleotides, which migrated together near the electrophoresis front. RESULTS In order to determine the composition of the molecules that were being formed during these reactions, DNA was extracted from regions of the native gel comprising processed substrates and annealed recombinants, and subjected to further analysis by denaturing gel electrophoresis. This involved excising each lane from the native gel, cutting each lane into sections spanning the size ranges from $18 to 55 nt, extracting the DNA from each section, and subjecting the recovered DNA to denaturing gel electrophoresis ( Figure 4A). In these experiments we also labeled either FC1 or FC2, but not both (as in Figure 3), to simplify the interpretation of the resulting autoradiographs. Figure 4B and C shows the results of this experiment. Overall, both of the labeled strands in FC1 and FC2 were processed with similar kinetics and into similar exonuclease products. There was a slow degradation of the labeled strand at early time points, followed by a more rapid degradation at later Figure 3. Native gel analysis of the joining reaction. A joining reaction was prepared containing 32 P-labeled substrates FC1 and FC2 and Mg 2+ and four dNTPs, incubated at 37 C, and aliquots removed and mixed with EDTA at the indicated times to stop the reaction. Loading buffer was then added and the samples subjected to electrophoresis using a non-denaturing 10% polyacrylamide gel. After drying the gel, autoradiography was used to locate the reaction products. A trace of unannealed strand can be seen at time zero ('*'). Vaccinia DNA polymerase degrades such single-stranded DNAs to nucleotides within seconds under these reaction conditions. time points. A few intermediary digestion products appeared in the precursor lanes; many map near sites where pyrimidine residues are located and which may be natural pause sites for the proofreading exonuclease. The appearance of substantial amounts of recombinant product did not occur until there were processed precursors, which had been degraded to the extent that the homologous regions on both duplexes were nearly fully exposed. At 8 min, we began to see the presence of precursor ('reactant') strands that showed evidence of the excision of 19-20 nt. Product molecules started to appear shortly thereafter, about 8-12 min into the reaction. The kinds of excision products that had been incorporated into these recombinant products varied in size. We saw some molecules (marked with a '*' in Figure 4B and C) that would permit the formation of duplexes bearing a simple nick at the junction point. However, other types of 3 0 -excision products were also present. The largest proportion ($45%) of the FC1-derived strands were incorporated into the recombinants as 26mer ( Figure 4B), which would create a 1 bp overhang when paired with the 5 0 end of the FC2-derived strand. Molecules of shorter lengths were also observed, which would create recombinants bearing small (1-5 bp) gaps. The processing of the FC2-derived strand generated a similar variety of excision products, although in this case the predominant species ($25%) were strands processed to a size that could form nicked recombinants ( Figure 4C). These observations suggested that vaccinia DNA polymerase may have a substrate preference which favors the enzymatic modification of molecules not incorporated into recombinant structures. To test this possibility directly, we constructed two precursor analogs, FC3 and FC4 ( Figure 2B), which bear gaps similar in size to those produced during processing of FC1 and FC2. We then compared the rate of exonucleolytic attack upon one of these recessed strands, depending upon whether or not this strand was incorporated into a nicked recombinant duplex. The results are shown in Figure 5. Equimolar amounts of FC3 alone, or FC3 annealed to FC4, were incubated with vaccinia DNA polymerase and the reaction sampled at different time points. The labeled strand being tracked on the gel was the same in both substrates. We observed that the 32 P-labeled strand in FC3 was rapidly processed in the absence of FC4, being either extended through DNA synthesis or degraded by the exonuclease. At later stages in the reaction, the extended products were also subjected to limited exonucleolytic attack. In contrast, the target strand in the recombinant structure comprising FC3+FC4 was far less susceptible to enzymatic modification, with most molecules losing only a single nucleotide over the length of the experiment. Similar results were obtained when FC4 was labeled (data not shown). What is the fate of these gapped molecules, regardless of whether they are produced through strand annealing (Figures 3 and 4) or by subsequent exonuclease attack on nicked reaction products ( Figure 5)? Liked nicked substrates, molecules bearing small gaps are also relatively stable in the presence of vaccinia DNA polymerase and dNTPs. Figure 6 shows a side-by-side comparison of the substrate properties of FC1, FC3 and FC5 where FC5 comprises a DNA duplex containing a small one-nucleotide gap ( Figure 2B, the purpose of the hairpin terminus is explained below). As previously noted, the unprotected 3 0 ended strand in FC1 is attacked slowly in the presence of dNTPs ( Figure 3) and this 3 0 end is an excellent substrate for both the 3 0 -5 0 exonuclease and the DNA polymerase in FC3 ( Figure 5). However, the one-nucleotide gap in FC5 is subjected to only limited further modification by vaccinia DNA polymerase, insofar as we detected the excision or addition of only 1-2 nt over the course of these reactions. The majority of molecules suffered no further net modification at all over the 28 min incubation period ( Figure 6). The differences we saw in the experiments detailed above, suggested that vaccinia DNA polymerase has a differential affinity for substrates (linear duplex ends) versus reaction products and that this difference in affinity would effectively favor the formation and stabilization of recombinant products. To test whether this reflected absolute differences in DNA binding properties, we used SPR to directly assess the binding of vaccinia DNA polymerase to three different kinds of molecules. These molecules were FC1, FC3 and FC5. FC1 comprises one of the two reaction substrates and FC3 and FC5 model two examples of reaction products. In order to perform this analysis we had to add a hairpin to the terminus of FC5 ( Figure 2B) so as to eliminate a 3 0 end that would complicate the analysis of enzyme binding to a second internal 3 0 end, located next to the one-nucleotide gap. In order to perform an SPR experiment a method is also required to attach the DNA to the CM5 sensor surface. To do this, the annealed substrates were labeled with biotin (substituting biotinylated dCTP for cidofovir diphosphate) by filling in one end of the duplex using N 4 biotin-14-dCTP, dATP (or dTTP), and reverse transcriptase. The sensor surface was coupled with streptavidin, and the biotinylated FC1, FC3 and FC5 molecules attached to three of the four chip surfaces at a low surface density (50-100 RU). The last (fourth) section of the sensor contained no DNA and served as a negative control for non-specific binding to biotin-blocked streptavidin. To perform the binding analysis the sensor surface was washed with Mg 2+ -free polymerase buffer, and then varying concentrations of vaccinia DNA polymerase were passed over the surface in the same buffer for 2.5 min to monitor an association rate. The concentrations of polymerase used ranged from 0.1 to 100 nM ($0.01-10 mg/ml). Washing with buffer permitted monitoring the dissociation rate. Figure 7 shows the resulting duplicate binding curves, for FC1, after subtracting the reference cell and blank injection signals from the experimental data. By fitting these data to a simple 1:1 equilibrium-binding model we established apparent equilibrium-dissociation constants (K D ) for FC1, FC3 and FC5 of 7.0 ± 0.7, 18 ± 2 and 25 ± 4 nM, respectively, using Prism software and BIAeval data points (Figure 7, lower panel). Similar numerical results, and the same trend, were obtained using BIAevaluation and Scrubber software. The three methods of analysis suggest that vaccinia virus DNA polymerase has a relative binding preference for FC1 > FC3 > FC5. DISCUSSION Vaccinia DNA polymerase can promote SSA reactions, which lead to the fusion of homologous duplex DNAs in vitro and can be used as a tool for assembling recombinant molecules. Many of the features of the in vitro reaction are also observed when linear DNAs are transfected into poxvirus-infected cells, including the fact that using cidofovir to block exonuclease activity inhibits recombination in vitro and in vivo and this block can be overcome by virus encoding cidofovir-resistant DNA polymerases (D. Gammon and D. Evans, unpublished data). This strongly suggests that the proofreading exonuclease activity of these polymerases is also used by poxviruses to promote doublestrand break repair and recombination in vivo. This is an unusual situation, because in all of the other exonucleasedependent recombination and repair systems characterized to date, a specialized enzyme typically provides the nuclease activity (e.g. RecBCD, RecJ, lambda Red exonuclease, HSV-1 alkaline exonuclease, WRN exonuclease, Mre11, etc.). Poxvirus genomes do not encode such specialized exonucleases and have, instead, seemingly adapted the DNA polymerase to serve this function. However, this raises questions regarding the nature of these enzymatic adaptions. In this study we have examined the behavior of the enzyme when presented with DNAs resembling the substrates, putative intermediates, and representative products of these strand joining reactions. Our observations suggest a straightforward explanation for how vaccinia DNA polymerase might catalyze this unusual reaction. The DNA joining reactions are readily followed using gel electrophoresis and 45 and 50 bp substrates that are rapidly converted into 75 bp joint molecules (Figure 3). Using high-resolution denaturing gel electrophoresis it was observed that the 3 0 -5 0 exonuclease activity processed the reacting strands (FC1 and FC2) into a variety of gapped molecules, and that a subset of these gapped species were then selectively incorporated into metastable reaction products (Figures 3 and 4). Close inspection of the reaction kinetics shows that exposure of most of the homology precedes the appearance of joint molecules, spontaneous annealing probably then creates joint molecules. Only a small fraction of the reaction products likely bear simple nicks on both sides of the 20 nt region of homology, due to some variability in the extent of strand excision ( Figure 4B and C). However the mixture of nicks, short-unpaired extensions, and small gaps do not destabilize the joint molecules enough to inhibit joint molecule formation. Such nicks gaps and extensions would also be readily repaired by bacterial enzymes following the transfection of in vitro reaction products into E.coli, which would explain how the method can be used to produce recombinant clones in bacteria. The transient stability of the duplex joints seen in Figure 3 is probably an important feature of this reaction. The effect is much better illustrated in Figure 5 where we directly compare how vaccinia DNA polymerase processes a nick-containing recombinant duplex (FC3 annealed to FC4) with the effects of the enzyme upon a gapped precursor of this molecule (FC3 alone). The joint molecule is very stable, suffering only limited attack by the exonuclease, whereas FC3 is subjected to a mixture of primer extension and modification by the exonuclease. We have previously noted that duplex molecules bearing longer unpaired 3 0 extensions are also rapidly processed by vaccinia DNA polymerase into metastable structures bearing small nicks and gaps. These are all reaction features that greatly favor the formation, processing, and transient stabilization of recombinant products. Each binding curve was measured in duplicate followed by washing with polymerase-free buffer. Magnesium and dNTPs were omitted from the reaction buffer to prevent enzymatic modification of the DNA substrates. The on-off rates are too fast to be measured with satisfactory accuracy by this method, so the K D values were calculated from a curve fit (R 2 0.98) to the effects of enzyme concentration upon the equilibrium-binding signal (lower panel). These observations suggest that vaccinia polymerase might exhibit binding properties that favors binding 3 0 ends located within either duplex substrates (FC1) or embedded within a classic primer-template structure (FC3), and disfavors binding to nicks or small gaps. To test this hypothesis we used SPR methods and another substrate that utilizes a hairpin structure to eliminate the 3 0 -terminus of the duplex end (FC5). FC5 can thus provide a test of the enzyme's affinity for recombinant reaction products, if one makes the not unreasonable assumption that the hairpin structure is an unlikely alternate binding site. Like the nicks in FC3/FC4, the one base gap in FC5 is subjected to only limited enzymatic processing by the polymerase, although in this substrate the onenucleotide gap in the primer strand mostly suffers no further net modification ( Figure 6) rather than suffer a loss of 1 or 2 nt ( Figure 5). FC1, FC3 and FC5 were then coupled to the surface of Biacore chip, using a biotin-streptavidin attachment method, and enzyme binding monitored using SPR. We estimate that the 14 atom-linked-biotin tether, plus the length of the attached oligonucleotide (>22 bp), would place the 3 0 end bound by the enzyme at least $75 s from the streptavidin surface. Assuming vaccinia polymerase exhibits dimensions similar to a protein like RB69 DNA polymerase , this distance should well exceed that needed to avoid any steric interference between enzyme and chip surface. The SPR method clearly showed that vaccinia DNA polymerase has a binding preference most favoring duplex ends and least favoring molecules resembling the typical products of strand joining reactions (i.e. FC1 > FC3 > FC5). Where others have used similar substrates (e.g. a blunt-ended duplex molecule like FC1), but different enzymes, there is still surprisingly good agreement between measured dissociation constants. We measured a K D for vaccinia polymerase of 7.0 ± 0.7 nM using FC1 (95% confidence interval 5.6-8.4 nM), versus 13 nM reported for human DNA polymerase b using SPR methods and a similar DNA. Using stopped-flow methods Otto et al. measured a K D for T4 DNA polymerase of 21 nM. One notable difference between these studies is that stopped-flow methods detect on-off rates for T4 DNA polymerase that are so fast (k off 9.3 s 1 ) as to suggest that DNA polymerase binding and dissociation rates should not be readily measurable using SPR methods. This fact is consistent with our observations (Figure 7), but is not consistent with what has been reported for earlier SPR measurements utilizing DNA polymerase b. These authors reported a k off 0.0099 s 1 for duplex DNA substrates. The origin of this discrepancy in reaction rates is difficult to identify, given the many differences in experimental protocols and the different enzymes used. In particular there are significant differences in buffer composition and reaction temperatures. However, we note that in this earlier SPR study the authors also coupled up to 50-fold more DNA to the chip surface than we did , and this high substrate density might have had a negative effect on reaction rates while not ultimately affecting K D values. Regardless of the cause of this discrepancy, the fact that these K D measurements all cluster between 7 and 21 nM provides some confidence that these methods all measure values close to true K D s. This is actually quite remarkable given the necessity of making several methodological assumptions (including the assumption that all the enzyme is active in these preparations) and the different techniques and enzymes used to calculate dissociation constants. When the relative binding preferences we have measured are considered within the context of how the enzyme processes homologous DNAs (Figures 3 and 4), it becomes apparent how this enzyme can promote duplex joining reactions in vitro. Vaccinia DNA polymerase has a clear preference for binding duplex ends, which are then processed by 3 0 -5 0 exonuclease into a pool of 3 0 -gapped molecules. This reaction proceeds even in the presence of dNTPs and may reflect some fundamental difference in the way DNA partitions between exonuclease and polymerase active sites in poxvirus enzymes. If these gaps span complementary sequences, and are long enough to create stable heteroduplex molecules, then these DNAs can anneal spontaneously to form joint molecules. The 3 0 ends that are subsumed within the resulting typical hybrid structures are $4-fold less-favored enzyme binding sites, compared with blunt ends, and thus this combination of reaction and binding properties will favor the production of metastable joint molecules. In contrast, the proofreading exonucleases of other DNA polymerases have only a limited appetite for properly duplex (as distinct from mismatched) DNA ends in the presence of dNTPs, and thus under our reaction conditions most other polymerases would not generate the gapped molecules from which recombinant duplexes are formed. These same reaction features are also likely operative in vivo, including a relative preference for binding and exonuclease processing of duplex ends by the polymerase. However, these reactions would be affected by the activities of other viral replication factors, single-strand binding proteins, and changing dNTP pools. These effects would be difficult to predict a priori. It is clear that the exonuclease and strand joining (Figure 1) activities are both modulated by dNTP concentration in vitro and so this could be a key factor regulating recombination in vivo. Unfortunately we do not understand how dNTP concentrations change temporally and spatially during infection and thus cannot predict exactly what effect these will have on virus recombination in vivo. It is also unclear what proportion of the E9 protein is incorporated into the processive form of enzyme complex, by complexing with the A20 and D4 proteins, nor is it certain if this fraction remains stable over time. Nevertheless we would note that even when incorporated into a replication complex, there is no reason to believe the exonuclease would be rendered inactive by A20 or D4. The activity is needed for proofreading and it could also serve an essential purpose in facilitating the repair of broken replication forks. One of the difficulties posed by the Moyer-Graves rolling hairpin model for poxvirus replication is that collision of a replication complex with a nick in the template strand would create double-strand breaks in the virus DNA ( Figure 8). We have shown that molecules bearing 5 0 -overhangs next to the region of homology are still substrates for duplex-by-duplex joining reactions. Consequently, these breaks could be repaired by a stalled replication complex using a SSA reaction coupled with nick ligation. We are currently devising efficient ways of isolating poxvirus replication complexes to test this proposal.
package problemsolving; /** * Given two binary strings a and b, return their sum as a binary string. * */ public class AddBinary { private static String addBinary(String a, String b) { String ans = ""; int carry = 0; for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) { int sum = carry; sum += (i >= 0) ? a.charAt(i) - '0' : 0; sum += (j >= 0) ? b.charAt(j) - '0' : 0; ans += (sum % 2); carry = sum / 2; } if (carry != 0) { ans += carry; } char[] arr = ans.toCharArray(); int start = 0; int end = arr.length - 1; while (start <= end) { char temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } return String.valueOf(arr); } public static void main(String[] args) { String a = "1010"; String b = "1011"; System.out.println(addBinary(a, b)); } }
a. Field of the Invention The instant invention relates to a catheter assembly with a front-loaded catheter tip and having a multi-contact connector. In particular, the instant invention relates to catheters comprising multi-contact connectors at the proximal end that allow for electrical connections in constrained spaces. b. Background Art It is known that catheters are widely used to perform a variety of functions relating to therapeutic and diagnostic medical procedures involving tissues within a body. For example, catheters can be inserted within a vessel located near the surface of a body (e.g., in an artery or vein in the leg, neck, or arm) and maneuvered to a region of interest within the body to enable diagnosis and/or treatment of tissue without the need for more invasive procedures. For example, catheters can be inserted into a body during ablation and mapping procedures performed on tissue within a body. Tissue ablation can be accomplished using a catheter to apply localized radiofrequency (RF) energy to a selected location within the body to create thermal tissue necrosis. Typically, the ablation catheter is inserted into a vessel in the body, sometimes with the aid of a pull wire or introducer, and threaded through the vessel until a distal tip of the ablation catheter reaches the desired location for the procedure involving a body tissue. The ablation catheters commonly used to perform these ablation procedures produce lesions and electrically isolate or render the tissue non-contractile at various points in the cardiac tissue by physical contact of the cardiac tissue with an electrode of the ablation catheter and application of energy, such as RF energy. By way of further example, another procedure, mapping, uses a catheter with sensing electrodes to monitor various forms of electrical activity in the body. Known ablation catheter assemblies typically involve insertion of a catheter through a sheath or introducer where the standard catheter shaft size is 7 FR (French), the standard catheter tip size is 4-8 FR, and the standard sheath or introducer size is 8-11 FR. For purposes of this application, the term “FR (French)” means the French catheter scale used to measure the outer diameter of catheters. In the French gauge system as it is also known, the diameter in millimeters of the catheter can be determined by dividing the French size by three. Thus, an increasing French size corresponds with a larger diameter catheter. Typically, the outer diameter of the sheath or introducer is larger than the outer diameter of the catheter shaft and is also larger than the outer diameter of the catheter tip. A difficulty in obtaining an adequate ablation lesion using known ablation catheter assemblies for certain procedures is that conventional catheter assemblies have overall a large outer diameter that can potentially cause trauma. For instance, when performing transseptal catheterization or punctures across the septum of the heart, the fossa ovalis can be susceptible to trauma or injury. It is possible that, using known devices, two, three, or more transseptal punctures can have to be made through the same area of the fossa ovalis to get more of the catheter assembly from one side of the heart to the other side of the heart. Another difficulty with known catheter assemblies such as those used for ablation procedures is that the ability to freely manipulate the catheter within the sheath or introducer is compromised or decreased because the catheter has greater overall contact with the interior walls of the sheath or introducer, as the standard catheter used for ablation normally has a constant diameter from the distal tip to the proximal handle end. Typically, the catheter and catheter tip is a single unitary assembly of constant diameter along the entire length of the catheter assembly, and typically, the sheath or introducer has a constant outer diameter and constant inner diameter along the entire length of the catheter assembly. When there is greater contact between the catheter and sheath or introducer, there is less degree of freedom of movement available in using the catheter assembly through transseptal punctures. Another difficulty with known catheter assemblies such as those used for ablation procedures is that the catheter tips can not be of a large enough size to accommodate an electrically active element or to accommodate magnetic material to create a magnetic field, so that the magnetized catheter can be pulled and guided through the body and through the heart rather than pushed. Known catheter assemblies with magnetized elements often cannot accommodate a large enough magnetic material or element to create a magnetic field or they create unfavorable drag forces inside the catheter or sheath. Known catheter assemblies such as those used for ablation procedures, include a standard electrical connector at their proximal end. These designs facilitate a connection between the catheter electrode wires and a multi-pin connector that is outside of a patient's body. Often the size of this connection is unimportant in most catheter assemblies; however, when the size of the connection is constrained, the electrical connector is more difficult to accommodate. This challenge is further exacerbated when the catheter assembly is irrigated, which adds the complicating element of a fluid lumen connection. Accordingly, there remains a need for a catheter assembly that can be used for medical procedures such as ablation that addresses these issues and that will minimize and/or eliminate one or more of the above-identified deficiencies.
Cancer Subtype Discovery Based on Integrative Model of Multigenomic Data. One major goal of large-scale cancer omics study is to understand molecular mechanisms of cancer and find new biomedical targets. To deal with the high-dimensional multidimensional cancer omics data (DNA methylation, mRNA expression, etc.), which can be used to discover new insight on identifying cancer subtypes, clustering methods are usually used to find an effective low-dimensional subspace of the original data and then cluster cancer samples in the reduced subspace. However, due to data-type diversity and big data volume, few methods can integrate these data and map them into an effective low-dimensional subspace. In this paper, we develop a dimension-reduction and data-integration method for indentifying cancer subtypes, named Scluster. Firstly, Scluster respectively projects the different original data into the principal subspaces by an adaptive sparse reduced-rank regression method. Then, a fused patient-by-patient network is obtained for these subgroups through a scaled exponential similarity kernel method. Finally, candidate cancer subtypes are identified using spectral clustering method. We demonstrate the efficiency of our Scluster method using three cancers by jointly analyzing mRNA expression, miRNA expression and DNA methylation data. The evaluation results and analyses show that Scluster is effective for predicting survival and identifies novel cancer subtypes of large-scale multi-omics data.
#include <Arduino.h> #include "Constant.h" #include "StructType.h" #ifndef MyRelayArray_H #define MyRelayArray_H #define RELAY_SIZE 8 #define RELAY_STATE_CHANGE_TO_OFF 0 #define RELAY_STATE_CHANGE_TO_ON 1 #define RELAY_STATE_CHANGE_TO_TOGGLE 2 class MyRelayArray{ uint8_t* relayPins = NULL; bool* relayState = NULL; uint32_t* relayStateChangeSchedule = NULL; uint8_t* relayStateChangeTo = NULL; bool isPowerOffVar; public: void begin(); bool setRelayState(uint8_t i, uint8_t state); bool getRelayState(uint8_t i); bool toggleRelayState(uint8_t i); void scheduleRelayStateChange(uint8_t i, uint32_t scheduleAt, uint8_t changeTo); void resetScheduleForRelayStateChange(uint8_t i); RelaySchedule* getRelaySchedule(uint8_t relayIdx); void relayScheduleLookUp(uint32_t curTime); void powerOnOffToggle(); bool isPowerOff(); }; #endif
The effect of terminal chain modifications on the mesomorphic properties of 4,4-disubstituted diphenyldiacetylenes A variety of terminal chain modifications (Y) were made on the diacetylenes in which X=C n H2n+1, C12H25O and F, and Y=CH2CH(Me)C2H5, COCH3, C≡CC5H11, C n F2n+1 C n H2n+1 and CH=CHCO2C3H7. Mesomorphic properties were determined by hot stage polarizing microscopy and DSC. These were compared with those for the dialkyl analogues (X=C m H2 m +1, Y=C n H2 n +1) and a series of 1- and 2-olefins (Y=CH=CHC n H2 n +1 and CH2CH=CHC n H2 n +1). The 1-olefin series showed wider range nematics than the dialkyl compounds, whereas the above modifications showed either narrow range nematic phases, no mesophase or higher melting temperatures. New transition temperature and enthalpy data are provided for some of the dialkyl and F-alkyl compounds previously reported, for comparisons. Preliminary birefringence data are also included along with the results of some heat and UV stability studies.
A split bregman method for linear spectral unmixing Linear spectral unmixing is a popular tool to describe the remote sensing hyperspectral data. However, due to the huge size of hyperspectral data and the real-time processing, it needs a faster and more accurate algorithm. In this paper, we present a novel algorithm for linear spectral unmixing based on nonnegative matrix factorization (NMF), referred to as the split bregman method for NMF (SBNMF). The proposed algorithm takes advantage of the fast convergence of split bregman method, and at the same time optimizes the alternating update method, which help it get accurate results faster. The experimental results based on both synthetic mixtures and a real image scene demonstrate the superiority of our proposed algorithm.
Pesticides in My Smoothie Bowl? Teaching resources, especially active learning pedagogy, are scarce for toxicology compared to what is available for other disciplines. Ecological and human health risk assessment are important aspects of toxicology and are routinely used by government agencies to regulate the registration and usage of many chemicals. Most traditional toxicology classes do not cover how such risk assessments are carried out in real-world scenarios. We developed this case study to introduce concepts and processes of ecological and human health risk assessment in pesticide registration by the U.S. EPA. In Part 1, dialogues among three college friends introduce organic food, pesticides, and the concept of risk. Part 2 and Part 3 build on Part 1 and focus on ecological risk assessment and human health risk assessment, respectively. At the end of each section, students select appropriate exposure and toxicity endpoints to perform a mini-risk assessment and draw conclusions regarding risk. In Part 4, students examine real pesticide monitoring data in various foods and perform basic data organization and analysis. This case is appropriate for upper-level college students taking toxicology or other environmental science related courses. With modifications, the case study may also be suitable for introductory level environmental and biological science students. Learning Goals Toxicology Learning Framework How are organisms living in the natural environment affected by natural and anthropogenic toxicants? How is the science of toxicology applied to government regulations to ensure the protection of individuals and the environment? How does the concept of dose-response relate to toxicology? Science Process Skills Interpreting results/data Displaying/modeling results/data Learning Objectives Students will be able to: Define risk and differentiate hazard and risk Define risk assessment terminology including risk, toxicity, exposure, acute, chronic, LC50, EC50, NOEL/NOAEL, uncertainty factor (UF), safety factor (SF), and population adjusted dose (PAD). Describe applications of LC50, EC50, NOEL/NOAEL, uncertainty factor (UF), safety factor (SF), and population adjusted dose (PAD) in ecological and human risk assessment for regulatory purposes. Properly interpret toxicity and exposure data and select appropriate (i.e., normally the most protective) toxicity and exposure endpoints for screening level risk assessment for pesticides and potentially apply the same principles to other chemicals. Compare calculated ecological risk of pesticide exposure to levels of concern (LOC) and determine whether the risk is acceptable. Explain the extensive risk assessment process used by regulatory agencies to inform decisions of regulatory agencies. Organize and analyze large datasets of chemical monitoring data in Microsoft Excel or Google Sheets, including following manual instructions to read the data, locating a subset of data of interest, calculating basic statistics (i.e., mean, standard deviation, and standard error), and present the data in a graph. INTRODUCTION Even though educational resources for most subjects in biological and environmental sciences are readily available, teaching activities and materials for some highly specialized disciplines including toxicology are sparse. The only journal for publishing toxicology specific teaching pedagogy is the Journal of Toxicological Education, with only nine articles published since its establishment in 2013. A search conducted on July 20, 2021 using key words "toxicology" or "risk assessment" in the National Center for Case Study Teaching in Science (NCCSTS) database returned 16 relevant articles, a miniscule number compared to the hundreds of articles in other disciplines of biology and environmental science. Despite being an integral part of toxicology, risk assessment is often considered an advanced topic that may not be taught until students reach graduate school. Some undergraduate environmental science and toxicology courses may introduce risk assessment, but it is often taught in traditional lecture format without real-world examples and applications or with active learning activities. Definitions on key terms and description of major steps are given but there is limited opportunity for students to apply and practice what they learn. As such, students may find it difficult to truly grasp the meaning of risk assessment terms and how the process is done. One case study published in NCCSTS aims to teach students concepts in human risk assessment, in which students calculate the cancer and non-cancer risks of tetrachloroethylene in drinking water and perform an abbreviated human health risk assessment. The case presents a realistic situation where residents of a community near a contaminant source may be exposed to the chemical via drinking water and offers scaffolded instructions for students to calculate risk and reach a conclusion. Here, we developed a similar but more extensive teaching activity to teach students both ecological and human health risk assessment, and specifically, the key principles and steps adopted by the U.S. Environmental Protection Agency (EPA) during pesticide registration to inform regulatory decisions. We selected pesticides as the contaminants of interest because pesticides are widely used and ubiquitous in the environment. Additionally, risk assessment for pesticides is well developed and documented by regulatory agencies and this provides the perfect teaching material for students to learn this topic. In the U.S., the EPA is the government agency responsible for conducting risk assessment as part of the pesticide registration process to ensure pesticide products on the market do not cause unreasonable risk to humans and the environment. All risk assessment documents are readily available through the public docket as part of the registration process. This lesson focuses on pesticide risk assessment in the U.S. and centers around a case study which employs dialogues between fictional characters (college friends) throughout the case to engage students and to introduce students to the main topics of the lesson. These characters discuss the potential presence of pesticides in fruit, the definition of risk, government practice of evaluating pesticide risk, as well as finding reference pesticide residue levels in food. We feel the discussions between the fictional college students may resonate among students who have similar concerns with pesticide safety. For instance, Part 1 (Supporting File Pesticides in my Smoothie Bowl -Part 1. Pre-class assignment) begins with a conversation between the characters about the potential presence of pesticides in fruits and prompts students to think about what "organic" means. The conversation then transitions to a discussion on the concept of risk and how risk is determined which is tied to Part 2 (Supporting File S2. Pesticides in my Smoothie Bowl -Part 2. Ecological risk assessment). After students gain some background knowledge on pesticides and terminology associated with risk in Part 1, they will follow instructions in Part 2 (ecological risk assessment; Supporting File S2. Pesticides in my Smooth Bowl -Part 2 Ecological risk assessment) and Part 3 (human health risk assessment; Supporting File S3. Pesticides in my Smoothie Bowl -Part 3 Human risk assessment) to further learn factors considered during risk assessment and steps in risk determination. Scaffolded questions guide students through the complex process of interpreting toxicity and exposure endpoints, choosing appropriate endpoints for risk calculation, and comparing risk to reference levels for risk determination. A table is provided at the end of both sections for students to incorporate the endpoints they select to calculate risk and reach a conclusion. In Part 4 (Supporting File S4. Pesticides in my Smoothie Bowl -Part 4. A peek into pesticide monitoring data) of the lesson, students have an opportunity to "get a taste" of an authentic dataset and appreciate the vast amount of information scientists often work with, unlike the relatively small datasets students normally see in class. Students first need to read a supplemental document to understand what the columns in the dataset refer to before they can process the data properly. They learn how to use the "sort and filter" function to organize data and locate particular subsets of data for calculating basic statistical parameters in Excel. Finally, they practice these skills by completing a task in which they choose a food item and a pesticide of interest and determine if products from different countries contain different levels of a particular pesticide. Overall, we hope this teaching activity will improve student understanding of risk and risk assessment and perhaps better prepare students who wish to pursue professional careers in toxicology and risk assessment. Intended Audience This case study was intended for upper-level college students taking environmental toxicology or other environmental science related courses. However, it can be modified to be suitable for introductory level environmental and biological science students. Required Learning Time A two-week period with approximately 2.5 to 3 hours of class time each week. Prerequisite Student Knowledge For students, we recommend foundational mathematics and arithmetic as well as basic understanding of descriptive statistics (i.e., mean, standard deviation, and standard error). Preferably, students should also have some background knowledge on environmental contaminants especially how they may exert adverse effects on environmental and human health. Such knowledge, however, is not critical because even non-biology or non-environmental science students can often learn such information quickly through life experience and some reading. Instructor can assign the ToxTutor module on risk assessment prior to the lesson to ensure that students have a good understanding of the key concepts. Prior experience with Microsoft Excel or Google Sheets is also helpful for completing Part 4. Prerequisite Teacher Knowledge In addition to the prerequisite student knowledge, instructors are expected to have experience teaching environmental science related courses or topics. If such experience is not available, instructors should at least have some knowledge of environmental contamination, principles of risk assessment, and factors involved in risk assessment (e.g., toxicity, exposure, uncertainty, etc.). Some good sources for such information are the U.S. EPA and the ToxTutor module on risk assessment. The case study itself also provides some of the background information. More details regarding the malathion risk assessment and risk assessment in general can be obtained from the EPA risk assessment document. Active Learning Different from the traditional lecturing method, students go over the handouts (Supporting Files S1-4) and learn by reading the relevant information and answering questions. The questions allow students to promptly evaluate their understanding and correct any misconceptions. Students then apply their knowledge of endpoint selection, risk quotient (RQ), uncertainty factors, and risk determination to evaluate the risk of malathion for ecological and human health. Working in groups allows students to interact with their peers, exchange ideas, and discuss difficult concepts. Using authentic datasets and scenarios, this case study provides an opportunity for students to get experience handling real-world data. We also created dialogues of fictional characters to introduce topics of pesticides and risk assessment. These conversations discuss topics such as food, wildlife, pesticides, risk, etc., and may resonate with and engage students in learning about risk assessment. Assessment Questions and tasks are provided through the case study that allow students to learn, practice, and test their understanding promptly. Therefore, students are primarily assessed by their responses to pre-class and in-class formative assessment questions, discussion questions, and an end-of-section exercise for each part. For Parts 2 and 3, the risk determination tasks allow students to apply what they have learned to select appropriate toxicity and exposure endpoints and determine risk and draw conclusions. Similarly, students will select a sub-dataset of interest and conduct statistical analysis in Part 4. Inclusive Teaching The lesson introduces risk assessment through conversations between three friends about pesticides in food. Because food is such an integral part of everyday life, this introduction provides an interesting start point for all students to explore the lesson and learn about risk assessment. Additionally, students have an opportunity to select pesticides and foods of their interest to investigate in Part 4. This will allow students of different backgrounds to participate in the lesson based on their preference for food and pesticide. This lesson requires a computer, Microsoft Excel, and an Internet connection, which are readily available even in institutions with limited resources. Due to the recent transition to online learning, schools normally provide free computers and WiFi hotspots as well as computer labs on campus, which allow students to complete online coursework. If free Microsoft Excel is not available, students can use Google Doc and Google Sheet (free with a Gmail account) to view the lesson and the dataset and complete data analysis. We also recommend think-pair-share or group work while going through the questions to encourage participation of students who may struggle with the questions. Summary The lesson consists of four parts: a pre-class assignment, ecological risk assessment, human risk assessment, and reviewing a large dataset of pesticide monitoring data in various food items. In the pre-class assignment, students explore the meaning of "organic," common types of pesticides, and the difference between hazard and risk. In Part 2, scaffolded questions are provided to guide students through the steps of selecting appropriate toxicity and exposure endpoints to calculate RQ. Part 3 focuses on risk assessment for human health, which utilizes similar principles as ecological risk assessment but may appear more complex. Students learn adjustments of toxicity endpoints to account for uncertainty and sensitive populations. Part 4 presents authentic monitoring data of pesticides in food from the U.S. Food and Drug Administration (FDA) and provides an opportunity for students to practice handling large datasets which are common in the real world. This lesson is designed for a two-week class period with about 2.5-3 hours of instructional time per week to cover most of the key steps in screening level risk assessment for pesticides typically conducted by regulatory agencies such as the EPA. However, instructors can modify the lesson and/or choose the parts that align with their teaching objectives. For example, if data analysis and quantitative skills is not the focus of the course, Part 4 can be excluded, and more instructional time can potentially be spent on other parts for more in-depth learning. Preparation We recommend using a Learning Management System (LMS) to house and distribute all the documents of this lesson to students. Create a folder and upload all parts of the lesson (Supporting Files S1-S4). In the same folder, set up the prelab assignment in the quiz format to collect responses and to hold students responsible for completing the assignment before class. As there are dialogues and other non-question information in the pre-lab assignment, include only the actual questions in the quiz without the additional reading material. Instruct students to read the handout and then submit their answers by completing the quiz. Posting the questions as a quiz in the LMS allows for easy tracking of student completion and quick grading as the multiple-choice questions can be graded automatically. Additionally, the LMS can often generate a report on student responses for each question 4 which is valuable to assess student understanding. For Parts 2-4, instructors can print out hard copies of the handout or make sure students have access to a computer. Part 1: Pre-Class Assignment Assign the pre-class section prior to in-class activities so that students have some background knowledge on pesticides and some of the factors involved in risk calculation. The dialogue between the fictional characters touches on some controversial and debated topics among the public including food safety, ecological impact of pesticides, and organic food. The questions in this section are designed to make students ponder these topics and stimulate their interest in evaluating pesticide safety to humans and other organisms. If instructors have time to cover this section in class rather than assigning this as a pre-class assignment, it may be fun and engaging to have students act as the characters. Questions 1-3 prompt students to research organic food. Students often have little knowledge or even misconceptions about what the term "organic" entails. Federal guidelines stipulate what can be called "organic" and one of the requirements is that there is no application of synthetic pesticides to the soil (for three years), crops, or feed for livestock. Unlikely naturally occurring substances, synthetic pesticides are artificially manufactured and are often potent and exert greater adverse effects to environmental and human health. When reviewing student answers for these questions, encourage students to discuss what they know before and after the assignment about what constitutes organic. Risk is determined by severity of the hazard and how likely the particular hazard may occur. As discussed in the dialogue between the fictional characters, something that is less hazardous but occurs more often may be riskier than those that have a more severe consequence but rarely happens. In chemical risk assessment, we have to consider the hazard (i.e., toxic effect) and likelihood of occurrence (i.e., possible concentrations that organisms encounter). It is key to make sure students correct any misconceptions about risk in risk assessment before moving on to Part 2. After students have a better understanding of risk, they learn the definition of chemical risk from the EPA website (Q7) and factors considered in risk assessment (Q8). The student handout provides detailed information on terminology, including RQ and common acute and chronic toxicity data collected for risk calculation. Students then answer Q9 and Q10 to test their understanding of RQ and common endpoints. Question 11 emphasizes that chemical exposure can occur in various routes, all of which need to be considered during risk assessment. Students learn the frequent need to adopt model-generating exposure levels in determining risk in Q12 and Q13. Table 1 introduces some common model organisms used in toxicity testing, and prompts students to think about variations in test durations related to taxonomic groups in Q14, as well as the common practice to assess short-term and long-term toxicity. If this section is assigned pre-class, spend about 15 minutes at the beginning of the class to review the questions in this section before letting students work on Part 2. It is possible that it may take longer to review this section if students are interested in discussing organic food and risk. Part 2: Ecological Risk Assessment Through scaffolded questions, Part 2 walks students through a mini ecological risk assessment for malathion during the pesticide re-registration process and introduces students to the steps of a typical pesticide ecological risk assessment. All the data used in this section are real data from a pesticide re-registration review document for malathion. As there are many new terminologies and concepts in this section, it may be better to break this part into two shorter subsections consisting of questions of related topics. We recommend giving students time to finish one subsection and then review the questions rather than let students finish the entire section and then go over answers. This makes the relatively long Part 2 more manageable to students and helps reduce the chances that students get distracted while working on the problems. We suggest dividing this section to the following subsections (instructors can modify as they see fit). Subsection 1: Questions 15-19 Questions 15, 16, and 17 test student understanding of the relationship between toxicity endpoints and a chemical's toxicity, and the relationship between toxicity endpoints and species sensitivity to a chemical. Keep in mind that a lower toxicity endpoint indicates higher toxicity. It is often hard for students to grasp this concept. An example can be given to help students understand: Chemical A has a LC50 of 0.1 mg/L and Chemical B has a LC50 of 1 mg/L. Based on the LC50 data, we know that 0.1 mg/L of Chemical A kills 50% of test organisms whereas it requires 1 mg/L of Chemical B (10 times the amount of Chemical A) to kill 50% of the same test organisms. In other words, it takes less of Chemical A to kill the same number of individuals than Chemical B. Therefore, Chemical A is more toxic than Chemical B. Similarly, a species with a lower toxicity endpoint of a particular chemical (e.g., LC50 or LD50) is more sensitive to this chemical than another species with a higher toxicity endpoint. With such knowledge, students will be able to choose the most conservative (i.e., protective) endpoints and species when calculating the RQ later in this section. Once a RQ is calculated, it is compared to the EPA's Level of Concern (LOC) and Risk Presumptions provided in Table 2. Students think about why LOCs for endangered and threatened species are lower than non-listed species in Q18. Question 19 is a good practice for students to use available data to calculate the RQ and compare it to LOC to determine if there is any potential risk. Subsection 2: Questions 20-29 The rest of Part 2 breaks the fairly complicated process of ecological risk assessment down into simplified steps. Students learn important concepts related to toxicity and exposure, the two key parts of a risk quotient. Questions 20-22 are about choosing protective toxicity endpoints to protect more sensitive organisms. This is another test of student understanding of the relationship between toxicity endpoints and species sensitivity introduced in Q15-17. Questions 23-27 guide students through the process of selecting appropriate exposure endpoints. There are commonly three exposure estimates available including a 21-day average, a 60-day average, and a peak concentration. Q23 and 24 prompt students to interpret the exposure data 5 and select exposure values that are most protective. Another factor to consider when selecting appropriate exposure values for RQ calculation is that the exposure endpoint should also be appropriate for the model organism. For instance, the 21-day average should be used to calculate chronic RQ for aquatic invertebrates that do not have a long lifespan, whereas a 60-day average is appropriate for calculating chronic RQ for fish. Questions 25, 26, and 27 are designed to help students understand such concepts. At the end of the section, students fill out the risk table in Q28 and determine RQs and provide their conclusion in Q29. If time is running out in class, these two questions can be assigned as homework and instructors can spend a few minutes to go over the answers in the next class session. Part 3: Human Health Risk Assessment The final section takes the process of risk assessment learned in Part 2 and applies the same general principles to human health risk assessment. This part begins with another discussion among the fictional characters about whether pesticides in food may affect human health and how food safety is ensured by government agencies through risk assessment. Many of the concepts in human risk assessment are similar to ecological risk assessment, but here students are introduced to the concept of uncertainty factors to create conservative estimates of risk when that approach is warranted (as we do with human health risk assessment). Question 30 allows students to expand what they know about exposure routes from Part 2 and consider more exposure routes in human risk assessment due to the complexity of human activities. Question 31 brings up a common scenario risk assessors face regarding selection of sex when conducting mammalian toxicity testing for human risk assessment. Students learn about the potential higher sensitivity of females due to reproduction and body mass. Questions 32-34 are designed to introduce the inter-and intra-species variations when using non-human test species and how such uncertainty is accounted for in human risk assessment using the uncertainty factor (UF) and margin of safety (10x in the case of malathion). Question 35 and 36 then ask students to apply these adjustment factors to derive a Population Adjusted Dose (PAD). The PAD, similar to the toxicity endpoints in ecological risk assessment, is used along with the exposure endpoints to estimate the risk. The process of obtaining toxicity endpoints for human risk assessment is more complex than ecological risk assessment. But once students understand the need to adjust the toxicity endpoints to account for interspecies extrapolation and intraspecies variations, the PAD is basically the value after the original toxicity endpoints is adjusted twice by the UF and the margin of safety, respectively. The handout then introduces risk calculation and reference levels for human risk assessment. Similar to an ecological RQ, risk is also calculated by dividing the exposure by the PAD. However, instead of comparing the risk value directly to levels of concern as in ecological risk assessment, risk for human health should be converted to a percentage value which is then compared to pre-determined LOC of 100%. In another word, risk is presumed if the exposure level is equal to or greater than the PAD. Students often get confused by the "directions" that are an inherent part of the process. For example, as mentioned in Part 2, counterintuitively, a lower LC50/NOEL/BMDL etc. means the compound is more toxic rather than less toxic. If they have this relationship backwards in their minds, then their uncertainty factor correction will also be backwards, so it is recommended to stop and check that this understanding of toxicity is correct before going into the uncertainty factor corrections. Anytime an uncertainty factor or a safety factor is applied, the original toxicity endpoint should always be divided by the uncertainty factor to generate a lower new endpoint which is more conservative and protective. Another challenge many students may face is the presence of many terms used as toxicity endpoints for human risk assessment and how these terms are related to one another. We have created a flow chart (Figure 1) to help instructors and students develop a better picture of how these terms are calculated and applied in the risk assessment process. Please note that the flow chart only includes the terms mentioned in this particular risk assessment for malathion. As reported previously, there is great potential for enriched discussions in this section. In the beginning, Q32-34 all offer opportunities to discuss aspects of the use of surrogate species and/or how we generate information about toxicity without performing experiments on people (which is generally considered morally unacceptable). Finally, as you reach the end of this case study, we strongly suggest asking students to reflect on what they have learned and how their view of pesticides, regulation, and risk have changed over the course of this case study. Some of the closing questions provide great "bookend" discussions that can be combined with similar discussions that happen at the beginning of the case study based on students' answers to the pre-class questions. Part 4. A Peek into Pesticide Monitoring Data This section is not meant to provide an extensive and indepth look into data analysis and interpretation. Instead, it is designed for students to have an opportunity to see the scale and quantity of real-world monitoring data conducted by government agencies. Give students a few minutes to open the data file and glance through the data. In Q41-43, students practice reading a data file and especially using supplemental information to identify the various components in the data file, which is important for correctly interpreting data. If this is the first time that students have dealt with ppm (parts per million) and ppb (parts per billion), take a few minutes to go over the units and make sure students convert between the two units correctly in Q42 (f). Question 44 shows students a few features in Excel that facilitate data viewing and sorting. In Q45, students follow instructions to locate the data of interest and conduct a t-test to compare two groups of data. They present the data using a bar graph to show the mean with standard error. Question 46 is an exercise where students select any data they are interested in and perform data organization and analysis. TEACHING DISCUSSION At the beginning of Class Session 1 when reviewing the preclass assignment, have the students discuss what they thought about pesticides previously (if at all). It is an interesting teachable moment to correct the common misconception of what the term "organic" means. Many students will assume it means food grown without the use of any chemicals (which is incorrect). This generates a really engaging discussion that sets the tone for the rest of the case study and in our experience does a good job of grabbing student attention to the topic. In Part 2, students learn how to properly evaluate risk. People (students and adults alike) are generally poor at assessing risk. We think nothing of performing risky behaviors daily (like driving in our car), but then might have fears regarding perfectly safe activities (like riding a roller coaster, removing a spider from the house, or flying in a plane). It is important to point out these blind spots because it can skew our understanding of risk. Chemicals can easily fall into that category of things we fear when there is no reason to do so (or alternatively we can be accustomed to ingesting foods without considering potential risks). Additionally, there can be a good discussion towards the end of Part 2 when the students find there is potential for risk from the cotton applications. You can ask students questions to extend the knowledge they have learned: What can be done to mitigate the potential risk found here? What other information would you like to have to make a decision to approve or deny this pesticide? What level of risk is acceptable? In Part 3, it may be helpful to show students the human risk assessment flow chart created for instructors. Some students will be confused about the multi-step adjustment for uncertainty. The flow chart provides a visual guide on the entire process. Instructors can also ask students to make their own flow chart. More time should be given to students if they need to create the flow chart. For the data analysis in Part 4, instructors can modify as needed. For instance, replace the t-test with ANOVA and have students compare three or more questions if the data allow. Similar to the t-test, there are online ANOVA calculators available for students who use Google Sheets or have trouble installing the data analysis package in Excel. One note about the data presented in the lesson. It is important that students do not walk away from this class thinking that malathion is an extreme environmental risk. The ecological risk assessment process described here is a very conservative one with many built-in assumptions that increase perceived risk. It might be worth pointing out to students that the risk assessment process has 4 tiers and at the 1st tier (essentially what is being presented in Part 2), estimates of exposure are extreme and toxicity estimates used are "worst case scenarios." If a chemical/pesticide fails at any particular tier of the process, it moves up to a higher tier that is more specific to that pesticide's applications and more realistic in terms of exposure and toxicity estimates (when possible). Malathion is not without risk but has been used for decades without wiping out entire aquatic invertebrate communities.
<filename>FOSS_Thesis_Webscraping_JobInfoSearch/src/survfate/jobinfosearch/XLSFileFilter.java package survfate.jobinfosearch; import java.io.File; public class XLSFileFilter extends javax.swing.filechooser.FileFilter { @Override public boolean accept(File file) { if (file.isDirectory()) return true; String filename = file.getName(); return filename.toUpperCase().endsWith(".XLS"); } @Override public String getDescription() { return "Excel 97-2003 Workbook (*.xls)"; } }
#include <stdio.h> void printResult(const int); int main(void) { int n; scanf("%d", &n); printResult(n); return 0; } void printResult(const int n) { int i = 0, j = 0, num = 1; const int final = n * n; int control = (i / n) % 2; while (i < final) { if (!control) { printf(" %d", num++); i++; } else { printf(" %d", num--); i++; } if (i % n == 0 && i != 0) { putchar('\n'); num += n; num += control == 0 ? -1 : 1; control = (i / n) % 2; } } }
<reponame>banrieen/PerfBoard<gh_stars>100-1000 import pandas as pd def simple_table(csf_file="", output=""): csv_file = pd.read_csv(csf_file) csv_file.to_html(output) # html_file = csv_file.to_html() return True if __name__ == "__main__": simple_table(r"testresult/taurus-result-songshanhu-test-overview.csv", r"testresult/taurus-result-songshanhu-test-overview.html")
/* * Copyright (c) 2007-2012 SlimDX Group * * 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 "../math/Vector3.h" using System::Runtime::InteropServices::OutAttribute; namespace SlimDX { namespace Direct3D9 { value class VertexElement; enum class VertexFormat; enum class Format; /// <summary> /// Contains miscellaneous constants and methods for use with D3DX. /// </summary> /// <unmanaged>None</unmanaged> public ref class D3DX sealed { private: D3DX() { } public: /// <summary> /// The value used to signify that the default value for a parameter should be used. /// </summary> /// <unmanaged>D3DX_DEFAULT</unmanaged> literal int Default = D3DX_DEFAULT; /// <summary> /// The default value for non power-of-two textures. /// </summary> /// <unmanaged>D3DX_DEFAULT_NONPOW2</unmanaged> literal int DefaultNonPowerOf2 = D3DX_DEFAULT_NONPOW2; /// <summary> /// Indicates that the method should load from file. /// </summary> /// <unmanaged>D3DX_FROM_FILE</unmanaged> literal int FromFile = D3DX_FROM_FILE; /// <summary> /// Indicates that the method should format from file. /// </summary> /// <unmanaged>D3DFMT_FROM_FILE</unmanaged> literal int FormatFromFile = D3DFMT_FROM_FILE; /// <summary> /// /// </summary> /// <unmanaged>D3DXGetDeclVertexSize</unmanaged> static int GetDeclarationVertexSize( array<VertexElement>^ elements, int stream ); /// <unmanaged>D3DXGetFVFVertexSize</unmanaged> static int GetFVFVertexSize( VertexFormat fvf ); /// <summary> /// Retrieves a declarator from a Flexible Vertex Format (FVF) code. /// </summary> /// <unmanaged>D3DXDeclaratorFromFVF</unmanaged> static array<VertexElement>^ DeclaratorFromFVF( VertexFormat fvf ); /// <summary> /// Retrieves a Flexible Vertex Format (FVF) code from a declarator. /// </summary> /// <unmanaged>D3DXFVFFromDeclarator</unmanaged> static VertexFormat FVFFromDeclarator( array<VertexElement>^ declarator ); /// <summary> /// Generates an output vertex declaration from the input declaration. /// The output declaration is intended for use by the mesh tessellation functions. /// </summary> /// <unmanaged>D3DXGenerateOutputDecl</unmanaged> static array<VertexElement>^ GenerateOutputDeclaration( array<VertexElement>^ declaration ); /// <summary>Returns the number of elements in the vertex declaration.</summary> /// <unmanaged>D3DXGetDeclLength</unmanaged> static int GetDeclarationLength( array<VertexElement>^ declaration ); /// <summary>Gets the size of the rectangle patch.</summary> /// <unmanaged>D3DXRectPatchSize</unmanaged> static Result GetRectanglePatchSize( float segmentCount, [Out] int% triangleCount, [Out] int% vertexCount ); /// <summary>Gets the size of the triangle patch.</summary> /// <unmanaged>D3DXTriPatchSize</unmanaged> static Result GetTrianglePatchSize( float segmentCount, [Out] int% triangleCount, [Out] int% vertexCount ); /// <summary>Generates a FOURCC Format code from the provided bytes.</summary> /// <unmanaged>MAKEFOURCC</unmanaged> static Format MakeFourCC( System::Byte c1, System::Byte c2, System::Byte c3, System::Byte c4 ); /// <summary>Turns on or off all D3DX debug output.</summary> /// <unmanaged>D3DXDebugMute</unmanaged> static bool DebugMute( bool mute ); /// <summary>Generates an optimized face remapping for a triangle list.</summary> /// <unmanaged>D3DXOptimizeFaces</unmanaged> static array<int>^ OptimizeFaces( array<int>^ indices, int faceCount, int vertexCount ); /// <summary>Generates an optimized face remapping for a triangle list.</summary> /// <unmanaged>D3DXOptimizeFaces</unmanaged> static array<int>^ OptimizeFaces( array<System::Int16>^ indices, int faceCount, int vertexCount ); /// <summary>Generates an optimized vertex remapping for a triangle list. </summary> /// <unmanaged>D3DXOptimizeFaces</unmanaged> static array<int>^ OptimizeVertices( array<int>^ indices, int faceCount, int vertexCount ); /// <summary>Generates an optimized vertex remapping for a triangle list. </summary> /// <unmanaged>D3DXOptimizeFaces</unmanaged> static array<int>^ OptimizeVertices( array<System::Int16>^ indices, int faceCount, int vertexCount ); /// <summary> /// Verifies that the compiled version of D3DX matches the runtime version of D3DX. /// </summary> /// <returns><c>true</c> if the versions match; otherwise, <c>false</c>.</returns> /// <unmanaged>D3DXCheckVersion</unmanaged> static bool CheckVersion(); /// <unmanaged>D3DXFresnelTerm</unmanaged> static float FresnelTerm( float cosTheta, float refractionIndex ); static array<Vector3>^ GetVectors( DataStream^ stream, int vertexCount, VertexFormat format ); static array<Vector3>^ GetVectors( DataStream^ stream, int vertexCount, int stride ); }; } }
General Motors officially launched its new electric motor in White Marsh Tuesday, a milestone in U.S. manufacturing — and a key part of the company's bet that the electric-vehicle market is poised to grow. With production under way at the Baltimore County "eMotor" plant, GM says, the company is the first automaker to manufacture electric-drive motors domestically. The operation is small for now: About 20 employees make motors for the plug-in electric Chevrolet Spark EV, side by side with 27 robots. Local leaders hope for growth — something that depends on consumers. Whether they will buy all-electric vehicles in significant numbers is the question facing White Marsh, GM and the entire auto industry, said Brett Smith, co-director of manufacturing, engineering and technology at the Center for Automotive Research in Ann Arbor, Mich. "We know we can sell this car to a small, small percentage of the population who is absolutely passionate about the environment or the technology," he said. "The challenge … is can we create a technology, a vehicle, that the average buyer can look at and say, 'That is a cost-competitive vehicle'?" GM said the Spark EV will hit the market at under $25,000 — but only after accounting for a $7,500 federal income tax credit. (A gas-powered version of the Spark sells for less than $13,000.) The subcompact car will go on sale this summer in California and Oregon. GM plans to sell it in Canada, Europe and South Korea later in the year but has no timeline yet for other markets, including the rest of the United States. The "electric drive" market — including hybrids — accounts for about 3.8 percent of U.S. auto sales, according to the Electric Drive Transportation Association. That's up from 2.2 percent in 2011. But for now, the lion's share of those purchases are hybrids that can run on gas, rather than pure electric vehicles such as the Spark EV. Automakers sold about 9,200 all-electric vehicles in the first three months of this year, compared with nearly 130,000 hybrids and plug-in hybrids. GM won't disclose the number of motors it can produce in its new 110,000-square-foot facility. But the plant's manager, William Tiger, said there's room to grow. "Put it this way — buy as many as you want," he said. "We'll build them." Government officials believe in the potential for growth. GM built its White Marsh eMotor facility with $105 million from the U.S. Department of Energy in addition to its own $121 million investment. The state has offered up to $3 million in economic-development grants, though Maryland officials believe GM will ultimately qualify for $2 million. That's based on hiring at the entire facility, not just at the electric-motor plant. GM's transmission plant next door employs most of the 250 people on site, an increase of 65 jobs since the state struck its original incentive deal with GM three years ago. The company reversed layoffs and hired new people as the market for its A1000 transmission improved. If GM can get employment up to 374 jobs in total, it will qualify for $6 million in grants from Baltimore County. GM apparently expected to have more people on the electric-motor side by now. As recently as last year, the company said it would hire about 189 workers for that operation, but now the company isn't offering forecasts for job growth there. Baltimore County Executive Kevin Kamenetz, who toured the site Tuesday, offered no complaints about the size of employment so far. "I'm just grateful for GM choosing Baltimore County to invest in the product, and the jobs they offer are good-paying jobs with great benefits," he said. "This second building is a substantial investment on their part, both in terms of the structure as well as the equipment, but it also hopefully will provide a glimpse of further opportunities that they could develop on the campus." Anirban Basu, head of Sage Policy Group, a Baltimore economic and policy consulting firm, said government investments in private enterprises don't always pan out. But he thinks it's the right move for developing and expanding new technologies, including those involved with electric vehicles. "I think the long term is very much working toward electric vehicles gaining market share," Basu said. He pointed out that oil is costly but natural gas for electricity is cheap and plentiful. "For the region to gain a foothold in that emerging segment is very important." GM leaders say they're serious about the market. That's why they chose to build the Spark EV motor themselves, rather than rely on a supplier — they want an intimate understanding of what works. "Big area, big opportunity," said Larry T. Nitz, executive director of electrification for GM. "We are committed to electrification." Kamenetz said he's optimistic about the Spark EV's potential after test-driving one of the sky-blue models parked outside the building Tuesday. He thinks GM, which plans to sell in only two states at first, is underestimating its likely domestic appeal. "I have to tell you, I got into it thinking that it would be just be one of these typical subcompacts, but I got out of it recognizing that this is truly a car of the future," Kamenetz said. The Spark EV starts with the push of a button, runs quietly and can go from zero to 60 mph in under eight seconds. Tiger waited for a break in the test drives Tuesday, and then said, "Can I try it?" He said he hadn't yet, even though it's his plant that makes the motors. Given the opportunity, he hit the accelerator and zipped off. Though Tuesday was the official launch, workers began making the motors months ago — first in production trials, then switching to salable versions in February. Tuesday morning, machines in the robot-heavy plant kept up a steady din as copper wire, laminated steel and other parts came together into 75-pound motors. Stephanie Spivey, a rotor assembly technician from Ellicott City, gave visitors a demonstration of the work she began doing only recently.
<filename>FracTales/Plugins/Wwise/Source/AudiokineticTools/Private/AudiokineticToolsModule.cpp // Copyright (c) 2006-2012 Audiokinetic Inc. / All Rights Reserved /*============================================================================= AudiokineticToolsModule.cpp =============================================================================*/ #include "AudiokineticToolsPrivatePCH.h" #include "ModuleManager.h" // @todo sequencer uobjects: The *.generated.inl should auto-include required headers (they should always have #pragma once anyway) #include "AkAudioDevice.h" #include "AkAudioClasses.h" #include "AkAudioBankFactory.h" #include "AkAudioEventFactory.h" #include "ActorFactoryAkAmbientSound.h" #include "AkComponentVisualizer.h" #include "MatineeModule.h" #include "MatineeClasses.h" #include "InterpTrackAkAudioEventHelper.h" #include "InterpTrackAkAudioRTPCHelper.h" #include "AssetToolsModule.h" #include "ContentBrowserModule.h" #include "AssetTypeActions_AkAudioBank.h" #include "AssetTypeActions_AkAudioEvent.h" #include "AssetTypeActions_AkAuxBus.h" #include "AssetTypeActions_AkAcousticTexture.h" #include "Editor/LevelEditor/Public/LevelEditor.h" #include "ISettingsModule.h" #include "AkSettings.h" #include "AkEventAssetBroker.h" #include "ComponentAssetBroker.h" #include "WaapiPicker/SWaapiPicker.h" #include "WaapiPicker/WwiseTreeItem.h" #include "AkAudioStyle.h" #include "SDockTab.h" #include "AssetRegistryModule.h" #include "UnrealEdMisc.h" #include "Editor/UnrealEdEngine.h" #include "Settings/ProjectPackagingSettings.h" #include "PropertyEditorModule.h" #include "UnrealEdGlobals.h" #include "WorkspaceMenuStructure.h" #include "WorkspaceMenuStructureModule.h" #include "ISequencerModule.h" #include "MovieScene.h" #include "MovieSceneAkAudioRTPCTrackEditor.h" #include "MovieSceneAkAudioEventTrackEditor.h" #include "AkMatineeImportTools.h" #include "MatineeToLevelSequenceModule.h" #include "WwiseEventDragDropOp.h" #include "AkSurfaceReflectorSetDetailsCustomization.h" #include "AkLateReverbComponentDetailsCustomization.h" #include "AkRoomComponentDetailsCustomization.h" #include "AkSurfaceReflectorSetComponentVisualizer.h" #include "WwisePicker/SWwisePicker.h" #include "AkAcousticPortalVisualizer.h" #define LOCTEXT_NAMESPACE "AkAudio" DEFINE_LOG_CATEGORY_STATIC(LogAudiokineticTools, Log, All); extern void AddGenerateAkBanksToBuildMenu(FMenuBuilder& MenuBuilder); class FAudiokineticToolsModule : public IAudiokineticTools { TSharedRef<SDockTab> CreateWaapiPickerWindow(const FSpawnTabArgs& Args) { return SNew(SDockTab) .Icon(FSlateIcon(FAkAudioStyle::GetStyleSetName(), "AudiokineticTools.AkPickerTabIcon").GetIcon()) .Label(LOCTEXT("AkAudioWaapiPickerTabTitle", "Waapi Picker")) .TabRole(ETabRole::NomadTab) .ContentPadding(5) [ SAssignNew(AkWaapiPicker, SWaapiPicker) .OnDragDetected(FOnDragDetected::CreateRaw(this, &FAudiokineticToolsModule::HandleOnDragDetected)) ]; } TSharedRef<SDockTab> CreateWwisePickerWindow(const FSpawnTabArgs& Args) { return SNew(SDockTab) .Icon(FSlateIcon(FAkAudioStyle::GetStyleSetName(), "AudiokineticTools.AkPickerTabIcon").GetIcon()) .Label(LOCTEXT("AkAudioWwisePickerTabTitle", "Wwise Picker")) .TabRole(ETabRole::NomadTab) .ContentPadding(5) [ SAssignNew(AkWwisePicker, SWwisePicker) ]; } FReply HandleOnDragDetected(const FGeometry& Geometry, const FPointerEvent& MouseEvent) { if (MouseEvent.IsMouseButtonDown(EKeys::LeftMouseButton)) { const TArray<TSharedPtr<FWwiseTreeItem>>& SelectedItems = AkWaapiPicker->GetSelectedItems(); return FReply::Handled().BeginDragDrop(FWwiseEventDragDropOp::New(SelectedItems)); } return FReply::Unhandled(); } void OpenOnlineHelp() { FPlatformProcess::LaunchFileInDefaultExternalApplication(TEXT("https://www.audiokinetic.com/library/?source=UE4&id=index.html")); } void AddWwiseHelp(FMenuBuilder& MenuBuilder) { MenuBuilder.BeginSection("AkHelp", LOCTEXT("AkHelpLabel", "Audiokinetic")); MenuBuilder.AddMenuEntry( LOCTEXT("AkWwiseHelpEntry", "Wwise Help"), LOCTEXT("AkWwiseHelpEntryToolTip", "Shows the online Wwise documentation."), FSlateIcon(), FUIAction(FExecuteAction::CreateRaw(this, &FAudiokineticToolsModule::OpenOnlineHelp))); MenuBuilder.EndSection(); } FString GetWwisePluginContentDir() { #if UE_4_18_OR_LATER const auto ProjectPluginsDir = FPaths::ProjectPluginsDir(); #else const auto ProjectPluginsDir = FPaths::GamePluginsDir(); #endif // UE_4_18_OR_LATER FString WwiseContent = TEXT("Wwise/Content"); if (FPaths::DirectoryExists(FPaths::EnginePluginsDir() / "Wwise") && FPaths::DirectoryExists(ProjectPluginsDir / "Wwise")) { FMessageDialog::Open(EAppMsgType::Ok, LOCTEXT("InstallConflict", "The Wwise UE4 Integration plug-in is installed in both the UE4 Engine and Game \"Plugins\" folder. This will cause conflicts. Please ensure the Wwise plug-in is installed in only one of the two locations.")); } if (FPaths::DirectoryExists(ProjectPluginsDir / WwiseContent)) { return ProjectPluginsDir / WwiseContent; } else { return FPaths::EnginePluginsDir() / WwiseContent; } } void VerifyAkSettings() { UAkSettings* AkSettings = GetMutableDefault<UAkSettings>(); if (AkSettings) { if (AkSettings->WwiseProjectPath.FilePath.IsEmpty()) { if (!AkSettings->SuppressWwiseProjectPathWarnings) { if (EAppReturnType::Yes == FMessageDialog::Open(EAppMsgType::YesNo, LOCTEXT("SettingsNotSet", "Wwise settings do not seem to be set. Would you like to open the settings window to set them?"))) { FModuleManager::LoadModuleChecked<ISettingsModule>("Settings").ShowViewer(FName("Project"), FName("Plugins"), FName("Wwise")); } } else { UE_LOG(LogAudiokineticTools, Log, TEXT("Wwise project not found. The Wwise picker will not be usable.")); } } else { // First-time plugin migration: Project might be relative to Engine path. Fix-up the path to make it relative to the game. #if UE_4_18_OR_LATER const auto ProjectDir = FPaths::ProjectDir(); #else const auto ProjectDir = FPaths::GameDir(); #endif // UE_4_18_OR_LATER FString FullGameDir = FPaths::ConvertRelativePathToFull(ProjectDir); FString TempPath = FPaths::ConvertRelativePathToFull(FullGameDir, AkSettings->WwiseProjectPath.FilePath); if (!FPaths::FileExists(TempPath)) { if (!AkSettings->SuppressWwiseProjectPathWarnings) { TSharedPtr<SWindow> Dialog = SNew(SWindow) .Title(LOCTEXT("ResetWwisePath", "Re-set Wwise Path")) .SupportsMaximize(false) .SupportsMinimize(false) .FocusWhenFirstShown(true) .SizingRule(ESizingRule::Autosized); TSharedRef<SWidget> DialogContent = SNew(SVerticalBox) + SVerticalBox::Slot() .FillHeight(0.25f) [ SNew(SSpacer) ] + SVerticalBox::Slot() .AutoHeight() [ SNew(STextBlock) .Text(LOCTEXT("AkUpdateWwisePath", "The Wwise UE4 Integration plug-in's update process requires the Wwise Project Path to be set in the Project Settings dialog. Would you like to open the Project Settings?")) .AutoWrapText(true) ] + SVerticalBox::Slot() .FillHeight(0.75f) [ SNew(SSpacer) ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SCheckBox) .Padding(FMargin(6.0, 2.0)) .OnCheckStateChanged_Lambda([&](ECheckBoxState DontAskState) { AkSettings->SuppressWwiseProjectPathWarnings = (DontAskState == ECheckBoxState::Checked); }) [ SNew(STextBlock) .Text(LOCTEXT("AkDontShowAgain", "Don't show this again")) ] ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.0f) [ SNew(SSpacer) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(0.0f, 3.0f, 0.0f, 3.0f) [ SNew(SButton) .Text(LOCTEXT("Yes", "Yes")) .OnClicked_Lambda([&]() -> FReply { FModuleManager::LoadModuleChecked<ISettingsModule>("Settings").ShowViewer(FName("Project"), FName("Plugins"), FName("Wwise")); Dialog->RequestDestroyWindow(); AkSettings->UpdateDefaultConfigFile(); return FReply::Handled(); }) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(0.0f, 3.0f, 0.0f, 3.0f) [ SNew(SButton) .Text(LOCTEXT("No", "No")) .OnClicked_Lambda([&]() -> FReply { Dialog->RequestDestroyWindow(); AkSettings->UpdateDefaultConfigFile(); return FReply::Handled(); }) ] ]; Dialog->SetContent(DialogContent); FSlateApplication::Get().AddModalWindow(Dialog.ToSharedRef(), nullptr); } else { UE_LOG(LogAudiokineticTools, Log, TEXT("Wwise project not found. The Wwise picker will not be usable.")); } } else { FPaths::MakePathRelativeTo(TempPath, *ProjectDir); AkSettings->WwiseProjectPath.FilePath = TempPath; AkSettings->UpdateDefaultConfigFile(); } } } if (GUnrealEd != NULL) { GUnrealEd->RegisterComponentVisualizer(UAkComponent::StaticClass()->GetFName(), MakeShareable(new FAkComponentVisualizer)); GUnrealEd->RegisterComponentVisualizer(UAkSurfaceReflectorSetComponent::StaticClass()->GetFName(), MakeShareable(new FAkSurfaceReflectorSetComponentVisualizer)); GUnrealEd->RegisterComponentVisualizer(UAkPortalComponent::StaticClass()->GetFName(), MakeShareable(new UAkPortalComponentVisualizer)); } } EAssetTypeCategories::Type AudiokineticAssetCategoryBit; void LateRegistrationOfMatineeToLevelSequencer() { IMatineeToLevelSequenceModule& Module = FModuleManager::LoadModuleChecked<IMatineeToLevelSequenceModule>(TEXT("MatineeToLevelSequence")); ConvertMatineeRTPCTrackHandle = Module.RegisterTrackConverterForMatineeClass(UInterpTrackAkAudioRTPC::StaticClass(), IMatineeToLevelSequenceModule::FOnConvertMatineeTrack::CreateLambda([](UInterpTrack* Track, FGuid PossessableGuid, UMovieScene* NewMovieScene) { if (Track->GetNumKeyframes() != 0 && PossessableGuid.IsValid()) { const UInterpTrackAkAudioRTPC* MatineeAkAudioRTPCTrack = StaticCast<const UInterpTrackAkAudioRTPC*>(Track); UMovieSceneAkAudioRTPCTrack* AkAudioRTPCTrack = NewMovieScene->AddTrack<UMovieSceneAkAudioRTPCTrack>(PossessableGuid); FAkMatineeImportTools::CopyInterpAkAudioRTPCTrack(MatineeAkAudioRTPCTrack, AkAudioRTPCTrack); } })); ConvertMatineeEventTrackHandle = Module.RegisterTrackConverterForMatineeClass(UInterpTrackAkAudioEvent::StaticClass(), IMatineeToLevelSequenceModule::FOnConvertMatineeTrack::CreateLambda([](UInterpTrack* Track, FGuid PossessableGuid, UMovieScene* NewMovieScene) { if (Track->GetNumKeyframes() != 0 && PossessableGuid.IsValid()) { const UInterpTrackAkAudioEvent* MatineeAkAudioEventTrack = StaticCast<const UInterpTrackAkAudioEvent*>(Track); UMovieSceneAkAudioEventTrack* AkAudioEventTrack = NewMovieScene->AddTrack<UMovieSceneAkAudioEventTrack>(PossessableGuid); FAkMatineeImportTools::CopyInterpAkAudioEventTrack(MatineeAkAudioEventTrack, AkAudioEventTrack); } })); ISequencerModule& SequencerModule = FModuleManager::LoadModuleChecked<ISequencerModule>(TEXT("Sequencer")); #if UE_4_16_OR_LATER RTPCTrackEditorHandle = SequencerModule.RegisterTrackEditor(FOnCreateTrackEditor::CreateStatic(&FMovieSceneAkAudioRTPCTrackEditor::CreateTrackEditor)); EventTrackEditorHandle = SequencerModule.RegisterTrackEditor(FOnCreateTrackEditor::CreateStatic(&FMovieSceneAkAudioEventTrackEditor::CreateTrackEditor)); #else RTPCTrackEditorHandle = SequencerModule.RegisterTrackEditor_Handle(FOnCreateTrackEditor::CreateStatic(&FMovieSceneAkAudioRTPCTrackEditor::CreateTrackEditor)); EventTrackEditorHandle = SequencerModule.RegisterTrackEditor_Handle(FOnCreateTrackEditor::CreateStatic(&FMovieSceneAkAudioEventTrackEditor::CreateTrackEditor)); #endif // UE_4_16_OR_LATER FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>("AssetRegistry"); AssetRegistryModule.Get().OnFilesLoaded().Remove(LateRegistrationOfMatineeToLevelSequencerHandle); } virtual void StartupModule() override { IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get(); AudiokineticAssetCategoryBit = AssetTools.RegisterAdvancedAssetCategory(FName(TEXT("Audiokinetic")), LOCTEXT("AudiokineticAssetCategory", "Audiokinetic")); AkAudioBankAssetTypeActions = MakeShareable( new FAssetTypeActions_AkAudioBank(AudiokineticAssetCategoryBit) ); AssetTools.RegisterAssetTypeActions( AkAudioBankAssetTypeActions.ToSharedRef() ); AkAudioEventAssetTypeActions = MakeShareable(new FAssetTypeActions_AkAudioEvent(AudiokineticAssetCategoryBit)); AssetTools.RegisterAssetTypeActions(AkAudioEventAssetTypeActions.ToSharedRef()); AkAuxBusAssetTypeActions = MakeShareable(new FAssetTypeActions_AkAuxBus(AudiokineticAssetCategoryBit)); AssetTools.RegisterAssetTypeActions(AkAuxBusAssetTypeActions.ToSharedRef()); AkAcousticTextureAssetTypeActions = MakeShareable(new FAssetTypeActions_AkAcousticTexture(AudiokineticAssetCategoryBit)); AssetTools.RegisterAssetTypeActions(AkAcousticTextureAssetTypeActions.ToSharedRef()); if ( FModuleManager::Get().IsModuleLoaded( "LevelEditor" ) ) { // Extend the build menu to handle Audiokinetic-specific entries FLevelEditorModule& LevelEditorModule = FModuleManager::GetModuleChecked<FLevelEditorModule>( TEXT("LevelEditor") ); LevelViewportToolbarBuildMenuExtenderAk = FLevelEditorModule::FLevelEditorMenuExtender::CreateRaw(this, &FAudiokineticToolsModule::ExtendBuildContextMenuForAudiokinetic); LevelEditorModule.GetAllLevelEditorToolbarBuildMenuExtenders().Add(LevelViewportToolbarBuildMenuExtenderAk); LevelViewportToolbarBuildMenuExtenderAkHandle = LevelEditorModule.GetAllLevelEditorToolbarBuildMenuExtenders().Last().GetHandle(); // Add Wwise to the help menu MainMenuExtender = MakeShareable(new FExtender); MainMenuExtender->AddMenuExtension("HelpBrowse", EExtensionHook::After, NULL, FMenuExtensionDelegate::CreateRaw(this, &FAudiokineticToolsModule::AddWwiseHelp)); LevelEditorModule.GetMenuExtensibilityManager()->AddExtender(MainMenuExtender); } RegisterSettings(); AkEventBroker = MakeShareable(new FAkEventAssetBroker); FComponentAssetBrokerage::RegisterBroker(AkEventBroker, UAkComponent::StaticClass(), true, true); UProjectPackagingSettings* PackagingSettings = Cast<UProjectPackagingSettings>(UProjectPackagingSettings::StaticClass()->GetDefaultObject()); FDirectoryPath WwiseAudioPath; WwiseAudioPath.Path = FString(TEXT("WwiseAudio")); int32 i; for(i = 0; i < PackagingSettings->DirectoriesToAlwaysStageAsUFS.Num(); i++) { if(PackagingSettings->DirectoriesToAlwaysStageAsUFS[i].Path == WwiseAudioPath.Path) { break; } } if(i == PackagingSettings->DirectoriesToAlwaysStageAsUFS.Num()) { PackagingSettings->DirectoriesToAlwaysStageAsUFS.Add(WwiseAudioPath); PackagingSettings->UpdateDefaultConfigFile(); } FGlobalTabmanager::Get()->RegisterNomadTabSpawner(SWaapiPicker::WaapiPickerTabName, FOnSpawnTab::CreateRaw(this, &FAudiokineticToolsModule::CreateWaapiPickerWindow)) .SetGroup(WorkspaceMenu::GetMenuStructure().GetLevelEditorCategory()) .SetIcon(FSlateIcon(FAkAudioStyle::GetStyleSetName(), "AudiokineticTools.AkPickerTabIcon")); FGlobalTabmanager::Get()->RegisterNomadTabSpawner(SWwisePicker::WwisePickerTabName, FOnSpawnTab::CreateRaw(this, &FAudiokineticToolsModule::CreateWwisePickerWindow)) .SetGroup(WorkspaceMenu::GetMenuStructure().GetLevelEditorCategory()) .SetIcon(FSlateIcon(FAkAudioStyle::GetStyleSetName(), "AudiokineticTools.AkPickerTabIcon")); FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry")); VerifyAkSettingsHandle = AssetRegistryModule.Get().OnFilesLoaded().AddRaw(this, &FAudiokineticToolsModule::VerifyAkSettings); LateRegistrationOfMatineeToLevelSequencerHandle = AssetRegistryModule.Get().OnFilesLoaded().AddRaw(this, &FAudiokineticToolsModule::LateRegistrationOfMatineeToLevelSequencer); FEditorDelegates::EndPIE.AddRaw(this, &FAudiokineticToolsModule::OnEndPIE); // Since we are initialized in the PostEngineInit phase, our Ambient Sound actor factory is not registered. We need to register it ourselves. if (GEditor) { UActorFactoryAkAmbientSound* NewFactory = NewObject<UActorFactoryAkAmbientSound>(); if (NewFactory) { GEditor->ActorFactories.Add(NewFactory); } } FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor"); PropertyModule.RegisterCustomClassLayout(UAkSurfaceReflectorSetComponent::StaticClass()->GetFName(), FOnGetDetailCustomizationInstance::CreateStatic(&FAkSurfaceReflectorSetDetailsCustomization::MakeInstance)); PropertyModule.RegisterCustomClassLayout(UAkLateReverbComponent::StaticClass()->GetFName(), FOnGetDetailCustomizationInstance::CreateStatic(&FAkLateReverbComponentDetailsCustomization::MakeInstance)); PropertyModule.RegisterCustomClassLayout(UAkRoomComponent::StaticClass()->GetFName(), FOnGetDetailCustomizationInstance::CreateStatic(&FAkRoomComponentDetailsCustomization::MakeInstance)); } virtual void ShutdownModule() override { // Only unregister if the asset tools module is loaded. We don't want to forcibly load it during shutdown phase. check( AkAudioBankAssetTypeActions.IsValid() ); check( AkAudioEventAssetTypeActions.IsValid() ); check( AkAcousticTextureAssetTypeActions.IsValid() ); if( FModuleManager::Get().IsModuleLoaded( "AssetTools" ) ) { FModuleManager::GetModuleChecked< FAssetToolsModule >( "AssetTools" ).Get().UnregisterAssetTypeActions( AkAudioBankAssetTypeActions.ToSharedRef() ); FModuleManager::GetModuleChecked< FAssetToolsModule >( "AssetTools" ).Get().UnregisterAssetTypeActions( AkAudioEventAssetTypeActions.ToSharedRef() ); FModuleManager::GetModuleChecked< FAssetToolsModule >( "AssetTools" ).Get().UnregisterAssetTypeActions( AkAcousticTextureAssetTypeActions.ToSharedRef() ); } AkAudioBankAssetTypeActions.Reset(); AkAudioEventAssetTypeActions.Reset(); AkAcousticTextureAssetTypeActions.Reset(); // Remove Audiokinetic build menu extenders if ( FModuleManager::Get().IsModuleLoaded( "LevelEditor" ) ) { FLevelEditorModule& LevelEditorModule = FModuleManager::GetModuleChecked<FLevelEditorModule>( "LevelEditor" ); LevelEditorModule.GetAllLevelEditorToolbarBuildMenuExtenders().RemoveAll([=](const FLevelEditorModule::FLevelEditorMenuExtender& Extender) { return Extender.GetHandle() == LevelViewportToolbarBuildMenuExtenderAkHandle; }); if (MainMenuExtender.IsValid()) { LevelEditorModule.GetMenuExtensibilityManager()->RemoveExtender(MainMenuExtender); } } if(GUnrealEd != NULL) { GUnrealEd->UnregisterComponentVisualizer(UAkComponent::StaticClass()->GetFName()); } FGlobalTabmanager::Get()->UnregisterTabSpawner("Waapi Picker"); FGlobalTabmanager::Get()->UnregisterTabSpawner("Wwise Picker"); auto MatineeToLevelSequenceModule = FModuleManager::GetModulePtr<IMatineeToLevelSequenceModule>(TEXT("MatineeToLevelSequence")); if (0 && MatineeToLevelSequenceModule) { // Currently, UnregisterTrackConverterForMatineeClass crashes MatineeToLevelSequenceModule->UnregisterTrackConverterForMatineeClass(ConvertMatineeRTPCTrackHandle); MatineeToLevelSequenceModule->UnregisterTrackConverterForMatineeClass(ConvertMatineeEventTrackHandle); } if (FModuleManager::Get().IsModuleLoaded(TEXT("Sequencer"))) { ISequencerModule& SequencerModule = FModuleManager::GetModuleChecked<ISequencerModule>(TEXT("Sequencer")); #if UE_4_16_OR_LATER SequencerModule.UnRegisterTrackEditor(RTPCTrackEditorHandle); SequencerModule.UnRegisterTrackEditor(EventTrackEditorHandle); #else SequencerModule.UnRegisterTrackEditor_Handle(RTPCTrackEditorHandle); SequencerModule.UnRegisterTrackEditor_Handle(EventTrackEditorHandle); #endif // UE_4_16_OR_LATER } FEditorDelegates::EndPIE.RemoveAll(this); // Only found way to close the tab in the case of a hot-reload. We need a pointer to the DockTab, and the only way of getting it seems to be InvokeTab. if (GUnrealEd && !GUnrealEd->IsPendingKill()) { FGlobalTabmanager::Get()->InvokeTab(SWaapiPicker::WaapiPickerTabName)->RequestCloseTab(); FGlobalTabmanager::Get()->InvokeTab(SWwisePicker::WwisePickerTabName)->RequestCloseTab(); } FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(SWaapiPicker::WaapiPickerTabName); FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(SWwisePicker::WwisePickerTabName); if (UObjectInitialized()) { FComponentAssetBrokerage::UnregisterBroker(AkEventBroker); } FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor"); PropertyModule.UnregisterCustomClassLayout(UAkSurfaceReflectorSetComponent::StaticClass()->GetFName()); PropertyModule.UnregisterCustomClassLayout(UAkLateReverbComponent::StaticClass()->GetFName()); PropertyModule.UnregisterCustomClassLayout(UAkRoomComponent::StaticClass()->GetFName()); } /** * Extends the Build context menu with Audiokinetic-specific menu items */ TSharedRef<FExtender> ExtendBuildContextMenuForAudiokinetic(const TSharedRef<FUICommandList> CommandList) { TSharedPtr<FExtender> Extender = MakeShareable(new FExtender); Extender->AddMenuExtension("LevelEditorGeometry", EExtensionHook::After, CommandList, FMenuExtensionDelegate::CreateStatic(&AddGenerateAkBanksToBuildMenu)); return Extender.ToSharedRef(); } private: void RegisterSettings() { if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings")) { SettingsModule->RegisterSettings("Project", "Plugins", "Wwise", LOCTEXT("RuntimeSettingsName", "Wwise"), LOCTEXT("RuntimeSettingsDescription", "Configure the Wwise Integration"), GetMutableDefault<UAkSettings>() ); } } void OnEndPIE(const bool bIsSimulating) { FAkAudioDevice* AkAudioDevice = FAkAudioDevice::Get(); if (AkAudioDevice) { AkAudioDevice->StopAllSounds(true); } } /** Asset type actions for Audiokinetic assets. Cached here so that we can unregister it during shutdown. */ TSharedPtr< FAssetTypeActions_AkAudioBank > AkAudioBankAssetTypeActions; TSharedPtr< FAssetTypeActions_AkAudioEvent > AkAudioEventAssetTypeActions; TSharedPtr< FAssetTypeActions_AkAuxBus > AkAuxBusAssetTypeActions; TSharedPtr< FAssetTypeActions_AkAcousticTexture > AkAcousticTextureAssetTypeActions; TSharedPtr<FExtender> MainMenuExtender; FLevelEditorModule::FLevelEditorMenuExtender LevelViewportToolbarBuildMenuExtenderAk; FDelegateHandle LevelViewportToolbarBuildMenuExtenderAkHandle; FDelegateHandle VerifyAkSettingsHandle; FDelegateHandle LateRegistrationOfMatineeToLevelSequencerHandle; FDelegateHandle RTPCTrackEditorHandle; FDelegateHandle EventTrackEditorHandle; FDelegateHandle ConvertMatineeRTPCTrackHandle; FDelegateHandle ConvertMatineeEventTrackHandle; /** Allow to create an AkComponent when Drag & Drop of an AkEvent */ TSharedPtr<IComponentAssetBroker> AkEventBroker; TSharedPtr<SWaapiPicker> AkWaapiPicker; TSharedPtr<SWwisePicker> AkWwisePicker; }; IMPLEMENT_MODULE( FAudiokineticToolsModule, AudiokineticTools ); void VerifyAkSettings() { UAkSettings* AkSettings = GetMutableDefault<UAkSettings>(); if( AkSettings ) { if (AkSettings->WwiseProjectPath.FilePath.IsEmpty()) { if (!AkSettings->SuppressWwiseProjectPathWarnings) { if (EAppReturnType::Yes == FMessageDialog::Open(EAppMsgType::YesNo, LOCTEXT("SettingsNotSet", "Wwise settings do not seem to be set. Would you like to open the settings window to set them?"))) { FModuleManager::LoadModuleChecked<ISettingsModule>("Settings").ShowViewer(FName("Project"), FName("Plugins"), FName("Wwise")); } } else { UE_LOG(LogAudiokineticTools, Log, TEXT("Wwise project not found. The Ak Pickers will not be usable.")); } } else { // First-time plugin migration: Project might be relative to Engine path. Fix-up the path to make it relative to the game. #if UE_4_18_OR_LATER const auto ProjectDir = FPaths::ProjectDir(); #else const auto ProjectDir = FPaths::GameDir(); #endif // UE_4_18_OR_LATER FString FullGameDir = FPaths::ConvertRelativePathToFull(ProjectDir); FString TempPath = FPaths::ConvertRelativePathToFull(FullGameDir, AkSettings->WwiseProjectPath.FilePath); if (!FPaths::FileExists(TempPath)) { if (!AkSettings->SuppressWwiseProjectPathWarnings) { TSharedPtr<SWindow> Dialog = SNew(SWindow) .Title(LOCTEXT("ResetWwisePath", "Re-set Wwise Path")) .SupportsMaximize(false) .SupportsMinimize(false) .FocusWhenFirstShown(true) .SizingRule(ESizingRule::Autosized); TSharedRef<SWidget> DialogContent = SNew(SVerticalBox) + SVerticalBox::Slot() .FillHeight(0.25f) [ SNew(SSpacer) ] + SVerticalBox::Slot() .AutoHeight() [ SNew(STextBlock) .Text(LOCTEXT("AkUpdateWwisePath", "The Wwise UE4 Integration plug-in's update process requires the Wwise Project Path to be set in the Project Settings dialog. Would you like to open the Project Settings?")) .AutoWrapText(true) ] + SVerticalBox::Slot() .FillHeight(0.75f) [ SNew(SSpacer) ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SCheckBox) .Padding(FMargin(6.0, 2.0)) .OnCheckStateChanged_Lambda([&](ECheckBoxState DontAskState) { AkSettings->SuppressWwiseProjectPathWarnings = (DontAskState == ECheckBoxState::Checked); }) [ SNew(STextBlock) .Text(LOCTEXT("AkDontShowAgain", "Don't show this again")) ] ] + SVerticalBox::Slot() .AutoHeight() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.0f) [ SNew(SSpacer) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(0.0f, 3.0f, 0.0f, 3.0f) [ SNew(SButton) .Text(LOCTEXT("Yes", "Yes")) .OnClicked_Lambda([&]() -> FReply { FModuleManager::LoadModuleChecked<ISettingsModule>("Settings").ShowViewer(FName("Project"), FName("Plugins"), FName("Wwise")); Dialog->RequestDestroyWindow(); AkSettings->UpdateDefaultConfigFile(); return FReply::Handled(); }) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(0.0f, 3.0f, 0.0f, 3.0f) [ SNew(SButton) .Text(LOCTEXT("No", "No")) .OnClicked_Lambda([&]() -> FReply { Dialog->RequestDestroyWindow(); AkSettings->UpdateDefaultConfigFile(); return FReply::Handled(); }) ] ]; Dialog->SetContent(DialogContent); FSlateApplication::Get().AddModalWindow(Dialog.ToSharedRef(), nullptr); } else { UE_LOG(LogAudiokineticTools, Log, TEXT("Wwise project not found. The Ak Pickers will not be usable.")); } } else { FPaths::MakePathRelativeTo(TempPath, *ProjectDir); AkSettings->WwiseProjectPath.FilePath = TempPath; AkSettings->UpdateDefaultConfigFile(); } } } if (GUnrealEd != NULL) { GUnrealEd->RegisterComponentVisualizer(UAkComponent::StaticClass()->GetFName(), MakeShareable(new FAkComponentVisualizer)); GUnrealEd->RegisterComponentVisualizer(UAkSurfaceReflectorSetComponent::StaticClass()->GetFName(), MakeShareable(new FAkSurfaceReflectorSetComponentVisualizer)); } } #undef LOCTEXT_NAMESPACE
/** Initializes the handler, needs to be called before Run(). @param config Pointer to SSEConfig instance. @param server Pointer to SSEServer instance. */ void SSEStatsHandler::Init(SSEConfig* config, SSEServer* server) { _config = config; _server = server; _startTime = time(NULL); }
<reponame>RJSent/stm8_card<filename>src/baseline.h #ifndef BASELINE_H #define BASELINE_H #include <stdint.h> #include "registers.h" #define COUNT_PER_60HZ 670 #define COUNT_PER_1MS 59 /* Oddly not 670 / 16.66 */ #define CLOCK_MEASUREMENT /* Clock used for COUNT_PER measurements */ /* Macro for sizeof array */ /* Be VERY careful with that, as it won't work if the array is > number of useful elements (e.g. has unused elements) */ /* TODO: replace with c_baseline submodule */ #define SIZEOFARRAY(x) (sizeof(x) / sizeof(x[0])) /* TODO: replace with stdbool everywhere */ typedef enum Boolean { FALSE, TRUE } boolean_t; char delay(unsigned long num); char random(); char random_upto(int max); unsigned int math_absolute(int val); /* return absolute value of argument */ int math_mag_decrease(int val, int amount); /* decrease magnitude of val by amount. Returns 0 if |amount| > |val| */ int math_mag_increase(int val, int amount); /* increase magnitude of val by amount. */ int math_mag_set(int val, const unsigned int amount); /* sets magnitude of val to amount while maintaining sign. */ uint8_t reverse_byte(uint8_t byte); char clk_hsi_prescaler(char divider); /* 1, 2, 4, or 8. Both CPU and peripherals */ char clk_cpu_prescaler(unsigned char divider); /* Powers of 2. <= 128. [1, 2, 4, 8, ... 128]*/ #endif
Know your Hallelujahs? Jeff Buckley's version of the song Hallelujah is set to shoot up the singles chart after X Factor winner Alexandra Burke released her own cover. According to midweek sales Buckley's version, from the 1994 album Grace, is set to be number three, but Burke's single will debut at number one. Burke, 20, has already broken the record for the fastest-selling download single in Europe. The original Leonard Cohen version of the song is currently at number 34. If Buckley's cover climbs any higher, this could mean two versions of the same song sitting at number one and number two in the Christmas charts. "I don't think this has ever happened in UK charts history, and certainly not for Christmas," HMV's Gennaro Castaldo said. However, there has been one occasion when four versions of the same song have entered the UK top 40 - but you have to go back to 1955. On 20 June, 1955 Al Hibbler, The Les Baxter Orchestra, Jimmy Young and Liberace all scored a hit with Unchained Melody, with Young's version topping the chart. Buckley fans unite Burke, who was crowned the X Factor winner on Saturday, has shifted 149,546 copies of her single so far this week. Alexandra Burke was crowned the X Factor winner on Saturday She is beating another X Factor winner Leona Lewis into second place. Lewis' cover of Snow Patrol's Run is the current number one single. However, fans of Buckley - who died in 1997 at the age of 30 - have united online in various groups and forums in a bid to get their icon to number one this Christmas. The physical CD single of Burke's version of the song will be available in the shops from Wednesday. The song itself, which was originally released in 1984, has been covered more than 170 times. Artists such as John Cale, Bono and Rufus Wainwright have all sung the track. Bookmark with: Delicious Digg reddit Facebook StumbleUpon What are these? E-mail this to a friend Printable version
<filename>test/sha256.h #include "emp-sh2pc/emp-sh2pc.h" using namespace emp; const int BITS = 32; /* implementation of SHA256 from FIPS PUB 180-4 * with the following modifications * - processes only a fixed length input. We've hardcoded it for 1, 2, or 3 blocks * - assumes padding already exists */ #define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z))) #define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #define SHR32(x, n) ((x) >> (n)) #define SIGMA_UPPER_0(x) (ROR32(x, 2) ^ ROR32(x, 13) ^ ROR32(x, 22)) #define SIGMA_UPPER_1(x) (ROR32(x, 6) ^ ROR32(x, 11) ^ ROR32(x, 25)) #define SIGMA_LOWER_0(x) (ROR32(x, 7) ^ ROR32(x, 18) ^ SHR32(x, 3)) #define SIGMA_LOWER_1(x) (ROR32(x, 17) ^ ROR32(x, 19) ^ SHR32(x, 10)) Integer ROR32(Integer x, Integer n); Integer ROR32(Integer x, uint n); uint ROR32(uint x, uint n); /* FIPS PUB 180-4 -- 4.2.2 * * "These words represent the first thirty-two bits of the fractional parts of * the cube roots of the first sixty-four prime numbers" */ static const uint32_t k_clear[64] = { 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 }; /* FIPS PUB 180-4 -- 5.3.3 * * Initial hash value * "These words were obtained by taking the first thirty-two bits of the fractional parts of the * square roots of the first eight prime numbers" */ static const uint32_t IV_clear[8] = { 0x6A09E667 , 0xBB67AE85 , 0x3C6EF372 , 0xA54FF53A , 0x510E527F , 0x9B05688C , 0x1F83D9AB , 0x5BE0CD19 }; void initSHA256(Integer k[64], Integer H[8]); string get_bitstring(Integer x); Integer composeSHA256result(Integer result[8]); /* computes sha256 for a 2-block message * output is stored in result * composed of 8 32-bit Integers such that * sha256(message) = result[0] || result[1] || ... || result[7] */ void computeSHA256_2l(uint message[2][16], Integer result[8]); /* computes sha256 for a 2-block message * output is stored in result * composed of 8 32-bit Integers such that * sha256(message) = result[0] || result[1] || ... || result[7] * this takes already distributed variables. */ void computeSHA256_1d(Integer message[1][16], Integer result[8]); void computeSHA256_2d(Integer message[2][16], Integer result[8]); void computeSHA256_3d(Integer message[3][16], Integer result[8]);