repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
wantnon2/c3dEngine2
c3dEngine2/demos/app_superSingleCell/projcode/gameObjs/sprite.cpp
// // sprite.cpp // HelloOpenGL // // Created by wantnon (<NAME>) on 12-12-22. // // #include "sprite.h"
sathishmscict/scrimage
scrimage-core/src/main/scala/com/sksamuel/scrimage/canvas/drawable/Polyline.scala
package com.sksamuel.scrimage.canvas.drawable import java.awt.Graphics2D import com.sksamuel.scrimage.canvas.{Context, Drawable} case class Polyline(points: Seq[Point], configure: Graphics2D => Unit = g2 => ()) extends Drawable { def draw(g: Graphics2D): Unit = g.drawPolyline(points.map(_.x).toArray, points.map(_.y).toArray, points.size) def close: Polygon = Polygon(points, configure) } object Polyline { def apply(points: Seq[Point], context: Context): Polyline = Polyline(points, context.toFn) }
Sendiradid/island.is
apps/air-discount-scheme/backend/migrations/20210428140700-fix-customer-record.js
<filename>apps/air-discount-scheme/backend/migrations/20210428140700-fix-customer-record.js 'use strict' module.exports = { up: (queryInterface) => { return queryInterface.sequelize.query(` BEGIN; /* fix wrong customer entry AEY RKV*/ UPDATE flight_leg SET date = '2021-04-29T12:45:00.000Z' WHERE id = 'd809e68a-2ce0-4249-928c-aac2cd939a0f'; /* fix wrong customer entry RKV AEY*/ UPDATE flight_leg SET date = '2021-05-02T14:20:00.000Z' WHERE id = '556cd4bc-e49b-43ba-bbc9-3659ad7c61eb'; COMMIT; `) }, down: (queryInterface) => { return queryInterface.sequelize.query(` BEGIN; /* unfix wrong customer entry AEY RKV*/ UPDATE flight_leg SET date = '2021-04-26T19:53:49.605Z' WHERE id = 'd809e68a-2ce0-4249-928c-aac2cd939a0f'; /* unfix wrong customer entry AEY RKV*/ UPDATE flight_leg SET date = '2021-04-26T19:53:49.605Z' WHERE id = '556cd4bc-e49b-43ba-bbc9-3659ad7c61eb'; COMMIT; `) }, }
xDamneDx/Epic-React
bookshelf/scripts/swap.js
const fs = require('fs') const inquirer = require('inquirer') const {spawnSync, getVariants, getExtraCreditTitles} = require('./utils') const branch = spawnSync('git rev-parse --abbrev-ref HEAD') if (branch === 'main') { throw new Error('Cannot run swap on main as there are no exercises.') } go() async function go() { let {2: match} = process.argv const allowedTypes = [/^exercise$/, /^final$/, /^\d+$/] const variants = getVariants() const maxExtra = Math.max( ...Object.values(variants) .reduce((m, v) => [...m, ...v.extras], []) .map(e => e.number), ) if (!Object.keys(variants).length) { console.log(`There are no variants needing a swap.`) return } const extraCreditTitles = getExtraCreditTitles() if (!match) { const prompt = await inquirer.prompt([ { name: 'matchVal', message: `Which modules do you want loaded?`, type: 'list', choices: [ {name: 'Exercise', value: 'exercise'}, {name: 'Final', value: 'final'}, ...Array.from({length: maxExtra}, (v, i) => ({ name: `Extra Credit ${i + 1}: ${extraCreditTitles[i]}`, value: i + 1, })), ], }, ]) match = prompt.matchVal } if (!allowedTypes.some(t => t.test(match))) { throw new Error( `The given match of "${match}" is not one of the allowed types of: ${allowedTypes.join( ', ', )}`, ) } console.log(`Changing used files to those matching "${match}"`) function getmainFileContents({main, exercise, final, extras}) { let uncommentedLines if (match === 'exercise') { uncommentedLines = exercise.exportLines } else if (match === 'final') { uncommentedLines = final ? final.exportLines : exercise.exportLines } else if (Number.isFinite(Number(match))) { const availableECs = extras .map(e => e.number) .filter(n => n <= Number(match)) const maxEC = Math.max(...availableECs) const maxExtra = extras.find(e => e.number === maxEC) uncommentedLines = (maxExtra || final || exercise).exportLines } else { console.log('this should not happen...', match) } if (!uncommentedLines) { throw new Error(`No variant found to enable for "${match}" in "${main}"`) } const l = lines => lines ? lines === uncommentedLines ? lines.join('\n') : `// ${lines.join('\n// ')}` : '' const extrasLines = extras .map( ({exportLines, title}) => `// 💯 ${title}\n${l(exportLines) || '// no extra credit'}`, ) .join('\n\n') return ( ` ${l((final || {}).exportLines) || '// no final'} ${l(exercise.exportLines) || '// no exercise'} ${extrasLines} `.trim() + '\n' ) } for (const [main, {final, exercise, extras}] of Object.entries(variants)) { const contents = getmainFileContents({main, final, exercise, extras}) fs.writeFileSync(main, contents) } }
gitskarios/Gitskarios
app/src/main/java/com/alorma/github/sdk/bean/dto/response/search/UsersSearch.java
package com.alorma.github.sdk.bean.dto.response.search; import core.User; import java.util.List; public class UsersSearch extends SearchBase { public List<User> items; public UsersSearch() { } }
jaylinjiehong/NumberOfPasses
Android/android-30/android30_code_view/src/com/company/source/com/android/internal/telephony/RadioConfig.java
<filename>Android/android-30/android30_code_view/src/com/company/source/com/android/internal/telephony/RadioConfig.java /* * Copyright (C) 2018 The Android Open Source Project * * 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.android.internal.telephony; import static com.android.internal.telephony.RILConstants.RADIO_NOT_AVAILABLE; import static com.android.internal.telephony.RILConstants.REQUEST_NOT_SUPPORTED; import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_PHONE_CAPABILITY; import static com.android.internal.telephony.RILConstants.RIL_REQUEST_GET_SLOT_STATUS; import static com.android.internal.telephony.RILConstants .RIL_REQUEST_SET_LOGICAL_TO_PHYSICAL_SLOT_MAPPING; import static com.android.internal.telephony.RILConstants.RIL_REQUEST_SET_PREFERRED_DATA_MODEM; import static com.android.internal.telephony.RILConstants.RIL_REQUEST_SWITCH_DUAL_SIM_CONFIG; import android.content.Context; import android.hardware.radio.V1_0.RadioResponseInfo; import android.hardware.radio.V1_0.RadioResponseType; import android.hardware.radio.config.V1_0.IRadioConfig; import android.hardware.radio.config.V1_1.ModemsConfig; import android.net.ConnectivityManager; import android.os.AsyncResult; import android.os.Handler; import android.os.HwBinder; import android.os.Message; import android.os.Registrant; import android.os.RemoteException; import android.os.WorkSource; import android.util.SparseArray; import com.android.internal.telephony.uicc.IccSlotStatus; import com.android.telephony.Rlog; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicLong; /** * This class provides wrapper APIs for IRadioConfig interface. */ public class RadioConfig extends Handler { private static final String TAG = "RadioConfig"; private static final boolean DBG = true; private static final boolean VDBG = false; //STOPSHIP if true private static final int EVENT_SERVICE_DEAD = 1; private static final HalVersion RADIO_CONFIG_HAL_VERSION_UNKNOWN = new HalVersion(-1, -1); private static final HalVersion RADIO_CONFIG_HAL_VERSION_1_0 = new HalVersion(1, 0); private static final HalVersion RADIO_CONFIG_HAL_VERSION_1_1 = new HalVersion(1, 1); private final boolean mIsMobileNetworkSupported; private volatile IRadioConfig mRadioConfigProxy = null; // IRadioConfig version private HalVersion mRadioConfigVersion = RADIO_CONFIG_HAL_VERSION_UNKNOWN; private final ServiceDeathRecipient mServiceDeathRecipient; private final AtomicLong mRadioConfigProxyCookie = new AtomicLong(0); private final RadioConfigResponse mRadioConfigResponse; private final RadioConfigIndication mRadioConfigIndication; private final SparseArray<RILRequest> mRequestList = new SparseArray<RILRequest>(); /* default work source which will blame phone process */ private final WorkSource mDefaultWorkSource; private static RadioConfig sRadioConfig; protected Registrant mSimSlotStatusRegistrant; final class ServiceDeathRecipient implements HwBinder.DeathRecipient { @Override public void serviceDied(long cookie) { // Deal with service going away logd("serviceDied"); sendMessage(obtainMessage(EVENT_SERVICE_DEAD, cookie)); } } private RadioConfig(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE); mIsMobileNetworkSupported = cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE); mRadioConfigResponse = new RadioConfigResponse(this); mRadioConfigIndication = new RadioConfigIndication(this); mServiceDeathRecipient = new ServiceDeathRecipient(); mDefaultWorkSource = new WorkSource(context.getApplicationInfo().uid, context.getPackageName()); } /** * Returns the singleton static instance of RadioConfig */ public static RadioConfig getInstance(Context context) { if (sRadioConfig == null) { sRadioConfig = new RadioConfig(context); } return sRadioConfig; } @Override public void handleMessage(Message message) { switch (message.what) { case EVENT_SERVICE_DEAD: logd("handleMessage: EVENT_SERVICE_DEAD cookie = " + message.obj + " mRadioConfigProxyCookie = " + mRadioConfigProxyCookie.get()); if ((long) message.obj == mRadioConfigProxyCookie.get()) { resetProxyAndRequestList("EVENT_SERVICE_DEAD", null); } break; } } /** * Release each request in mRequestList then clear the list * @param error is the RIL_Errno sent back * @param loggable true means to print all requests in mRequestList */ private void clearRequestList(int error, boolean loggable) { RILRequest rr; synchronized (mRequestList) { int count = mRequestList.size(); if (DBG && loggable) { logd("clearRequestList: mRequestList=" + count); } for (int i = 0; i < count; i++) { rr = mRequestList.valueAt(i); if (DBG && loggable) { logd(i + ": [" + rr.mSerial + "] " + requestToString(rr.mRequest)); } rr.onError(error, null); rr.release(); } mRequestList.clear(); } } private void resetProxyAndRequestList(String caller, Exception e) { loge(caller + ": " + e); mRadioConfigProxy = null; // increment the cookie so that death notification can be ignored mRadioConfigProxyCookie.incrementAndGet(); RILRequest.resetSerial(); // Clear request list on close clearRequestList(RADIO_NOT_AVAILABLE, false); getRadioConfigProxy(null); } /** Returns a {@link IRadioConfig} instance or null if the service is not available. */ public IRadioConfig getRadioConfigProxy(Message result) { if (!mIsMobileNetworkSupported) { if (VDBG) logd("getRadioConfigProxy: Not calling getService(): wifi-only"); if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(RADIO_NOT_AVAILABLE)); result.sendToTarget(); } return null; } if (mRadioConfigProxy != null) { return mRadioConfigProxy; } updateRadioConfigProxy(); if (mRadioConfigProxy == null) { if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(RADIO_NOT_AVAILABLE)); result.sendToTarget(); } } return mRadioConfigProxy; } private void updateRadioConfigProxy() { try { // Try to get service from different versions. try { mRadioConfigProxy = android.hardware.radio.config.V1_1.IRadioConfig.getService( true); mRadioConfigVersion = RADIO_CONFIG_HAL_VERSION_1_1; } catch (NoSuchElementException e) { } if (mRadioConfigProxy == null) { try { mRadioConfigProxy = android.hardware.radio.config.V1_0 .IRadioConfig.getService(true); mRadioConfigVersion = RADIO_CONFIG_HAL_VERSION_1_0; } catch (NoSuchElementException e) { } } if (mRadioConfigProxy == null) { loge("getRadioConfigProxy: mRadioConfigProxy == null"); return; } // Link to death recipient and set response. If fails, set proxy to null and return. mRadioConfigProxy.linkToDeath(mServiceDeathRecipient, mRadioConfigProxyCookie.incrementAndGet()); mRadioConfigProxy.setResponseFunctions(mRadioConfigResponse, mRadioConfigIndication); } catch (RemoteException | RuntimeException e) { mRadioConfigProxy = null; loge("getRadioConfigProxy: RadioConfigProxy setResponseFunctions: " + e); return; } } private RILRequest obtainRequest(int request, Message result, WorkSource workSource) { RILRequest rr = RILRequest.obtain(request, result, workSource); synchronized (mRequestList) { mRequestList.append(rr.mSerial, rr); } return rr; } private RILRequest findAndRemoveRequestFromList(int serial) { RILRequest rr; synchronized (mRequestList) { rr = mRequestList.get(serial); if (rr != null) { mRequestList.remove(serial); } } return rr; } /** * This is a helper function to be called when a RadioConfigResponse callback is called. * It finds and returns RILRequest corresponding to the response if one is found. * @param responseInfo RadioResponseInfo received in response callback * @return RILRequest corresponding to the response */ public RILRequest processResponse(RadioResponseInfo responseInfo) { int serial = responseInfo.serial; int error = responseInfo.error; int type = responseInfo.type; if (type != RadioResponseType.SOLICITED) { loge("processResponse: Unexpected response type " + type); } RILRequest rr = findAndRemoveRequestFromList(serial); if (rr == null) { loge("processResponse: Unexpected response! serial: " + serial + " error: " + error); return null; } return rr; } /** * Wrapper function for IRadioConfig.getSimSlotsStatus(). */ public void getSimSlotsStatus(Message result) { IRadioConfig radioConfigProxy = getRadioConfigProxy(result); if (radioConfigProxy != null) { RILRequest rr = obtainRequest(RIL_REQUEST_GET_SLOT_STATUS, result, mDefaultWorkSource); if (DBG) { logd(rr.serialString() + "> " + requestToString(rr.mRequest)); } try { radioConfigProxy.getSimSlotsStatus(rr.mSerial); } catch (RemoteException | RuntimeException e) { resetProxyAndRequestList("getSimSlotsStatus", e); } } } /** * Wrapper function for IRadioConfig.setPreferredDataModem(int modemId). */ public void setPreferredDataModem(int modemId, Message result) { if (!isSetPreferredDataCommandSupported()) { if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(REQUEST_NOT_SUPPORTED)); result.sendToTarget(); } return; } RILRequest rr = obtainRequest(RIL_REQUEST_SET_PREFERRED_DATA_MODEM, result, mDefaultWorkSource); if (DBG) { logd(rr.serialString() + "> " + requestToString(rr.mRequest)); } try { ((android.hardware.radio.config.V1_1.IRadioConfig) mRadioConfigProxy) .setPreferredDataModem(rr.mSerial, (byte) modemId); } catch (RemoteException | RuntimeException e) { resetProxyAndRequestList("setPreferredDataModem", e); } } /** * Wrapper function for IRadioConfig.getPhoneCapability(). */ public void getPhoneCapability(Message result) { IRadioConfig radioConfigProxy = getRadioConfigProxy(null); if (radioConfigProxy == null || mRadioConfigVersion.less(RADIO_CONFIG_HAL_VERSION_1_1)) { if (result != null) { AsyncResult.forMessage(result, null, CommandException.fromRilErrno(REQUEST_NOT_SUPPORTED)); result.sendToTarget(); } return; } RILRequest rr = obtainRequest(RIL_REQUEST_GET_PHONE_CAPABILITY, result, mDefaultWorkSource); if (DBG) { logd(rr.serialString() + "> " + requestToString(rr.mRequest)); } try { ((android.hardware.radio.config.V1_1.IRadioConfig) mRadioConfigProxy) .getPhoneCapability(rr.mSerial); } catch (RemoteException | RuntimeException e) { resetProxyAndRequestList("getPhoneCapability", e); } } /** * @return whether current radio config version supports SET_PREFERRED_DATA_MODEM command. * If yes, we'll use RIL_REQUEST_SET_PREFERRED_DATA_MODEM to indicate which modem is preferred. * If not, we shall use RIL_REQUEST_ALLOW_DATA for on-demand PS attach / detach. * See PhoneSwitcher for more details. */ public boolean isSetPreferredDataCommandSupported() { IRadioConfig radioConfigProxy = getRadioConfigProxy(null); return radioConfigProxy != null && mRadioConfigVersion .greaterOrEqual(RADIO_CONFIG_HAL_VERSION_1_1); } /** * Wrapper function for IRadioConfig.setSimSlotsMapping(int32_t serial, vec<uint32_t> slotMap). */ public void setSimSlotsMapping(int[] physicalSlots, Message result) { IRadioConfig radioConfigProxy = getRadioConfigProxy(result); if (radioConfigProxy != null) { RILRequest rr = obtainRequest(RIL_REQUEST_SET_LOGICAL_TO_PHYSICAL_SLOT_MAPPING, result, mDefaultWorkSource); if (DBG) { logd(rr.serialString() + "> " + requestToString(rr.mRequest) + " " + Arrays.toString(physicalSlots)); } try { radioConfigProxy.setSimSlotsMapping(rr.mSerial, primitiveArrayToArrayList(physicalSlots)); } catch (RemoteException | RuntimeException e) { resetProxyAndRequestList("setSimSlotsMapping", e); } } } private static ArrayList<Integer> primitiveArrayToArrayList(int[] arr) { ArrayList<Integer> arrayList = new ArrayList<>(arr.length); for (int i : arr) { arrayList.add(i); } return arrayList; } static String requestToString(int request) { switch (request) { case RIL_REQUEST_GET_PHONE_CAPABILITY: return "GET_PHONE_CAPABILITY"; case RIL_REQUEST_GET_SLOT_STATUS: return "GET_SLOT_STATUS"; case RIL_REQUEST_SET_LOGICAL_TO_PHYSICAL_SLOT_MAPPING: return "SET_LOGICAL_TO_PHYSICAL_SLOT_MAPPING"; case RIL_REQUEST_SET_PREFERRED_DATA_MODEM: return "SET_PREFERRED_DATA_MODEM"; case RIL_REQUEST_SWITCH_DUAL_SIM_CONFIG: return "SWITCH_DUAL_SIM_CONFIG"; default: return "<unknown request " + request + ">"; } } /** * Wrapper function for using IRadioConfig.setModemsConfig(int32_t serial, * ModemsConfig modemsConfig) to switch between single-sim and multi-sim. */ public void setModemsConfig(int numOfLiveModems, Message result) { IRadioConfig radioConfigProxy = getRadioConfigProxy(result); if (radioConfigProxy != null && mRadioConfigVersion.greaterOrEqual(RADIO_CONFIG_HAL_VERSION_1_1)) { android.hardware.radio.config.V1_1.IRadioConfig radioConfigProxy11 = (android.hardware.radio.config.V1_1.IRadioConfig) radioConfigProxy; RILRequest rr = obtainRequest(RIL_REQUEST_SWITCH_DUAL_SIM_CONFIG, result, mDefaultWorkSource); if (DBG) { logd(rr.serialString() + "> " + requestToString(rr.mRequest) + ", numOfLiveModems = " + numOfLiveModems); } try { ModemsConfig modemsConfig = new ModemsConfig(); modemsConfig.numOfLiveModems = (byte) numOfLiveModems; radioConfigProxy11.setModemsConfig(rr.mSerial, modemsConfig); } catch (RemoteException | RuntimeException e) { resetProxyAndRequestList("setModemsConfig", e); } } } // TODO: not needed for now, but if we don't want to use System Properties any more, // we need to implement a wrapper function for getModemsConfig as well /** * Register a handler to get SIM slot status changed notifications. */ public void registerForSimSlotStatusChanged(Handler h, int what, Object obj) { mSimSlotStatusRegistrant = new Registrant(h, what, obj); } /** * Unregister corresponding to registerForSimSlotStatusChanged(). */ public void unregisterForSimSlotStatusChanged(Handler h) { if (mSimSlotStatusRegistrant != null && mSimSlotStatusRegistrant.getHandler() == h) { mSimSlotStatusRegistrant.clear(); mSimSlotStatusRegistrant = null; } } static ArrayList<IccSlotStatus> convertHalSlotStatus( ArrayList<android.hardware.radio.config.V1_0.SimSlotStatus> halSlotStatusList) { ArrayList<IccSlotStatus> response = new ArrayList<IccSlotStatus>(halSlotStatusList.size()); for (android.hardware.radio.config.V1_0.SimSlotStatus slotStatus : halSlotStatusList) { IccSlotStatus iccSlotStatus = new IccSlotStatus(); iccSlotStatus.setCardState(slotStatus.cardState); iccSlotStatus.setSlotState(slotStatus.slotState); iccSlotStatus.logicalSlotIndex = slotStatus.logicalSlotId; iccSlotStatus.atr = slotStatus.atr; iccSlotStatus.iccid = slotStatus.iccid; response.add(iccSlotStatus); } return response; } static ArrayList<IccSlotStatus> convertHalSlotStatus_1_2( ArrayList<android.hardware.radio.config.V1_2.SimSlotStatus> halSlotStatusList) { ArrayList<IccSlotStatus> response = new ArrayList<IccSlotStatus>(halSlotStatusList.size()); for (android.hardware.radio.config.V1_2.SimSlotStatus slotStatus : halSlotStatusList) { IccSlotStatus iccSlotStatus = new IccSlotStatus(); iccSlotStatus.setCardState(slotStatus.base.cardState); iccSlotStatus.setSlotState(slotStatus.base.slotState); iccSlotStatus.logicalSlotIndex = slotStatus.base.logicalSlotId; iccSlotStatus.atr = slotStatus.base.atr; iccSlotStatus.iccid = slotStatus.base.iccid; iccSlotStatus.eid = slotStatus.eid; response.add(iccSlotStatus); } return response; } private static void logd(String log) { Rlog.d(TAG, log); } private static void loge(String log) { Rlog.e(TAG, log); } }
zhangkn/iOS14Header
usr/lib/libcoreroutine.dylib/RTStoredLocationOfInterestEnumerationOptions.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:52:36 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /usr/lib/libcoreroutine.dylib * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <libcoreroutine.dylib/libcoreroutine.dylib-Structs.h> #import <libobjc.A.dylib/NSCopying.h> @class NSDateInterval; @interface RTStoredLocationOfInterestEnumerationOptions : NSObject <NSCopying> { BOOL _ascendingVisitEntryDate; BOOL _singleVisit; unsigned long long _batchSize; NSDateInterval* _dateInterval; } @property (nonatomic,readonly) BOOL ascendingVisitEntryDate; //@synthesize ascendingVisitEntryDate=_ascendingVisitEntryDate - In the implementation block @property (nonatomic,readonly) unsigned long long batchSize; //@synthesize batchSize=_batchSize - In the implementation block @property (nonatomic,copy,readonly) NSDateInterval * dateInterval; //@synthesize dateInterval=_dateInterval - In the implementation block @property (nonatomic,readonly) BOOL singleVisit; //@synthesize singleVisit=_singleVisit - In the implementation block -(id)copyWithZone:(NSZone*)arg1 ; -(NSDateInterval *)dateInterval; -(id)init; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)batchSize; -(unsigned long long)hash; -(id)initWithAscendingVisitEntryDate:(BOOL)arg1 batchSize:(unsigned long long)arg2 dateInterval:(id)arg3 singleVisit:(BOOL)arg4 ; -(BOOL)singleVisit; -(BOOL)ascendingVisitEntryDate; @end
hclsampleapps/kandy-cpaas2-sample-ios-oc
kandy-cpaas2-sample-ios-oc/Dashboard/DashboardTypeCustomCollectionCell.h
#import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface DashboardTypeCustomCollectionCell : UICollectionViewCell @property(nonatomic, weak) IBOutlet UILabel *lblName; @property(nonatomic, weak) IBOutlet UIImageView *imgBg; @property(nonatomic, weak) IBOutlet UIImageView *imgPreview1; -(void)displayContentwithImage : (UIImage*)image andTitle : (NSString*)title; @end NS_ASSUME_NONNULL_END
qq573011406/FASTBuild_UnrealEngine
Code/Tools/FBuild/FBuildTest/Data/TestPrecompiledHeaders/Deoptimization/PrecompiledHeader.h
#ifndef PCH_INCLUDED #define PCH_INCLUDED // A define which is not used within the PCH, but should still uniquify the output // because files compiled using the PCH might rely on the define #define SPECIAL_DEFINE 1 #endif // PCH_INCLUDED
LJLintermittent/leetcode
src/test/java/com/learn/leetcode/test/TestLC557.java
package com.learn.leetcode.test; /** * Description: * date: 2021/7/23 9:46 * Package: com.learn.leetcode.test * * @author 李佳乐 * @email <EMAIL> */ @SuppressWarnings("all") public class TestLC557 { public static void main(String[] args) { String s = " acd lijiale haha"; String ans = reverseWords(s); System.out.println(ans); } /** * 反转字符串中的每一个单词3 */ public static String reverseWords(String s) { int len = s.length(); StringBuilder stringBuilder = new StringBuilder(); int i = 0; while (i < len) { int start = i; while (i < len && s.charAt(i) != ' ') { i++; } for (int m = start; m < i; m++) { stringBuilder.append(s.charAt(start + i - 1 - m)); } while (i < len && s.charAt(i) == ' ') { i++; stringBuilder.append(' '); } } return stringBuilder.toString(); } }
Miguel-David/1KSegundaEvaluacion
src/ExplicacionSwing/PanelSueldo.java
package ExplicacionSwing; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class PanelSueldo{ private JTextField sueldo; private JTextField salario; private JTextField nombre; private JTextField horas; private JPanel panel; public PanelSueldo(){ inicializar(); } public JPanel getPanel() { return panel; } public String getNombre() { return nombre.getText(); } private void inicializar() { panel=new JPanel(); panel.setBorder(new EmptyBorder(10,10,10,10)); panel.setLayout(new GridBagLayout()); JLabel etiquetaNombre=new JLabel("Nombre del empleado"); JLabel etiquetaSueldo=new JLabel("Salario Básico/Hora"); nombre=new JTextField(20); sueldo=new JTextField(15); anyadeComponente(panel,etiquetaNombre,0,0,2,1); anyadeComponente(panel,etiquetaSueldo,2,0,1,1); anyadeComponente(panel,nombre,0,1,2,1); anyadeComponente(panel,sueldo,2,1,1,1); JLabel etiquetaHoras=new JLabel("Horas Trabajadas:"); JLabel etiquetaSalario=new JLabel("Salario Mensual"); anyadeComponente(panel,etiquetaHoras,0,2,1,1); anyadeComponente(panel,etiquetaSalario,2,2,1,1); horas=new JTextField(10); JButton calcular=new JButton("Calcular"); salario=new JTextField(5); anyadeComponente(panel,horas,0,3,1,1); anyadeComponente(panel,calcular,1,3,1,1); anyadeComponente(panel,salario,2,3,1,1); //Calcular calcular.addActionListener(e->hazCalculo()); } private void hazCalculo() { int perras=Integer.parseInt(sueldo.getText()); int tiempo=Integer.parseInt(horas.getText()); String nombreCadena=nombre.getText(); salario.setText(""+perras*tiempo); JOptionPane.showMessageDialog(null,nombreCadena+", tu salario es €:"+perras*tiempo); } public static void anyadeComponente( JPanel panel, Component componente, int posx, int posy, int anchox, int anchoy){ GridBagConstraints c=new GridBagConstraints(); c.gridx=posx; c.gridy=posy; c.gridwidth=anchox; c.gridheight=anchoy; panel.add(componente,c); } public static void main(String[] args) { JFrame ventana=new JFrame("Cálculo de Sueldo"); ventana.setLayout(new GridLayout(2,2)); PanelSueldo panelSueldo=new PanelSueldo(); PanelSueldo panelSueldo1=new PanelSueldo(); PanelSueldo panelSueldo2=new PanelSueldo(); PanelSueldo panelSueldo3=new PanelSueldo(); ventana.add(panelSueldo.panel); ventana.add(panelSueldo1.panel); ventana.add(panelSueldo2.panel); ventana.add(panelSueldo3.panel); ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ventana.pack(); ventana.setLocationRelativeTo(null); ventana.setVisible(true); } }
tiagoeborsanyi/festival-app
client/src/store/actions/auth.js
import axios from 'axios'; import * as actionTypes from './actionTypes'; export const authStart = () => { return { type: actionTypes.AUTH_START }; }; export const authSuccess = (token, userId, admin = false) => { return { type: actionTypes.AUTH_SUCCESS, token: token, userId: userId, admin: admin }; }; export const authFail = (error) => { return { type: actionTypes.AUTH_FAIL, error }; }; export const logout = () => { localStorage.removeItem('token'); localStorage.removeItem('expirationDate'); localStorage.removeItem('userId'); localStorage.removeItem('admin'); localStorage.removeItem('name'); return { type: actionTypes.AUTH_LOGOUT } }; export const checkAuthTimeout = (expirationTime) => dispatch => { setTimeout(() => { dispatch(logout()); }, expirationTime * 1000); }; export const auth = (email, pass) => async dispatch => { dispatch(authStart()); const authData = { email, password: <PASSWORD>}; let url = `/api/users/login`; try { const response = await axios.post(url, authData); console.log(response) if (response) { const { token, expiresIn, localId, admin } = response.data; const expirationDate = new Date(new Date().getTime() + expiresIn * 1000); localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); localStorage.setItem('userId', localId); localStorage.setItem('admin', response.data.admin); localStorage.setItem('name', response.data.name); dispatch(authSuccess(token, localId, admin)); dispatch(checkAuthTimeout(expiresIn)); } } catch (error) { dispatch(authFail(error.response.data)); } } export const setAuthRedirectPath = (path) => { return { type: actionTypes.SET_AUTH_REDIRECT_PATH, path } } export const authCheckState = () => dispatch => { const token = localStorage.getItem('token'); if (!token) { dispatch(logout()); } else { const expirationDate = new Date(localStorage.getItem('expirationDate')); if (expirationDate <= new Date()) { dispatch(logout()); } else { const userId = localStorage.getItem('userId'); const admin = localStorage.getItem('admin'); dispatch(authSuccess(token, userId, admin)); dispatch(checkAuthTimeout((expirationDate.getTime() - new Date().getTime()) / 1000)); } } }
kamranghiasvand/wedding-auth-server
src/main/java/com/bluebox/security/authenticationserver/persistence/service/sms/meliPayment/dto/MeliPaymentResp.java
package com.bluebox.security.authenticationserver.persistence.service.sms.meliPayment.dto; import lombok.Getter; import lombok.Setter; /** * @author by <NAME> */ @Getter @Setter public class MeliPaymentResp { private String value; private int retStatus; private String strRetStatus; }
code-forger/PyPal
src/actuator/impulse.cpp
<gh_stars>0 #include "../globals.h" extern "C" { void actuator_impulse_apply(palImpulseActuator* i) { i->Apply(); } void actuator_impulse_set_impulse(palImpulseActuator* i, float impulse) { i->SetImpulse(impulse); } palImpulseActuator* actuator_impulse_create(palBody* pb, Float x, Float y, Float z, Float ax, Float ay, Float az) { palImpulseActuator*pia = dynamic_cast<palImpulseActuator*>(PF->CreateObject("palImpulseActuator")); pia->Init(pb,x,y,z,ax,ay,az); return pia; } }
flber/df
hack/ruby/plant.rb
module DFHack class << self # return a Plant # arg similar to unit.rb/unit_find, no menu def plant_find(what=cursor) if what.kind_of?(Integer) world.items.all.binsearch(what) elsif what.respond_to?(:x) or what.respond_to?(:pos) world.plants.all.find { |p| same_pos?(what, p) } else raise "what what?" end end def each_tree(material=:any) @raws_tree_name ||= {} if @raws_tree_name.empty? df.world.raws.plants.all.each_with_index { |p, idx| @raws_tree_name[idx] = p.id if p.flags[:TREE] } end if material != :any mat = match_rawname(material, @raws_tree_name.values) unless wantmat = @raws_tree_name.index(mat) raise "invalid tree material #{material}" end end world.plants.all.each { |plant| next if not @raws_tree_name[plant.material] next if wantmat and plant.material != wantmat yield plant } end def each_shrub(material=:any) @raws_shrub_name ||= {} if @raws_tree_name.empty? df.world.raws.plants.all.each_with_index { |p, idx| @raws_shrub_name[idx] = p.id if not p.flags[:GRASS] and not p.flags[:TREE] } end if material != :any mat = match_rawname(material, @raws_shrub_name.values) unless wantmat = @raws_shrub_name.index(mat) raise "invalid shrub material #{material}" end end end SaplingToTreeAge = 120960 def cuttrees(material=nil, count_max=100, quiet=false) if !material # list trees cnt = Hash.new(0) each_tree { |plant| next if plant.grow_counter < SaplingToTreeAge next if map_designation_at(plant).hidden cnt[plant.material] += 1 } cnt.sort_by { |mat, c| c }.each { |mat, c| name = @raws_tree_name[mat] puts " #{name} #{c}" unless quiet } else cnt = 0 each_tree(material) { |plant| next if plant.grow_counter < SaplingToTreeAge b = map_block_at(plant) d = b.designation[plant.pos.x%16][plant.pos.y%16] next if d.hidden if d.dig == :No d.dig = :Default b.flags.designated = true cnt += 1 break if cnt == count_max end } puts "Updated #{cnt} plant designations" unless quiet end end def growtrees(material=nil, count_max=100, quiet=false) if !material # list plants cnt = Hash.new(0) each_tree { |plant| next if plant.grow_counter >= SaplingToTreeAge next if map_designation_at(plant).hidden cnt[plant.material] += 1 } cnt.sort_by { |mat, c| c }.each { |mat, c| name = @raws_tree_name[mat] puts " #{name} #{c}" unless quiet } else cnt = 0 each_tree(material) { |plant| next if plant.grow_counter >= SaplingToTreeAge next if map_designation_at(plant).hidden plant.grow_counter = SaplingToTreeAge cnt += 1 break if cnt == count_max } puts "Grown #{cnt} saplings" unless quiet end end end end
h0tbird/clusterawsadm
providers/terraform-provider-aws/aws/internal/service/wafv2/lister/list_pages_gen.go
<reponame>h0tbird/clusterawsadm // Code generated by "aws/internal/generators/listpages/main.go -function=ListIPSets,ListRegexPatternSets,ListRuleGroups,ListWebACLs -paginator=NextMarker github.com/aws/aws-sdk-go/service/wafv2"; DO NOT EDIT. package lister import ( "context" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/wafv2" ) func ListIPSetsPages(conn *wafv2.WAFV2, input *wafv2.ListIPSetsInput, fn func(*wafv2.ListIPSetsOutput, bool) bool) error { return ListIPSetsPagesWithContext(context.Background(), conn, input, fn) } func ListIPSetsPagesWithContext(ctx context.Context, conn *wafv2.WAFV2, input *wafv2.ListIPSetsInput, fn func(*wafv2.ListIPSetsOutput, bool) bool) error { for { output, err := conn.ListIPSetsWithContext(ctx, input) if err != nil { return err } lastPage := aws.StringValue(output.NextMarker) == "" if !fn(output, lastPage) || lastPage { break } input.NextMarker = output.NextMarker } return nil } func ListRegexPatternSetsPages(conn *wafv2.WAFV2, input *wafv2.ListRegexPatternSetsInput, fn func(*wafv2.ListRegexPatternSetsOutput, bool) bool) error { return ListRegexPatternSetsPagesWithContext(context.Background(), conn, input, fn) } func ListRegexPatternSetsPagesWithContext(ctx context.Context, conn *wafv2.WAFV2, input *wafv2.ListRegexPatternSetsInput, fn func(*wafv2.ListRegexPatternSetsOutput, bool) bool) error { for { output, err := conn.ListRegexPatternSetsWithContext(ctx, input) if err != nil { return err } lastPage := aws.StringValue(output.NextMarker) == "" if !fn(output, lastPage) || lastPage { break } input.NextMarker = output.NextMarker } return nil } func ListRuleGroupsPages(conn *wafv2.WAFV2, input *wafv2.ListRuleGroupsInput, fn func(*wafv2.ListRuleGroupsOutput, bool) bool) error { return ListRuleGroupsPagesWithContext(context.Background(), conn, input, fn) } func ListRuleGroupsPagesWithContext(ctx context.Context, conn *wafv2.WAFV2, input *wafv2.ListRuleGroupsInput, fn func(*wafv2.ListRuleGroupsOutput, bool) bool) error { for { output, err := conn.ListRuleGroupsWithContext(ctx, input) if err != nil { return err } lastPage := aws.StringValue(output.NextMarker) == "" if !fn(output, lastPage) || lastPage { break } input.NextMarker = output.NextMarker } return nil } func ListWebACLsPages(conn *wafv2.WAFV2, input *wafv2.ListWebACLsInput, fn func(*wafv2.ListWebACLsOutput, bool) bool) error { return ListWebACLsPagesWithContext(context.Background(), conn, input, fn) } func ListWebACLsPagesWithContext(ctx context.Context, conn *wafv2.WAFV2, input *wafv2.ListWebACLsInput, fn func(*wafv2.ListWebACLsOutput, bool) bool) error { for { output, err := conn.ListWebACLsWithContext(ctx, input) if err != nil { return err } lastPage := aws.StringValue(output.NextMarker) == "" if !fn(output, lastPage) || lastPage { break } input.NextMarker = output.NextMarker } return nil }
Sata51/configfile
src/shared/errors/bad-script-permission.error.js
export class BadScriptPermission extends Error { constructor(scriptName, message = `Bad permission on "${scriptName}" script.`) { super(message) this.scriptName = scriptName } }
lechium/tvOS135Headers
System/Library/PrivateFrameworks/SearchFoundation.framework/_SFPBSportsTeam.h
/* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:17:32 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/PrivateFrameworks/SearchFoundation.framework/SearchFoundation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <ProtocolBuffer/PBCodable.h> #import <libobjc.A.dylib/_SFPBSportsTeam.h> @class _SFPBImage, NSString, NSData; @protocol _SFPBSportsTeam <NSObject> @property (nonatomic,retain) _SFPBImage * logo; @property (nonatomic,copy) NSString * record; @property (nonatomic,copy) NSString * score; @property (nonatomic,copy) NSString * accessibilityDescription; @property (nonatomic,copy) NSString * name; @property (nonatomic,readonly) NSData * jsonData; @required -(NSString *)name; -(id)initWithDictionary:(id)arg1; -(void)setName:(id)arg1; -(NSString *)score; -(void)setScore:(id)arg1; -(_SFPBImage *)logo; -(void)setLogo:(id)arg1; -(NSString *)record; -(void)setRecord:(id)arg1; -(NSData *)jsonData; -(id)initWithJSON:(id)arg1; -(void)setAccessibilityDescription:(id)arg1; -(NSString *)accessibilityDescription; @end #import <libobjc.A.dylib/NSSecureCoding.h> @class _SFPBImage, NSString, NSData; @interface _SFPBSportsTeam : PBCodable <_SFPBSportsTeam, NSSecureCoding> { _SFPBImage* _logo; NSString* _record; NSString* _score; NSString* _accessibilityDescription; NSString* _name; } @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,retain) _SFPBImage * logo; //@synthesize logo=_logo - In the implementation block @property (nonatomic,copy) NSString * record; //@synthesize record=_record - In the implementation block @property (nonatomic,copy) NSString * score; //@synthesize score=_score - In the implementation block @property (nonatomic,copy) NSString * accessibilityDescription; //@synthesize accessibilityDescription=_accessibilityDescription - In the implementation block @property (nonatomic,copy) NSString * name; //@synthesize name=_name - In the implementation block @property (nonatomic,readonly) NSData * jsonData; -(NSString *)name; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(id)initWithDictionary:(id)arg1 ; -(void)setName:(NSString *)arg1 ; -(id)dictionaryRepresentation; -(NSString *)score; -(BOOL)readFrom:(id)arg1 ; -(void)writeTo:(id)arg1 ; -(void)setScore:(NSString *)arg1 ; -(_SFPBImage *)logo; -(void)setLogo:(_SFPBImage *)arg1 ; -(NSString *)record; -(void)setRecord:(NSString *)arg1 ; -(NSData *)jsonData; -(id)initWithFacade:(id)arg1 ; -(id)initWithJSON:(id)arg1 ; -(void)setAccessibilityDescription:(NSString *)arg1 ; -(NSString *)accessibilityDescription; @end
JoeFu/filemaker18helper
FMP_Help/pairs/pair2_23.js
var pairs = { "\u6A21":{"\u5F0F":1} ,"\u5F0F":{"\u952E":1,"(":1,"\u4E2D":1,"\u3002":1,"\u547D":1,"\u4E0B":1,"\u6765":1,"\u5316":1,"\u201D":1,"\u67E5":1,"\u5E03":1,"\u5BF9":1,"\u68C0":1,"\u201C":1,"\uFF09":1} ,"\u952E":{"\u76D8":1,"\u6D4F":1,"\u521B":1,"\u5165":1,"\u7701":1,"\u6253":1,"\u9009":1,"\u5728":1,"\u76EE":1,"\u6216":1,"\u7684":1,"\u5207":1,"\u5E76":1,"\u5DE6":1,"\u53F3":1,"\u9760":1,"\u663E":1,"\u4F7F":1,"\u5BF9":1,"\u5C06":1} ,"\u76D8":{"\u5FEB":1,"\uFF09":1,"\u7684":1} ,"\u5FEB":{"\u6377":1,"\u901F":1} ,"\u6377":{"\u65B9":1} ,"\u65B9":{"\u5F0F":1,"\u5F62":1} ,"(":{"macos":1} ,"macos":{")":1} ,")":{"\u53EF":1} ,"\u53EF":{"\u4EE5":1} ,"\u4EE5":{"\u5728":1,"\u4E0B":1,"\u4F7F":1,"\u53CA":1,"\u62D6":1,"45":1,"\u6B63":1} ,"\u5728":{"filemaker":1,"\u4E0D":1,"\u5E03":1,"\u9009":1,"\u62D6":1,"\u8C03":1,"\u76F8":1,"\u201C":1} ,"filemaker":{"\u00A0":1} ,"\u00A0":{"pro":1,"\u00A0":1,"\u60A8":1} ,"pro":{"advanced":1} ,"advanced":{"\u6A21":1} ,"\u4E2D":{"\u5DE5":1,"\u6240":1,"\u7684":1,"\u6DFB":1} ,"\u5DE5":{"\u4F5C":1,"\u5177":1} ,"\u4F5C":{"\u65F6":1,"\uFF0C":1} ,"\u65F6":{"\u4F7F":1,"\uFF09":1,"\u7981":1,"\u5206":1,"\u6309":1,"\u8C03":1,"\uFF0C":1,"\u62D6":1,"\u663E":1,"\u5207":1} ,"\u4F7F":{"\u7528":1,"\u6240":1} ,"\u7528":{"\u4EE5":1,"\u6D4F":1,"\u67E5":1,"\u952E":1,"\u9009":1,"tab":1,"\u7BAD":1,"\u4E8E":1,"\u201C":1} ,"\u4E0B":{"\u952E":1,"\u7684":1,"\u4E00":1,"\u62C9":1,"\u6253":1,"\uFF0C":1,"\u5BF9":1} ,"\u3002":{"\u8981":1,"\u76EE":1,"\u8F6C":1,"\u9009":1,"\u6CE8":1,"\uFF08":1,"\uFF09":1,"\u7528":1,"\u8C03":1,"\u6309":1,"\u62F7":1} ,"\u8981":{"\u5207":1,"\u4EC5":1} ,"\u5207":{"\u6362":1} ,"\u6362":{"\u81F3":1,"\u5B57":1,"\u6240":1,"\u5230":1,"\u52A8":1,"enter":1} ,"\u81F3":{"\u6309":1,"\u9009":1,"\u201C":1,"\u6700":1} ,"\u6309":{"\u952E":1,"enter":1,"\u94AE":1,"tab":1,"\u4F4F":1,"return":1,"shift":1,"option":1} ,"\u6D4F":{"\u89C8":1} ,"\u89C8":{"\u6A21":1} ,"\u547D":{"\u4EE4":1,"\u540D":1} ,"\u4EE4":{"-b":1,"-f":1,"-l":1,"-u":1,"-n":1,"-d":1,"-e":1,"-option-e":1,"-r":1,"-j":1,"-s":1,"-t":1,"-shift-t":1,"-p":1,"-option-p":1,"-shift-r":1,"-option-f":1,"-=\u53EF":1,"-i":1,"\u3002":1,"-1":1,"\u9009":1,"-option-c":1,"-option-v":1,"-option-\u5411":1,"-option-shift-r":1,"-option-y":1,"\u62D6":1,"\u540C":1,"-option-shift-y":1,"-option-":1,"-option-shift-":1,"-shift-[\u5C06":1,"-option-[\u5C06":1,"\uFF0C":1,"-option-l":1,"-option-r":1,"-shift-]":1,"-option-]":1,"-shift-option-l":1,"-2":1,"-3":1,"-4":1,"-k":1,"-return":1,"-enter":1,"-option-t":1} ,"-b":{"\u67E5":1} ,"\u67E5":{"\u627E":1,"\u5668":1} ,"\u627E":{"\u6A21":1,"\u6761":1,"\u6846":1,"\u8BF7":1} ,"-f":{"\u5E03":1} ,"\u5E03":{"\u5C40":1} ,"\u5C40":{"\u6A21":1,"\u5DE5":1,"\u3002":1,"\u547D":1,"\u8BF7":1,"esc":1,"\u7F16":1,"\u4E0A":1,"\u90E8":1,"\u521B":1} ,"-l":{"\u9884":1} ,"\u9884":{"\u89C8":1} ,"-u":{"\u53EF":1} ,"\u7684":{"\u952E":1,"\u6309":1,"\u60C5":1,"\u4FE1":1,"\u67E5":1,"\u5BF9":1,"\u540C":1,"\u5927":1,"\u201C":1,"\u76F8":1,"\u6837":1,"\u5E03":1,"\u9501":1,"\u8BA1":1,"\u7EBF":1,"\u6BD4":1} ,"\u6765":{"\u521B":1,"\u81EA":1,"\u6392":1,"\u7528":1,"\u590D":1} ,"\u521B":{"\u5EFA":1} ,"\u5EFA":{"\u3001":1,"\u8BB0":1,"\u548C":1,"\u67E5":1,"\u5E03":1,"\u65B0":1,"\u6216":1,"\u4E0E":1} ,"\u3001":{"\u5220":1,"\u590D":1,"\u7701":1,"\u6392":1,"\u683C":1,"\u63A7":1,"\u53C2":1} ,"\u5220":{"\u9664":1} ,"\u9664":{"\u3001":1,"\u8BB0":1,"\u67E5":1,"\u5BF9":1} ,"\u590D":{"\u5236":1,"\u6309":1} ,"\u5236":{"\u3001":1,"\u8BB0":1,"\u67E5":1,"\u5E03":1,"\u6240":1,"\u5BF9":1,"\u7EBF":1} ,"\u7701":{"\u7565":1} ,"\u7565":{"\u3001":1,"\u8BB0":1,"\u591A":1,"\u201D":1} ,"\u6392":{"\u5E8F":1,"\u5217":1} ,"\u5E8F":{"\u548C":1,"\u547D":1,"\u6309":1} ,"\u548C":{"\u6253":1,"\u590D":1,"\u5BF9":1} ,"\u6253":{"\u5370":1,"\u5F00":1} ,"\u5370":{"\u8BB0":1} ,"\u8BB0":{"\u5F55":1} ,"\u5F55":{"\u3002":1,"\u547D":1,"\u4E14":1,"\u6392":1,"\u8BF7":1,"esc":1,"\u7F16":1} ,"\u76EE":{"\u7684":1} ,"-n":{"\u590D":1,"\u5220":1,"\u8F6C":1} ,"-d":{"\u5220":1,"\u663E":1,"\u901A":1} ,"-e":{"\u5220":1,"\u590D":1} ,"\u4E14":{"\u4E0D":1} ,"\u4E0D":{"\u505A":1,"\u663E":1,"\u5FC5":1,"\u53D8":1} ,"\u505A":{"\u786E":1} ,"\u786E":{"\u8BA4":1} ,"\u8BA4":{"\u547D":1} ,"-option-e":{"\u4FEE":1} ,"\u4FEE":{"\u6539":1} ,"\u6539":{"\u4E0A":1,"\u4E3A":1,"\u952E":1} ,"\u4E0A":{"\u6B21":1,"\u4E00":1,"\u7684":1,"\u5BF9":1,"\u952E":1,"\u5C42":1} ,"\u6B21":{"\u67E5":1} ,"\u6761":{"\u4EF6":1,"\u8BB0":1,"\u6C34":1,"\u7684":1} ,"\u4EF6":{"\u547D":1} ,"-r":{"\u663E":1,"\u9501":1} ,"\u663E":{"\u793A":1} ,"\u793A":{"\u6240":1,"\u5BF9":1,"\u6216":1,"\u68C0":1} ,"\u6240":{"\u6709":1,"\u9700":1,"\u9009":1} ,"\u6709":{"\u8BB0":1,"\u6570":1} ,"-j":{"\u5BF9":1,"\u6267":1} ,"\u5BF9":{"\u8BB0":1,"\u8BDD":1,"\u9F50":1,"\u8C61":1,"\u8FB9":1,"\u6240":1,"\u9009":1} ,"-s":{"\u8F6C":1} ,"\u8F6C":{"\u5230":1,"\u5BF9":1} ,"\u5230":{"\u4E0B":1,"\u4E0A":1,"\u7279":1,"\u7F51":1,"\u53C2":1} ,"\u4E00":{"\u6761":1,"\u4E2A":1} ,"\u8BF7":{"\u53C2":1,"\u6C42":1,"\u5728":1} ,"\u53C2":{"\u9605":1,"\u8003":1} ,"\u9605":{"\u5BFC":1} ,"\u5BFC":{"\u822A":1} ,"\u822A":{"\u952E":1,"\u5BF9":1} ,"\u7279":{"\u5B9A":1} ,"\u5B9A":{"\u8BB0":1,"\u7684":1,"\u5E03":1,"\u4F4D":1,"\u5BF9":1,"\u5728":1,"\u547D":1,"\u5B57":1} ,"esc":{"\uFF08":1,"\u4E3A":1} ,"\uFF08":{"\u6FC0":1,"\u9009":1,"\u5F53":1,"\u8981":1,"\u6487":1,"\u5982":1,"\u6570":1,"\u9002":1,"\u5E03":1} ,"\u6FC0":{"\u6D3B":1} ,"\u6D3B":{"\u5F53":1,"\u52A8":1,"\u5FEB":1} ,"\u5F53":{"\u524D":1,"\u811A":1,"\u68C0":1} ,"\u524D":{"\u8BB0":1,"\u8BF7":1,"\u5E03":1,"\u666F":1,"\u5DE5":1} ,"\u7F16":{"\u53F7":1,"\u8F91":1} ,"\u53F7":{"\u6846":1,"\uFF0C":1,"\uFF09":1} ,"\u6846":{"\uFF09":1,"\u7684":1,"\u547D":1,"\uFF08":1,"\u5305":1,"\u4E0D":1,"\u4E2D":1} ,"\uFF09":{"\uFF0C":1,"\u547D":1,"\u7C98":1,"\u5F53":1,"\u76EE":1,"\u6216":1,"\u7BAD":1,"fn-enter":1,"\u4F7F":1,"\u952E":1} ,"\uFF0C":{"\u952E":1,"\u7136":1,"\u53EF":1,"\u4EE5":1,"\u8BF7":1,"\u5BF9":1,"\u5173":1,"\u6216":1} ,"\u5165":{"\u8BB0":1,"\u8BF7":1,"\u5E03":1} ,"\u7136":{"\u540E":1} ,"\u540E":{"\u6309":1,"\u5355":1} ,"enter":{"\u952E":1,"\uFF08":1,"\u76EE":1} ,"-t":{"\u7701":1,"\u521B":1} ,"\u591A":{"\u4E2A":1} ,"\u4E2A":{"\u8BB0":1,"\u67E5":1,"\u5E03":1,"\u5BF9":1} ,"-shift-t":{"\u4E3A":1} ,"\u4E3A":{"\u6D3B":1,"\u5782":1,"\u6C34":1,"\u78C5":1,"\u5398":1} ,"\u52A8":{"\u5B57":1,"\u7BAD":1,"\u65F6":1,"\u624B":1,"\u6001":1,"\u5BF9":1,"\u8BE5":1,"\u547D":1,"\u9009":1,"\u90E8":1,"\u6765":1,"1":1,"10":1} ,"\u5B57":{"\u6BB5":1,"\u952E":1} ,"\u6BB5":{"\u6253":1,"\u5185":1,"\u65F6":1,"\u3001":1,"\u9009":1,"\u201D":1,"\u547D":1,"\u91CD":1} ,"\u5F00":{"\u6216":1,"\u201C":1,"\u65F6":1,"\u5B57":1} ,"\u6216":{"\u5173":1,"\u65E5":1,"shift-tab":1,"\u5BBD":1,"\u9690":1,"\u7F16":1,"\u4ECE":1,"\u82F1":1,"0.1":1,"\u547D":1,"enter":1,"shift-enter":1,"fn-shift-enter":1,"\u5782":1,"\u4EC5":1,"\u5706":1} ,"\u5173":{"\u95ED":1} ,"\u95ED":{"\u4E0B":1,"\u5F39":1,"\u7F51":1} ,"\u62C9":{"\u5217":1} ,"\u5217":{"\u8868":1,"\u548C":1,"\u952E":1} ,"\u8868":{"\u6216":1} ,"\u65E5":{"\u5386":1} ,"\u5386":{"esc":1} ,"\u5F39":{"\u51FA":1} ,"\u51FA":{"\u83DC":1} ,"\u83DC":{"\u5355":1} ,"\u5355":{"\u7A7A":1,"\u51FB":1} ,"\u7A7A":{"\u683C":1} ,"\u683C":{"\u952E":1,"\u5F0F":1,"\u547D":1,"\u3001":1} ,"-p":{"\u5728":1} ,"\u8BDD":{"\u6846":1} ,"\u60C5":{"\u51B5":1} ,"\u51B5":{"\u4E0B":1} ,"-option-p":{"\u5237":1} ,"\u5237":{"\u65B0":1} ,"\u65B0":{"\u7A97":1,"\u5E03":1,"\u6392":1,"\u5B57":1} ,"\u7A97":{"\u53E3":1} ,"\u53E3":{"\u547D":1} ,"-shift-r":{"\u6FC0":1,"\u89E3":1} ,"\u901F":{"\u67E5":1} ,"-option-f":{"\u6253":1} ,"\u201C":{"\u66FF":1,"\u7701":1,"\u68C0":1,"\u5B9A":1,"\u6837":1,"\u5916":1,"\u6570":1,"\u5B57":1,"\u9009":1,"\u7EBF":1,"\u692D":1,"\u77E9":1,"\u5BF9":1} ,"\u66FF":{"\u6362":1} ,"\u5185":{"\u5BB9":1} ,"\u5BB9":{"\u201D":1} ,"\u201D":{"\u5BF9":1,"\u6309":1,"\u7684":1,"\u547D":1,"\u9009":1,"\u5DE5":1} ,"\u9009":{"\u62E9":1,"\u62E9\u002F\u53D6":1,"\u4E2D":1,"\u5BF9":1,"\u9879":1,"\u5B9A":1,"\u90E8":1} ,"\u62E9":{"\u5B57":1,"\u201C":1,"\u5E03":1,"\u591A":1,"\u6846":1,"\u88AB":1,"\u201D":1,"\u4E0E":1} ,"-=\u53EF":{"\u4EE5":1} ,"\u6C42":{"\u3002":1,"\u547D":1,"enter":1,"\u8BF7":1,"esc":1,"\u7F16":1} ,"\u62E9\u002F\u53D6":{"\u6D88":1} ,"\u6D88":{"\u9009":1} ,"\u94AE":{"\u547D":1} ,"\u6267":{"\u884C":1} ,"\u884C":{"\u67E5":1} ,"\u811A":{"\u672C":1} ,"\u672C":{"\u88AB":1} ,"\u88AB":{"\u6682":1,"\u5305":1} ,"\u6682":{"\u505C":1} ,"\u505C":{"\u65F6":1} ,"\u7981":{"\u6B62":1} ,"\u6B62":{"\uFF09":1} ,"\u7C98":{"\u8D34":1} ,"\u8D34":{"\u6765":1,"\u53E6":1} ,"\u81EA":{"\u7D22":1} ,"\u7D22":{"\u5F15":1} ,"\u5F15":{"\u7684":1} ,"\u4FE1":{"\u606F":1} ,"\u606F":{"\u547D":1} ,"-i":{"\u8F6C":1,"\u663E":1} ,"\u9F50":{"\u5BF9":1,"\u547D":1,"\u6548":1,"\u952E":1} ,"\u8C61":{"\u3001":1,"\u91CD":1,"\u3002":1,"\u6309":1,"\uFF0C":1,"\u7684":1,"\u5927":1,"\u7F51":1,"\u624B":1,"\u65F6":1,"\u5C06":1,"\u5207":1,"\u5411":1,"\u79FB":1,"\u547D":1,"\u7EC4":1,"\u7F6E":1,"\u9009":1,"\u5BF9":1,"\u6392":1,"\u201D":1} ,"\u5316":{"\u5B57":1} ,"\u63A7":{"\u5236":1} ,"\u5177":{"\uFF0C":1,"\u4E0E":1,"\u76F8":1,"\u753B":1,"\u4EE5":1,"\u952E":1} ,"\u53CA":{"\u521B":1} ,"\u91CD":{"\u590D":1,"\u65B0":1,"\u547D":1} ,"tab":{"\u952E":1} ,"shift-tab":{"\u76F4":1} ,"\u76F4":{"\u81F3":1,"\uFF0C":1,"\u6539":1,"\u7684":1,"\u79FB":1} ,"\u9700":{"\u7684":1} ,"\u4F4F":{"shift":1,"\u547D":1,"option-shift":1,"option":1} ,"shift":{"\u952E":1,"\u5E76":1,"\u4F7F":1} ,"\u540C":{"\u65F6":1,"\u4F4D":1} ,"\u5206":{"\u522B":1,"\u6807":1,"\u8D8A":1,"\u590D":1,"\u91CD":1,"\u65CB":1,"\u5BF9":1} ,"\u522B":{"\u5355":1} ,"\u51FB":{"\u5404":1,"\u6807":1} ,"\u5404":{"\u4E2A":1} ,"\u6CE8":{"\u91CA":1} ,"\u91CA":{"\u00A0":1} ,"\u60A8":{"\u4E5F":1} ,"\u4E5F":{"\u53EF":1} ,"\u62D6":{"\u52A8":1} ,"\u7BAD":{"\u5934":1} ,"\u5934":{"\u6307":1,"\u952E":1} ,"\u6307":{"\u9488":1} ,"\u9488":{"\u6765":1} ,"\u5305":{"\u542B":1,"\u56F4":1} ,"\u542B":{"\u5BF9":1} ,"\u5FC5":{"\u5B8C":1} ,"\u5B8C":{"\u5168":1} ,"\u5168":{"\u5305":1} ,"\u56F4":{"\u5BF9":1,"\u5728":1} ,"\u4EC5":{"\u9009":1,"\u6C34":1,"\u5782":1,"\u9650":1} ,"\u68C0":{"\u67E5":1} ,"\u5668":{"\u6253":1,"\u201D":1,"\u547D":1,"\u7684":1,"\u952E":1} ,"\u8C03":{"\u6574":1} ,"\u6574":{"\u6240":1,"\u64CD":1,"\u9009":1,"\u591A":1,"\u5BF9":1} ,"\u5927":{"\u5C0F":1} ,"\u5C0F":{"\u547D":1,"\u8C03":1,"\u5E76":1,"\u65F6":1} ,"-1":{"\u4F1A":1,"\u663E":1} ,"\u4F1A":{"\u79FB":1} ,"\u79FB":{"\u81F3":1,"\u52A8":1} ,"\u4F4D":{"\u201D":1,"\u7F6E":1} ,"\u9879":{"\u5361":1} ,"\u5361":{"\u3002":1,"\u547D":1,"\u4E2D":1,"\uFF08":1,"\u952E":1} ,"\u64CD":{"\u4F5C":1} ,"return":{"\u3002":1,"\u6216":1} ,"\u5E76":{"\u4FDD":1,"\u62D6":1,"\u52A8":1} ,"\u4FDD":{"\u6301":1} ,"\u6301":{"\u5176":1,"\u56FA":1} ,"\u5176":{"\u6BD4":1,"\u957F":1} ,"\u6BD4":{"\u4F8B":1} ,"\u4F8B":{"\u4E0D":1,"\u8C03":1} ,"\u53D8":{"\u6309":1,"\u3002":1} ,"\u624B":{"\u67C4":1} ,"\u67C4":{"\u3002":1,"\u5728":1} ,"\u957F":{"\u5EA6":1} ,"\u5EA6":{"\u6216":1,"\u5DEE":1,"\u589E":1} ,"\u5BBD":{"\u5EA6":1} ,"\u5DEE":{"\u4E0D":1} ,"option-shift":{"\u5E76":1} ,"\u76F8":{"\u5BF9":1,"\u540C":1,"\u4E92":1} ,"\u8FB9":{"\u7F18":1} ,"\u7F18":{"\u5C06":1} ,"\u5C06":{"\u4FDD":1,"\u5BF9":1,"\u6240":1,"\u5F53":1} ,"\u56FA":{"\u5B9A":1} ,"\u7F6E":{"\u3002":1,"\u4E3A":1,"\u4E8E":1} ,"\u62F7":{"\u8D1D":1} ,"\u8D1D":{"\u6240":1} ,"\u6837":{"\u5F0F":1} ,"-option-c":{"\u7C98":1} ,"\u53E6":{"\u4E00":1} ,"-option-v":{"\u76EE":1} ,"\u5DE6":{"\u5BF9":1,"\u952E":1} ,"-option-\u5411":{"\u5DE6":1,"\u53F3":1,"\u4E0A":1,"\u4E0B":1} ,"\u53F3":{"\u5BF9":1,"\u952E":1} ,"\u9760":{"\u4E0A":1,"\u4E0B":1} ,"\u9690":{"\u85CF":1} ,"\u85CF":{"\u6807":1,"\u5BF9":1,"\u53C2":1,"\u68C0":1} ,"\u6807":{"\u5C3A":1,"\u7B7E":1} ,"\u5C3A":{"\u547D":1} ,"-option-shift-r":{"\u663E":1} ,"\u7F51":{"\u683C":1} ,"-option-y":{"\u5728":1} ,"\u8003":{"\u7EBF":1} ,"\u7EBF":{"\u5E76":1,"\u7684":1,"\u547D":1,"\u201D":1,"\u7ED8":1,"\u6761":1} ,"\u6001":{"\u53C2":1} ,"\u6548":{"\u679C":1} ,"\u679C":{"\u6309":1,"\u547D":1,"\u8BBE":1} ,"\u8BE5":{"\u5BF9":1} ,"-option-shift-y":{"\u521B":1} ,"\u8F91":{"\u5BF9":1} ,"-option-":{";":1,"\u2019":1} ,";":{"\u5C06":1,"\u521B":1} ,"-option-shift-":{";":1} ,"\u2019":{"\uFF08":1} ,"\u6487":{"\u53F7":1} ,"\u5411":{"\u524D":1,"\u80CC":1} ,"\u666F":{"\u79FB":1} ,"-shift-[\u5C06":{"\u6240":1} ,"\u6700":{"\u4E0A":1} ,"\u5C42":{"\u547D":1} ,"-option-[\u5C06":{"\u90E8":1} ,"\u90E8":{"\u5206":1} ,"\u7B7E":{"\u4ECE":1,"\u62D6":1} ,"\u4ECE":{"\u6C34":1,"\u5782":1} ,"\u6C34":{"\u5E73":1} ,"\u5E73":{"\u6539":1,"\u547D":1,"\u6216":1} ,"\u5782":{"\u76F4":1} ,"\u8D8A":{"\u8FC7":1} ,"\u8FC7":{"\u5BF9":1,"\u62D6":1} ,"option":{"\u5E76":1,"\u4EC5":1,"\u4F7F":1,"\u6D4F":1} ,"\u901A":{"\u8FC7":1} ,"\u7EC4":{"\u5408":1} ,"\u5408":{"\u5BF9":1} ,"\u9501":{"\u5B9A":1} ,"-option-l":{"\u5C06":1} ,"1":{"\u78C5":1} ,"\u78C5":{"\uFF08":1,"\u6216":1} ,"\u5982":{"\u679C":1} ,"\u8BBE":{"\u7F6E":1} ,"\u82F1":{"\u5BF8":1} ,"\u5BF8":{"\uFF09":1} ,"0.1":{"\u5398":1} ,"\u5398":{"\u7C73":1} ,"\u7C73":{"\uFF08":1,"\uFF09":1} ,"10":{"\u500D":1} ,"\u500D":{"\u8FDC":1} ,"\u8FDC":{"shift-\u7BAD":1} ,"shift-\u7BAD":{"\u5934":1} ,"\u65CB":{"\u8F6C":1} ,"-option-r":{"\u5C06":1} ,"\u80CC":{"\u666F":1} ,"-shift-]":{"\u5C06":1} ,"\u4E8E":{"\u5E95":1,"\u6CA1":1} ,"\u5E95":{"\u5C42":1} ,"-option-]":{"\u62C6":1} ,"\u62C6":{"\u5206":1} ,"\u89E3":{"\u9664":1} ,"-shift-option-l":{"\u76EE":1} ,"-2":{"\u663E":1} ,"\u5916":{"\u89C2":1} ,"\u89C2":{"\u201D":1} ,"-3":{"\u663E":1} ,"\u6570":{"\u636E":1,"\u5B57":1} ,"\u636E":{"\u201D":1} ,"-4":{"\u76EE":1} ,"-k":{"\u5728":1} ,"\u6DFB":{"\u52A0":1} ,"\u52A0":{"\u65B0":1} ,"-return":{"\u6216":1} ,"-enter":{"\u5BF9":1} ,"\u540D":{"return":1} ,"-option-t":{"\u76EE":1} ,"\u4E0E":{"\u201C":1,"\u5BFC":1,"\u4FEE":1} ,"\u4E92":{"\u5207":1} ,"shift-enter":{"\uFF08":1} ,"fn-enter":{"\u6216":1} ,"fn-shift-enter":{"\uFF08":1} ,"\u9002":{"\u7528":1} ,"\u6CA1":{"\u6709":1} ,"\u8BA1":{"\u7B97":1} ,"\u7B97":{"\u673A":1} ,"\u673A":{"\uFF09":1} ,"\u753B":{"\u4E00":1,"\u7EBF":1,"\u5706":1,"\u6B63":1} ,"\u7ED8":{"\u5236":1} ,"45":{"\u5EA6":1} ,"\u589E":{"\u91CF":1} ,"\u91CF":{"\u753B":1} ,"\u692D":{"\u5706":1} ,"\u5706":{"\u5F62":1,"\u753B":1,"\u7684":1} ,"\u5F62":{"\u201D":1,"\u753B":1,"\u7684":1,"\u6216":1} ,"\u77E9":{"\u5F62":1} ,"\u6B63":{"\u65B9":1} ,"\u9650":{"\u4EE5":1} } ;Search.control.loadWordPairs(pairs);
SoftwareMansion/expo
ios/versioned-react-native/ABI15_0_0/React/Views/ABI15_0_0RCTConvert+MapKit.h
<filename>ios/versioned-react-native/ABI15_0_0/React/Views/ABI15_0_0RCTConvert+MapKit.h /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import <MapKit/MapKit.h> #import <ReactABI15_0_0/ABI15_0_0RCTConvert.h> @class ABI15_0_0RCTMapAnnotation; @class ABI15_0_0RCTMapOverlay; @interface ABI15_0_0RCTConvert (MapKit) + (MKCoordinateSpan)MKCoordinateSpan:(id)json; + (MKCoordinateRegion)MKCoordinateRegion:(id)json; + (MKMapType)MKMapType:(id)json; + (ABI15_0_0RCTMapAnnotation *)ABI15_0_0RCTMapAnnotation:(id)json; + (ABI15_0_0RCTMapOverlay *)ABI15_0_0RCTMapOverlay:(id)json; + (NSArray<ABI15_0_0RCTMapAnnotation *> *)ABI15_0_0RCTMapAnnotationArray:(id)json; + (NSArray<ABI15_0_0RCTMapOverlay *> *)ABI15_0_0RCTMapOverlayArray:(id)json; @end
Thulio-Carvalho/Advanced-Algorithms-Problems
Old/Contests/C5/P4.cpp
#include <bits/stdc++.h> using namespace std; int daysOff(int n, int start){ int day = start; int off = 0; for (int i = 1; i <= n; i++){ if (day%(6) == 0){ off++; } if (day%(7) == 0){ off++; day = 0; } // cout << day << endl; // cout << "offs yet = " << off << endl; day++; } return off; } int main(){ int n; scanf("%d", &n); int min, max; min = daysOff(n, 1); max = min; for (int i = 2; i <= 7; i++){ int cnt = daysOff(n, i); if (cnt > max){ max = cnt; } if (cnt < min) min = cnt; } printf("%d %d\n", min, max); return 0; }
wangcy6/weekly_read
code_reading/oceanbase-master/src/share/allocator/ob_tenant_mutil_allocator_mgr.h
<filename>code_reading/oceanbase-master/src/share/allocator/ob_tenant_mutil_allocator_mgr.h /** * Copyright (c) 2021 OceanBase * OceanBase CE is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #ifndef _OB_SHARE_TENANT_MUTIL_ALLOCATOR_MGR_H_ #define _OB_SHARE_TENANT_MUTIL_ALLOCATOR_MGR_H_ #include "share/ob_define.h" #include "share/ob_unit_getter.h" #include "lib/allocator/ob_block_alloc_mgr.h" #include "lib/allocator/ob_vslice_alloc.h" namespace oceanbase { namespace common { class ObILogAllocator; class ObIReplayTaskAllocator; class ObTenantMutilAllocator; class ObTenantMutilAllocatorMgr { public: typedef ObTenantMutilAllocator TMA; ObTenantMutilAllocatorMgr() : is_inited_(false), locks_(), tma_array_(), clog_entry_alloc_(ObMemAttr(OB_SERVER_TENANT_ID, ObModIds::OB_LOG_TASK_BODY), OB_MALLOC_MIDDLE_BLOCK_SIZE, clog_body_blk_alloc_) {} ~ObTenantMutilAllocatorMgr() {} int init(); int get_tenant_mutil_allocator(const uint64_t tenant_id, ObTenantMutilAllocator*& out_allocator); int get_tenant_log_allocator(const uint64_t tenant_id, ObILogAllocator*& out_allocator); int get_tenant_replay_allocator(const uint64_t tenant_id, ObIReplayTaskAllocator*& out_allocator); int get_tenant_limit(const uint64_t tenant_id, int64_t& limit); int set_tenant_limit(const uint64_t tenant_id, const int64_t new_limit); void* alloc_log_entry_buf(const int64_t size) { return clog_entry_alloc_.alloc(size); } void free_log_entry_buf(void* ptr) { if (NULL != ptr) { clog_entry_alloc_.free(ptr); } } // a tricky interface, ugly but save memory void free_log_task_buf(void* ptr); int update_tenant_mem_limit(const share::TenantUnits& all_tenant_units); public: static ObTenantMutilAllocatorMgr& get_instance(); private: int construct_allocator_(const uint64_t tenant_id, TMA*& out_allocator); int create_tenant_mutil_allocator_(const uint64_t tenant_id, TMA*& out_allocator); private: static const uint64_t PRESERVED_TENANT_COUNT = 10000; private: bool is_inited_; obsys::CRWLock locks_[PRESERVED_TENANT_COUNT]; ObTenantMutilAllocator* tma_array_[PRESERVED_TENANT_COUNT]; ObBlockAllocMgr clog_body_blk_alloc_; ObVSliceAlloc clog_entry_alloc_; private: DISALLOW_COPY_AND_ASSIGN(ObTenantMutilAllocatorMgr); }; // end of class ObTenantMutilAllocatorMgr #define TMA_MGR_INSTANCE (::oceanbase::common::ObTenantMutilAllocatorMgr::get_instance()) } // end of namespace common } // end of namespace oceanbase #endif /* _OB_SHARE_TENANT_MUTIL_ALLOCATOR_MGR_H_ */
codehaus/coconut
cake/trunk/cake-service/cake-service-tck/src/main/java/org/codehaus/cake/test/tck/RequireService.java
/* Copyright 2004 - 2008 <NAME> <<EMAIL>> * Licensed under the Apache 2.0 License. */ package org.codehaus.cake.test.tck; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface RequireService { public Class[] value(); public boolean isAvailable() default true; }
DianaAssistant/DIANA
redemption/src/utils/utf.hpp
<filename>redemption/src/utils/utf.hpp /* 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 2 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2012 Author(s): <NAME>, <NAME>, <NAME>, <NAME>, <NAME> Based on xrdp Copyright (C) <NAME> 2004-2010 stream object, used for input / output communication between entities */ #pragma once #include "utils/sugar/bytes_view.hpp" #include "utils/only_type.hpp" #include <cstdint> enum { maximum_length_of_utf8_character_in_bytes = 4 }; // UTF8Len assumes input is valid utf8, zero terminated, that has been checked before std::size_t UTF8Len(byte_ptr source) noexcept; std::size_t UTF16ByteLen(bytes_view source) noexcept; void UTF16Lower(uint8_t * source, std::size_t max_len) noexcept; void UTF16Upper(uint8_t * source, std::size_t max_len) noexcept; // UTF8GetLen find the number of bytes of the len first characters of input. // It assumes input is valid utf8, zero terminated (that has been checked before). std::size_t UTF8GetPos(uint8_t const * source, std::size_t len) noexcept; // UTF8Len assumes input is valid utf8, zero terminated, that has been checked before std::size_t UTF8StringAdjustedNbBytes(const uint8_t * source, std::size_t max_len) noexcept; // UTF8RemoveOne assumes input is valid utf8, zero terminated, that has been checked before void UTF8RemoveOne(writable_bytes_view source) noexcept; // UTF8InsertUtf16 assumes input is valid utf8, zero terminated, that has been checked before // UTF8InsertUtf16 won't insert anything and return false if modified string buffer does not have enough space to insert bool UTF8InsertUtf16(writable_bytes_view source, std::size_t bytes_used, uint16_t unicode_char) noexcept; // UTF8toUTF16 never writes the trailing zero std::size_t UTF8toUTF16(bytes_view source, uint8_t * target, size_t t_len) noexcept; std::size_t UTF8toUTF16(bytes_view source, writable_bytes_view target) noexcept; // UTF8toUTF16 never writes the trailing zero (with Lf to CrLf conversion). std::size_t UTF8toUTF16_CrLf(bytes_view source, uint8_t * target, std::size_t t_len) noexcept; template<class ResizableArray> void UTF8toResizableUTF16(bytes_view utf16_source, ResizableArray& utf8_target) { utf8_target.resize(utf16_source.size() * 4); auto len = UTF8toUTF16(utf16_source, make_writable_array_view(utf8_target)); utf8_target.resize(len); } template<class ResizableArray> ResizableArray UTF8toResizableUTF16(bytes_view utf16_source) { ResizableArray utf8_target; UTF8toResizableUTF16(utf16_source, utf8_target); return utf8_target; } template<class ResizableArray> void UTF8toResizableUTF16_zstring(bytes_view utf16_source, ResizableArray& utf8_target) { utf8_target.resize(utf16_source.size() * 4); auto len = UTF8toUTF16(utf16_source, make_writable_array_view(utf8_target)); utf8_target[len ] = '\0'; utf8_target[len + 1] = '\0'; utf8_target.resize(len + 2); } template<class ResizableArray> ResizableArray UTF8toResizableUTF16_zstring(bytes_view utf16_source) { ResizableArray utf8_target; UTF8toResizableUTF16_zstring(utf16_source, utf8_target); return utf8_target; } class UTF8toUnicodeIterator { public: explicit UTF8toUnicodeIterator(byte_ptr str) noexcept; UTF8toUnicodeIterator & operator++() noexcept; uint32_t operator*() const noexcept { return this->ucode; } [[nodiscard]] uint32_t code() const noexcept { return this->ucode; } [[nodiscard]] uint8_t const * pos() const noexcept { return this->source; } private: const uint8_t * source; uint32_t ucode = 0; }; // Return number of UTF8 bytes used to encode UTF16 input // do not write trailing 0 std::size_t UTF16toUTF8(const uint8_t * utf16_source, std::size_t utf16_len, uint8_t * utf8_target, std::size_t target_len) noexcept; // Return number of UTF8 bytes used to encode UTF16 input // do not write trailing 0 writable_bytes_view UTF16toUTF8_buf(bytes_view utf16_source, writable_bytes_view utf8_target) noexcept; writable_bytes_view UTF16toUTF8_buf(only_type<uint16_t> utf16_source, writable_bytes_view utf8_target) noexcept; template<class ResizableArray> void UTF16toResizableUTF8(bytes_view utf16_source, ResizableArray& utf8_target) { utf8_target.resize(utf16_source.size() * 2); auto len = UTF16toUTF8_buf(utf16_source, make_writable_array_view(utf8_target)).size(); utf8_target.resize(len); } template<class ResizableArray> ResizableArray UTF16toResizableUTF8(bytes_view utf16_source) { ResizableArray utf8_target; UTF16toResizableUTF8(utf16_source, utf8_target); return utf8_target; } template<class ResizableArray> void UTF16toResizableUTF8_zstring(bytes_view utf16_source, ResizableArray& utf8_target) { utf8_target.resize(utf16_source.size() * 2 + 1); auto len = UTF16toUTF8_buf(utf16_source, make_writable_array_view(utf8_target)).size(); utf8_target[len] = '\0'; utf8_target.resize(len + 1); } template<class ResizableArray> ResizableArray UTF16toResizableUTF8_zstring(bytes_view utf16_source) { ResizableArray utf8_target; UTF16toResizableUTF8_zstring(utf16_source, utf8_target); return utf8_target; } // Return number of UTF8 bytes used to encode UTF16 input // do not write trailing 0 std::size_t UTF16toUTF8(const uint16_t * utf16_source, std::size_t utf16_len, uint8_t * utf8_target, std::size_t target_len) noexcept; // Return number of UTF8 bytes used to encode UTF32 input // do not write trailing 0 std::size_t UTF32toUTF8(const uint8_t * utf32_source, std::size_t utf32_len, uint8_t * utf8_target, std::size_t target_len) noexcept; // Return number of UTF8 bytes used to encode UTF32 input // do not write trailing 0 std::size_t UTF32toUTF8(uint32_t utf32_char, uint8_t * utf8_target, std::size_t target_len) noexcept; size_t UTF8CharNbBytes(const uint8_t * source) noexcept; bool is_utf8_string(uint8_t const * s, int length = -1) noexcept; /*NOLINT*/ bool is_ASCII_string(bytes_view source) noexcept; bool is_ASCII_string(byte_ptr source) noexcept; std::size_t UTF8StrLenInChar(byte_ptr source) noexcept; std::size_t UTF16toLatin1(const uint8_t * utf16_source_, std::size_t utf16_len, uint8_t * latin1_target, std::size_t latin1_len) noexcept; std::size_t Latin1toUTF16(bytes_view latin1_source, uint8_t * utf16_target, std::size_t utf16_len) noexcept; std::size_t Latin1toUTF8( const uint8_t * latin1_source, std::size_t latin1_len, uint8_t * utf8_target, std::size_t utf8_len) noexcept;
blockfuse/payment-gateway
adapters/lnd-adapter/spec/integration/routes/peers.spec.js
const getApp = require('../../../app'); const service = require('ln-service/service'); const request = require('supertest'); describe('Peers', () => { let app; beforeAll((done) => { return getApp().then(returnedApp => { app = returnedApp; done(); }); }); describe('/v0/peers/', () => { it('responds and lists peers', (done) => { let url = `/v0/peers/`; request(app) .get(url) .set('Authorization', 'Basic cnBjdXNlcjpycGNwYXNzd29yZA==') .expect(200) .end(function(err, res) { expect(Array.isArray(res.body.peers)).toBe(true); if (err) throw err; done(); }); }); // TODO: Add a second peer to connect to instead of just self xit('responds and adds a peer', (done) => { let url = `/v0/peers/`; let body = { socket: 'localhost:9735', public_key: '<KEY>' }; request(app) .post(url) .send(body) .set('Authorization', 'Basic cnBjdXNlcjpycGNwYXNzd29yZA==') .expect(200) .end(function(err, res) { if (err) throw err; done(); }); }); // TODO: Add a second peer to connect to xit('responds and removes a peer', (done) => { const peerId = '<KEY>'; let url = `/v0/peers/${peerId}`; request(app) .delete(url) .set('Authorization', 'Basic cnBjdXNlcjpycGNwYXNzd29yZA==') .expect(200) .end(function(err, res) { if (err) throw err; done(); }); }); }); });
timfjord/sublime_debugger
modules/commands.py
from __future__ import annotations from .typecheck import * # import Debugger; Debugger.modules.debugger.commands.Commands.generate_commands_and_menus(); from .import core from .debugger import Debugger from .adapters_registry import AdaptersRegistry import sublime_plugin import sublime import json menu_context = 1 << 0 menu_main = 1 << 1 menu_commands = 1 << 2 menu_no_prefix = 1 << 3 menu_widget = 1 << 4 open_without_running = 1 << 5 visible_debugger_open = 1 << 6 visible_debugger_closed = 1 << 7 class Command: menu_context = 1 menu_main = 1 << 1 menu_commands = 1 << 2 menu_no_prefix = 1 << 3 menu_widget = 1 << 4 def __init__(self, name: str, command: str, action: Callable[[sublime.Window], None], flags:int=menu_commands|menu_main): self.name = name self.action = action self.flags = flags self.command = command def run(self, window: sublime.Window): self.action(window) def is_visible(self, window: sublime.Window) -> bool: return True def is_enabled(self, window: sublime.Window) -> bool: return True class CommandDebugger(Command): def __init__(self, name: str, command: str, action:Callable[[Debugger], None], enabled: Callable[[Debugger], bool] | None = None, flags: int = menu_commands|menu_main): self.name = name self.action = action self.enabled = enabled self.flags = flags self.command = command def parameters(self, window: sublime.Window) -> tuple[sublime.Window, Debugger|None]: return window, Debugger.get(window) def run(self, window: sublime.Window): debugger = Debugger.get(window) if not debugger or not debugger.is_panel_visible(): debugger = Debugger.get(window, True) # don't run this command if the debugger is not visible if self.flags & open_without_running: return if not debugger: return self.action(debugger) def is_visible(self, window: sublime.Window): debugger = Debugger.get(window) if self.flags & visible_debugger_open: return bool(debugger) if self.flags & visible_debugger_closed: return not bool(debugger) return True def is_enabled(self, window: sublime.Window): debugger = Debugger.get(window) if not self.enabled: return True if debugger: return self.enabled(debugger) return False def open_settings(window: sublime.Window): window.run_command('edit_settings', { 'base_file': '${packages}/Debugger/debugger.sublime-settings' }) def generate_commands(window: sublime.Window): Commands.generate_commands_and_menus() commands = [ CommandDebugger ( name='Open', command='open', action=Debugger.open, ), CommandDebugger ( name='Quit', command='quit', action=Debugger.quit, flags=menu_commands|menu_main|visible_debugger_open, ), Command( name='Settings', command='settings', action=open_settings, flags=menu_main ), Command( name='Preferences: Debugger Settings', command='settings', action=open_settings, flags=menu_commands | menu_no_prefix ), Command( name='Generate Commands', command='generate_commands', action=generate_commands, flags=menu_commands ), None, CommandDebugger ( name='Install Adapters', command='install_adapters', action=Debugger.install_adapters, ), CommandDebugger ( name='Add or Select Configuration', command='change_configuration', action=Debugger.change_configuration, ), None, CommandDebugger ( name='Start', command='start', action=Debugger.on_play, flags=menu_commands|menu_main|open_without_running ), CommandDebugger ( name='Start (no debug)', command='start_no_debug', action=Debugger.on_play_no_debug, ), CommandDebugger ( name='Stop', command='stop', action=Debugger.on_stop, enabled=Debugger.is_stoppable ), None, CommandDebugger ( name='Resume', command='resume', action=Debugger.on_resume, enabled=Debugger.is_paused ), CommandDebugger ( name='Pause', command='pause', action=Debugger.on_pause, enabled=Debugger.is_running, ), CommandDebugger ( name='Step Over', command='step_over', action=Debugger.on_step_over, enabled=Debugger.is_paused ), CommandDebugger ( name='Step In', command='step_in', action=Debugger.on_step_in, enabled=Debugger.is_paused ), CommandDebugger ( name='Step Out', command='step_out', action=Debugger.on_step_out, enabled=Debugger.is_paused ), None, CommandDebugger ( name='Input Command', command='input_command', action=Debugger.on_input_command, enabled=Debugger.is_active ), CommandDebugger ( name='Run Task', command='run_task', action=Debugger.on_run_task, ), CommandDebugger ( name='Run Last Task', command='run_last_task', action=Debugger.on_run_last_task, flags=menu_main, ), CommandDebugger ( name='Add Function Breakpoint', command='add_function_breakpoint', action=Debugger.add_function_breakpoint, ), CommandDebugger ( name='Clear Breakpoints', command='clear_breakpoints', action=Debugger.clear_all_breakpoints, ), CommandDebugger ( name='Clear Console', command='clear_console', action=Debugger.clear_terminal_panel, flags=menu_widget, ), CommandDebugger ( name='Show Protocol', command='show_protocol', action=Debugger.show_protocol_panel, flags=menu_widget, ), CommandDebugger ( name='Add Watch Expression', command='add_watch_expression', action=Debugger.add_watch_expression, ), CommandDebugger ( name='Force Save', command='save_data', action=Debugger.save_data, ), None, CommandDebugger ( name='Toggle Breakpoint', command='toggle_breakpoint', action=Debugger.toggle_breakpoint, flags=menu_context, ), CommandDebugger ( name='Toggle Column Breakpoint', command='toggle_column_breakpoint', action=Debugger.toggle_column_breakpoint, flags=menu_context, ), CommandDebugger ( name='Run To Selected Line', command='run_to_current_line', action=Debugger.run_to_current_line, enabled=Debugger.is_paused, flags=menu_context, ), None, ] class DebuggerCommand (sublime_plugin.WindowCommand): def run(self, action: str): #type: ignore command = Commands.commands_by_action[action] command.run(self.window) def is_enabled(self, action: str): #type: ignore command = Commands.commands_by_action[action] return command.is_enabled(self.window) def is_visible(self, action: str): #type: ignore command = Commands.commands_by_action[action] return command.is_visible(self.window) # allow using debugger_exec to run a build system as a Debugger Task class DebuggerExecCommand(sublime_plugin.WindowCommand): def run(self, **kwargs): from .debugger import Debugger from .dap import Task debugger = Debugger.get(self.window, create=True) task = Task.from_json(kwargs) debugger.run_task(task) class Commands: commands_by_action: dict[str, Command] = {} @staticmethod def initialize(): for command in commands: if not command: continue Commands.commands_by_action[command.command] = command for adapter in AdaptersRegistry.all: for command in adapter.commands(): Commands.commands_by_action[command.command] = command @staticmethod def generate_commands_and_menus(): all_commands: list[Command|None] = [] all_commands.extend(commands) for adapter in AdaptersRegistry.all: c = adapter.commands() if c: all_commands.extend(c) current_package = core.current_package() def generate_commands(menu: int, prefix: str = "", include_seperators: bool = True): out_commands: list[Any] = [] for command in all_commands: if not command: if include_seperators: out_commands.append({"caption": '-'}) continue if not (command.flags & menu): continue if command.flags & menu_no_prefix: caption = command.name else: caption = prefix + command.name out_commands.append( { "caption": caption, "command": "debugger", "args": { "action": command.command, } } ) return out_commands def save_commands(file: str, commands: Any): with open(current_package + file, 'w') as f: json.dump(commands, f, indent=4, separators=(',', ': ')) commands_palette = generate_commands(menu_commands, prefix="Debugger: ", include_seperators=False) # hidden command used for gathering input from the command palette commands_palette.append({ "caption": "Debugger", "command": "debugger_input" }) save_commands('/Commands/Commands.sublime-commands', commands_palette) main = [{ "id": "tools", "children": [ { "id": "debugger", "caption": "Debugger", "children": generate_commands(menu_main), } ]} ] save_commands('/Commands/Main.sublime-menu', main) print('Generating commands') commands_context = generate_commands(menu_context) save_commands('/Commands/Context.sublime-menu', commands_context) commands_context = generate_commands(menu_widget) save_commands('/Commands/Widget Debug.sublime-menu', commands_context) # keymap_commands = [] # for action in actions_window + actions_context: # if action['caption'] == '-': # continue # keymap_commands.append( # { # "keys": action.get('keys', "UNBOUND"), # "command": "debugger", # "args": { # "action": action['action'], # } # } # ) # with open(current_package + '/Commands/Default.sublime-keymap', 'w') as file: # json.dump(keymap_commands, file, indent=4, separators=(',', ': ')) # generate_commands_and_menus()
npocmaka/Windows-Server-2003
com/published/dload/ole32.c
#include "compch.h" #pragma hdrstop #define _OLE32_ #include <objidl.h> #undef WINOLEAPI #define WINOLEAPI HRESULT STDAPICALLTYPE #undef WINOLEAPI_ #define WINOLEAPI_(_x) _x STDAPICALLTYPE static WINOLEAPI CLSIDFromProgID( IN LPCOLESTR lpszProgID, OUT LPCLSID lpclsid ) { return E_FAIL; } static WINOLEAPI CLSIDFromString( IN LPOLESTR lpsz, OUT LPCLSID pclsid ) { return E_FAIL; } static WINOLEAPI CoCancelCall( IN DWORD dwThreadId, IN ULONG ulTimeout ) { return E_FAIL; } static WINOLEAPI CoCreateGuid( OUT GUID * pGuid ) { return RPC_S_OUT_OF_MEMORY; } static WINOLEAPI CoCreateInstance( IN REFCLSID rclsid, IN LPUNKNOWN pUnkOuter, IN DWORD dwClsContext, IN REFIID riid, OUT LPVOID FAR* ppv ) { *ppv = NULL; return E_FAIL; } static WINOLEAPI CoDisableCallCancellation( IN LPVOID pReserved ) { return E_FAIL; } static WINOLEAPI CoDisconnectObject( IN LPUNKNOWN pUnk, IN DWORD dwReserved ) { return E_FAIL; } static WINOLEAPI CoEnableCallCancellation( IN LPVOID pReserved ) { return E_FAIL; } static WINOLEAPI CoInitialize( IN LPVOID pvReserved ) { return E_FAIL; } static WINOLEAPI CoInitializeEx( IN LPVOID pvReserved, IN DWORD dwCoInit ) { return E_FAIL; } static WINOLEAPI CoInitializeSecurity( IN PSECURITY_DESCRIPTOR pSecDesc, IN LONG cAuthSvc, IN SOLE_AUTHENTICATION_SERVICE *asAuthSvc, IN void *pReserved1, IN DWORD dwAuthnLevel, IN DWORD dwImpLevel, IN void *pAuthList, IN DWORD dwCapabilities, IN void *pReserved3 ) { return E_FAIL; } static WINOLEAPI CoImpersonateClient() { return E_FAIL; } static WINOLEAPI_(HINSTANCE) CoLoadLibrary( IN LPOLESTR lpszLibName, IN BOOL bAutoFree ) { return NULL; } static WINOLEAPI CoRevertToSelf() { return E_FAIL; } static WINOLEAPI CoSwitchCallContext( IN IUnknown *pNewObject, OUT IUnknown **ppOldObject ) { return E_FAIL; } static WINOLEAPI CoMarshalInterface( IN LPSTREAM pStm, IN REFIID riid, IN LPUNKNOWN pUnk, IN DWORD dwDestContext, IN LPVOID pvDestContext, IN DWORD mshlflags ) { return E_FAIL; } static WINOLEAPI CoRegisterClassObject( IN REFCLSID rclsid, IN LPUNKNOWN pUnk, IN DWORD dwClsContext, IN DWORD flags, OUT LPDWORD lpdwRegister ) { return E_FAIL; } static WINOLEAPI CoReleaseMarshalData( IN LPSTREAM pStm ) { return E_FAIL; } static WINOLEAPI CoResumeClassObjects( void ) { return E_FAIL; } static WINOLEAPI CoRevokeClassObject( IN DWORD dwRegister ) { return E_FAIL; } static WINOLEAPI CoSetProxyBlanket( IN IUnknown *pProxy, IN DWORD dwAuthnSvc, IN DWORD dwAuthzSvc, IN OLECHAR *pServerPrincName, IN DWORD dwAuthnLevel, IN DWORD dwImpLevel, IN RPC_AUTH_IDENTITY_HANDLE pAuthInfo, IN DWORD dwCapabilities ) { return E_FAIL; } static WINOLEAPI CoSuspendClassObjects( void ) { return E_FAIL; } static WINOLEAPI_(LPVOID) CoTaskMemAlloc( IN SIZE_T cb ) { return NULL; } static WINOLEAPI_(LPVOID) CoTaskMemRealloc( IN LPVOID pv, IN SIZE_T cb ) { return NULL; } static WINOLEAPI_(void) CoTaskMemFree( IN LPVOID pv ) { NOTHING; } static WINOLEAPI_(void) CoUninitialize( void ) { NOTHING; } static WINOLEAPI CoUnmarshalInterface( IN LPSTREAM pStm, IN REFIID riid, OUT LPVOID FAR* ppv ) { return E_FAIL; } static WINOLEAPI CreateClassMoniker( IN REFCLSID rclsid, OUT LPMONIKER FAR* ppmk) { *ppmk = NULL; return E_FAIL; } static WINOLEAPI CreateItemMoniker( IN LPCOLESTR lpszDelim, IN LPCOLESTR lpszItem, OUT LPMONIKER FAR* ppmk) { *ppmk = NULL; return E_FAIL; } static WINOLEAPI CreateStreamOnHGlobal( IN HGLOBAL hGlobal, IN BOOL fDeleteOnRelease, OUT LPSTREAM FAR* ppstm ) { return E_FAIL; } static WINOLEAPI GetRunningObjectTable( IN DWORD reserved, OUT LPRUNNINGOBJECTTABLE FAR* pprot ) { *pprot = NULL; return E_FAIL; } static WINOLEAPI MkParseDisplayName( LPBC pbc, LPCOLESTR szUserName, ULONG FAR *pchEaten, LPMONIKER FAR *ppmk ) { *ppmk = NULL; return E_FAIL; } static WINOLEAPI OleInitialize( IN LPVOID pvReserved ) { return E_FAIL; } static WINOLEAPI OleLoadFromStream( IN LPSTREAM pStm, IN REFIID iidInterface, OUT LPVOID FAR* ppvObj ) { return E_FAIL; } static WINOLEAPI OleSaveToStream( IN LPPERSISTSTREAM pPStm, IN LPSTREAM pStm ) { return E_FAIL; } static WINOLEAPI OleLockRunning( IN LPUNKNOWN pUnknown, IN BOOL fLock, IN BOOL fLastUnlockCloses ) { return E_FAIL; } static WINOLEAPI_(void) OleUninitialize( void ) { NOTHING; } static WINOLEAPI ProgIDFromCLSID( IN REFCLSID clsid, OUT LPOLESTR FAR* lplpszProgID ) { return E_FAIL; } static WINOLEAPI StringFromCLSID( IN REFCLSID rclsid, OUT LPOLESTR FAR* lplpsz ) { return E_FAIL; } static WINOLEAPI WriteClassStm( IN LPSTREAM pStm, IN REFCLSID rclsid ) { return E_FAIL; } static WINOLEAPI CreateDataAdviseHolder( OUT LPDATAADVISEHOLDER FAR* ppDAHolder ) { return E_FAIL; } static WINOLEAPI StgCreateDocfile( IN const OLECHAR FAR* pwcsName, IN DWORD grfMode, IN DWORD reserved, OUT IStorage FAR * FAR *ppstgOpen ) { return E_FAIL; } static WINOLEAPI CreateILockBytesOnHGlobal( IN HGLOBAL hGlobal, IN BOOL fDeleteOnRelease, OUT LPLOCKBYTES FAR* pplkbyt ) { return E_FAIL; } static WINOLEAPI StgCreateDocfileOnILockBytes( IN ILockBytes FAR *plkbyt, IN DWORD grfMode, IN DWORD reserved, OUT IStorage FAR * FAR *ppstgOpen ) { return E_FAIL; } static WINOLEAPI OleQueryCreateFromData( IN LPDATAOBJECT pSrcDataObject ) { return E_FAIL; } static WINOLEAPI OleQueryLinkFromData( IN LPDATAOBJECT pSrcDataObject ) { return E_FAIL; } static WINOLEAPI CreateFileMoniker( IN LPCOLESTR lpszPathName, OUT LPMONIKER FAR* ppmk ) { return E_FAIL; } static WINOLEAPI GetClassFile( IN LPCOLESTR szFilename, OUT CLSID FAR* pclsid ) { return E_FAIL; } static WINOLEAPI StgOpenStorage( IN const OLECHAR FAR* pwcsName, IN IStorage FAR *pstgPriority, IN DWORD grfMode, IN SNB snbExclude, IN DWORD reserved, OUT IStorage FAR * FAR *ppstgOpen ) { return E_FAIL; } static WINOLEAPI_(int) StringFromGUID2( IN REFGUID rguid, OUT LPOLESTR lpsz, IN int cchMax ) { return 0; } static WINOLEAPI CoMarshalInterThreadInterfaceInStream( IN REFIID riid, IN LPUNKNOWN pUnk, OUT LPSTREAM *ppStm ) { return E_FAIL; } static WINOLEAPI CoGetInterfaceAndReleaseStream( IN LPSTREAM pStm, IN REFIID iid, OUT LPVOID FAR* ppv) { return E_FAIL; } static WINOLEAPI DoDragDrop( IN LPDATAOBJECT pDataObj, IN LPDROPSOURCE pDropSource, IN DWORD dwOKEffects, OUT LPDWORD pdwEffect ) { return E_FAIL; } static WINOLEAPI OleGetClipboard( OUT LPDATAOBJECT FAR* ppDataObj ) { return E_FAIL; } static WINOLEAPI OleSetClipboard( IN LPDATAOBJECT pDataObj ) { return E_FAIL; } static WINOLEAPI OleRegEnumVerbs( IN REFCLSID clsid, OUT LPENUMOLEVERB FAR* ppenum ) { return E_FAIL; } static WINOLEAPI PropVariantClear( PROPVARIANT * pvar ) { return E_FAIL; } static WINOLEAPI_(void) ReleaseStgMedium( IN LPSTGMEDIUM pmedium ) { NOTHING; } static WINOLEAPI_(void) CoFreeUnusedLibraries(void) { NOTHING; } static WINOLEAPI RevokeDragDrop( IN HWND hwnd ) { return E_FAIL; } static WINOLEAPI RegisterDragDrop( IN HWND hwnd, IN LPDROPTARGET pDropTarget ) { return E_FAIL; } static WINOLEAPI OleFlushClipboard(void) { return E_FAIL; } static WINOLEAPI CoGetMalloc( IN DWORD dwMemContext, OUT LPMALLOC FAR* ppMalloc ) { return E_FAIL; } static WINOLEAPI OleRegGetMiscStatus( IN REFCLSID clsid, IN DWORD dwAspect, OUT DWORD FAR* pdwStatus ) { return E_FAIL; } static WINOLEAPI OleRegGetUserType( IN REFCLSID clsid, IN DWORD dwFormOfType, OUT LPOLESTR FAR* pszUserType ) { return E_FAIL; } static WINOLEAPI CreateOleAdviseHolder( OUT LPOLEADVISEHOLDER FAR* ppOAHolder ) { return E_FAIL; } static WINOLEAPI OleRun( IN LPUNKNOWN pUnknown ) { return E_FAIL; } static WINOLEAPI FreePropVariantArray( ULONG cVariants, PROPVARIANT * rgvars ) { return E_FAIL; } static WINOLEAPI CreateBindCtx( IN DWORD reserved, OUT LPBC FAR* ppbc ) { return E_FAIL; } static WINOLEAPI StgOpenStorageEx( IN const WCHAR* pwcsName, IN DWORD grfMode, IN DWORD stgfmt, // enum IN DWORD grfAttrs, // reserved IN STGOPTIONS * pStgOptions, IN void * reserved, IN REFIID riid, OUT void ** ppObjectOpen ) { return E_FAIL; } static WINOLEAPI CoGetClassObject( IN REFCLSID rclsid, IN DWORD dwClsContext, IN LPVOID pvReserved, IN REFIID riid, OUT LPVOID FAR* ppv ) { *ppv = NULL; return E_FAIL; } static WINOLEAPI OleDraw( IN LPUNKNOWN pUnknown, IN DWORD dwAspect, IN HDC hdcDraw, IN LPCRECT lprcBounds ) { return E_OUTOFMEMORY; } static WINOLEAPI OleCreateFromData( IN LPDATAOBJECT pSrcDataObj, IN REFIID riid, IN DWORD renderopt, IN LPFORMATETC pFormatEtc, IN LPOLECLIENTSITE pClientSite, IN LPSTORAGE pStg, OUT LPVOID FAR* ppvObj ) { *ppvObj = NULL; return E_FAIL; } static WINOLEAPI OleSetMenuDescriptor( IN HOLEMENU holemenu, IN HWND hwndFrame, IN HWND hwndActiveObject, IN LPOLEINPLACEFRAME lpFrame, IN LPOLEINPLACEACTIVEOBJECT lpActiveObj ) { return E_FAIL; } static WINOLEAPI OleSave( IN LPPERSISTSTORAGE pPS, IN LPSTORAGE pStg, IN BOOL fSameAsLoad ) { return E_FAIL; } static WINOLEAPI CoFileTimeNow( OUT FILETIME FAR* lpFileTime ) { lpFileTime->dwHighDateTime = 0; lpFileTime->dwLowDateTime = GetTickCount(); return S_OK; } static WINOLEAPI_(void) CoFreeLibrary( IN HINSTANCE hInst ) { NOTHING; } static WINOLEAPI CoRegisterMessageFilter( IN LPMESSAGEFILTER lpMessageFilter, OUT LPMESSAGEFILTER FAR* lplpMessageFilter ) { return E_FAIL; } static WINOLEAPI GetHGlobalFromStream( IN LPSTREAM pstm, OUT HGLOBAL FAR* phglobal ) { return E_OUTOFMEMORY; } static WINOLEAPI PropVariantCopy( PROPVARIANT * pvarDest, const PROPVARIANT * pvarSrc ) { return E_FAIL; } static WINOLEAPI CoAllowSetForegroundWindow( IN IUnknown *pUnk, IN LPVOID lpvReserved ) { return E_FAIL; } static WINOLEAPI CoCreateFreeThreadedMarshaler( IN LPUNKNOWN punkOuter, OUT LPUNKNOWN *ppunkMarshal ) { *ppunkMarshal = NULL; return E_FAIL; } static WINOLEAPI CoWaitForMultipleHandles( IN DWORD dwFlags, IN DWORD dwTimeout, IN ULONG cHandles, IN LPHANDLE pHandles, OUT LPDWORD lpdwindex) { return E_FAIL; } static WINOLEAPI StringFromIID( IN REFIID rclsid, OUT LPOLESTR FAR* lplpsz ) { return E_FAIL; } static WINOLEAPI IIDFromString( IN LPOLESTR lpsz, OUT LPIID lpiid ) { return E_FAIL; } // // !! WARNING !! The entries below must be in alphabetical order, and are CASE SENSITIVE (eg lower case comes last!) // DEFINE_PROCNAME_ENTRIES(ole32) { DLPENTRY(CLSIDFromProgID) DLPENTRY(CLSIDFromString) DLPENTRY(CoAllowSetForegroundWindow) DLPENTRY(CoCancelCall) DLPENTRY(CoCreateFreeThreadedMarshaler) DLPENTRY(CoCreateGuid) DLPENTRY(CoCreateInstance) DLPENTRY(CoDisableCallCancellation) DLPENTRY(CoDisconnectObject) DLPENTRY(CoEnableCallCancellation) DLPENTRY(CoFileTimeNow) DLPENTRY(CoFreeLibrary) DLPENTRY(CoFreeUnusedLibraries) DLPENTRY(CoGetClassObject) DLPENTRY(CoGetInterfaceAndReleaseStream) DLPENTRY(CoGetMalloc) DLPENTRY(CoImpersonateClient) DLPENTRY(CoInitialize) DLPENTRY(CoInitializeEx) DLPENTRY(CoInitializeSecurity) DLPENTRY(CoLoadLibrary) DLPENTRY(CoMarshalInterThreadInterfaceInStream) DLPENTRY(CoMarshalInterface) DLPENTRY(CoRegisterClassObject) DLPENTRY(CoRegisterMessageFilter) DLPENTRY(CoReleaseMarshalData) DLPENTRY(CoResumeClassObjects) DLPENTRY(CoRevertToSelf) DLPENTRY(CoRevokeClassObject) DLPENTRY(CoSetProxyBlanket) DLPENTRY(CoSuspendClassObjects) DLPENTRY(CoSwitchCallContext) DLPENTRY(CoTaskMemAlloc) DLPENTRY(CoTaskMemFree) DLPENTRY(CoTaskMemRealloc) DLPENTRY(CoUninitialize) DLPENTRY(CoUnmarshalInterface) DLPENTRY(CoWaitForMultipleHandles) DLPENTRY(CreateBindCtx) DLPENTRY(CreateClassMoniker) DLPENTRY(CreateDataAdviseHolder) DLPENTRY(CreateFileMoniker) DLPENTRY(CreateILockBytesOnHGlobal) DLPENTRY(CreateItemMoniker) DLPENTRY(CreateOleAdviseHolder) DLPENTRY(CreateStreamOnHGlobal) DLPENTRY(DoDragDrop) DLPENTRY(FreePropVariantArray) DLPENTRY(GetClassFile) DLPENTRY(GetHGlobalFromStream) DLPENTRY(GetRunningObjectTable) DLPENTRY(IIDFromString) DLPENTRY(MkParseDisplayName) DLPENTRY(OleCreateFromData) DLPENTRY(OleDraw) DLPENTRY(OleFlushClipboard) DLPENTRY(OleGetClipboard) DLPENTRY(OleInitialize) DLPENTRY(OleLoadFromStream) DLPENTRY(OleLockRunning) DLPENTRY(OleQueryCreateFromData) DLPENTRY(OleQueryLinkFromData) DLPENTRY(OleRegEnumVerbs) DLPENTRY(OleRegGetMiscStatus) DLPENTRY(OleRegGetUserType) DLPENTRY(OleRun) DLPENTRY(OleSave) DLPENTRY(OleSaveToStream) DLPENTRY(OleSetClipboard) DLPENTRY(OleSetMenuDescriptor) DLPENTRY(OleUninitialize) DLPENTRY(ProgIDFromCLSID) DLPENTRY(PropVariantClear) DLPENTRY(PropVariantCopy) DLPENTRY(RegisterDragDrop) DLPENTRY(ReleaseStgMedium) DLPENTRY(RevokeDragDrop) DLPENTRY(StgCreateDocfile) DLPENTRY(StgCreateDocfileOnILockBytes) DLPENTRY(StgOpenStorage) DLPENTRY(StgOpenStorageEx) DLPENTRY(StringFromCLSID) DLPENTRY(StringFromGUID2) DLPENTRY(StringFromIID) DLPENTRY(WriteClassStm) }; DEFINE_PROCNAME_MAP(ole32)
forkstuffs/HSCore
HSCore-config/HSCore-config-path/src/main/java/me/hsgamer/hscore/config/path/LongConfigPath.java
<filename>HSCore-config/HSCore-config-path/src/main/java/me/hsgamer/hscore/config/path/LongConfigPath.java package me.hsgamer.hscore.config.path; import me.hsgamer.hscore.config.BaseConfigPath; public final class LongConfigPath extends BaseConfigPath<Long> { /** * Create a config path * * @param path the path to the value * @param def the default value if it's not found */ public LongConfigPath(String path, Long def) { super(path, def, o -> { try { return Long.parseLong(String.valueOf(o)); } catch (Exception e) { return def; } }); } }
viszi/codes
CodeWars/4kyu/JavaScript/012-range-extraction.js
// https://www.codewars.com/kata/51ba717bb08c1cd60f00002f // A format for expressing an ordered list of integers is to use a comma separated list of either // - individual integers // - or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example "12,13,15-17" // Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format. // solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]); // // returns "-6,-3-1,3-5,7-11,14,15,17-20" function solution(list) { let previous = list[0]; let subRange = []; // store result in array let result = [previous]; for (i = 1; i < list.length; i++) { // get the next number let actual = list[i]; // if it is the next number if (Math.abs(actual - previous) === 1) { // add numbers in a range to an array // during first initialization we have to add previous value too if (subRange.length === 0) { subRange.push(previous); } subRange.push(actual); } else { // if next number breaks a range add the range to result if (subRange.length > 0) { // remove the last element and replace it with correct range result.pop(); // if there is only 2 elements in the subrange add both to the result if (subRange.length === 2) { result.push(subRange[0], subRange[1]); } else { // for more than 2 elements add the ends of the range result.push(`${subRange.shift()}-${subRange.pop()}`) } // reset the subrange subRange = []; } // push the actual number to the result result.push(actual); } previous = actual; // if we reached the last item and we have a subrange then we have to add it if (i === list.length - 1 && subRange.length > 0) { // replace the last element with the subRange data result.pop(); if (subRange.length === 2) { result.push(subRange[0], subRange[1]); } else { result.push(`${subRange.shift()}-${subRange.pop()}`) } } } return result.join(','); } console.log(solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]), " => -6,-3-1,3-5,7-11,14,15,17-20");
isislab-unisa/dmason2.5
src/main/java/it/isislab/dmason/sim/field/network/kway/algo/interfaces/PartitioningAlgorithm.java
<filename>src/main/java/it/isislab/dmason/sim/field/network/kway/algo/interfaces/PartitioningAlgorithm.java<gh_stars>10-100 /** * Copyright 2016 Universita' degli Studi di Salerno 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 it.isislab.dmason.sim.field.network.kway.algo.interfaces; import it.isislab.dmason.annotation.AuthorAnnotation; import java.io.IOException; @AuthorAnnotation( author = {"<NAME>", "<NAME>"}, date = "22/7/2015" ) public interface PartitioningAlgorithm { /** * Executes the partition of a graph using the algorithm specified * by the class which implements this interface. * @throws IOException the exception * @throws InterruptedException the exception * @return the path of the file which describes the partition calculated. */ public String partitioning() throws IOException,InterruptedException; }
jottasantosdev/logica-de-programacao
controle/if_4.js
const nota = 9.3; if (nota >= 9) { console.log('<NAME>!'); console.log('Parabéns!'); } console.log('Fim!');
ds462716/jeecg-boot-master
jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/pd/service/impl/PdStoreroomPatrolServiceImpl.java
package org.jeecg.modules.pd.service.impl; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.shiro.SecurityUtils; import org.jeecg.common.constant.PdConstant; import org.jeecg.common.system.vo.LoginUser; import org.jeecg.modules.pd.entity.PdStoreroomPatrol; import org.jeecg.modules.pd.entity.PdStoreroomPatrolDetail; import org.jeecg.modules.pd.mapper.PdStoreroomPatrolDetailMapper; import org.jeecg.modules.pd.mapper.PdStoreroomPatrolMapper; import org.jeecg.modules.pd.service.IPdStoreroomPatrolService; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.List; import java.util.Collection; /** * @Description: pd_storeroom_patrol * @Author: jiangxz * @Date: 2020-04-07 * @Version: V1.0 */ @Service public class PdStoreroomPatrolServiceImpl extends ServiceImpl<PdStoreroomPatrolMapper, PdStoreroomPatrol> implements IPdStoreroomPatrolService { @Autowired private PdStoreroomPatrolMapper pdStoreroomPatrolMapper; @Autowired private PdStoreroomPatrolDetailMapper pdStoreroomPatrolDetailMapper; @Override public List<PdStoreroomPatrol> selectList(PdStoreroomPatrol pdStoreroomPatrol) { return pdStoreroomPatrolMapper.selectList(pdStoreroomPatrol); } @Override public Page<PdStoreroomPatrol> selectList(Page<PdStoreroomPatrol> pageList, PdStoreroomPatrol pdStoreroomPatrol) { return pageList.setRecords(pdStoreroomPatrolMapper.selectList(pdStoreroomPatrol)); } @Override @Transactional public void saveMain(PdStoreroomPatrol pdStoreroomPatrol, List<PdStoreroomPatrolDetail> pdStoreroomPatrolDetailList) { LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); pdStoreroomPatrol.setPatrolMan(sysUser.getRealname()); pdStoreroomPatrolMapper.insert(pdStoreroomPatrol); Double patrolCount = 0D; //巡查数量 Double passCount = 0D; //合格数量 Double failCount = 0D; //不合格数量 if(pdStoreroomPatrolDetailList!=null && pdStoreroomPatrolDetailList.size()>0) { for(PdStoreroomPatrolDetail entity : pdStoreroomPatrolDetailList) { patrolCount = patrolCount + entity.getStockNum(); if(PdConstant.RESULT_QUALIFIED.equals(entity.getPatrolResult())){ passCount = passCount + entity.getStockNum(); }else if(PdConstant.RESULT_UNQUALIFIED.equals(entity.getPatrolResult())){ failCount = failCount + entity.getStockNum(); } //外键设置 entity.setStoreroomPatrolId(pdStoreroomPatrol.getId()); entity.setId(null); pdStoreroomPatrolDetailMapper.insert(entity); } } pdStoreroomPatrol.setPatrolCount(patrolCount); pdStoreroomPatrol.setPassCount(passCount); pdStoreroomPatrol.setFailCount(failCount); // 更新数量 pdStoreroomPatrolMapper.updateById(pdStoreroomPatrol); } @Override @Transactional public void updateMain(PdStoreroomPatrol pdStoreroomPatrol,List<PdStoreroomPatrolDetail> pdStoreroomPatrolDetailList) { pdStoreroomPatrolMapper.updateById(pdStoreroomPatrol); //1.先删除子表数据 pdStoreroomPatrolDetailMapper.deleteByMainId(pdStoreroomPatrol.getId()); //2.子表数据重新插入 if(pdStoreroomPatrolDetailList!=null && pdStoreroomPatrolDetailList.size()>0) { for(PdStoreroomPatrolDetail entity:pdStoreroomPatrolDetailList) { //外键设置 entity.setStoreroomPatrolId(pdStoreroomPatrol.getId()); pdStoreroomPatrolDetailMapper.insert(entity); } } } @Override @Transactional public void delMain(String id) { pdStoreroomPatrolDetailMapper.deleteByMainId(id); pdStoreroomPatrolMapper.deleteById(id); } @Override @Transactional public void delBatchMain(Collection<? extends Serializable> idList) { for(Serializable id:idList) { pdStoreroomPatrolDetailMapper.deleteByMainId(id.toString()); pdStoreroomPatrolMapper.deleteById(id); } } }
alecnunn/mud
src/refl/System.cpp
// Copyright (c) 2019 <NAME> <EMAIL> // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #include <infra/Cpp20.h> #ifndef MUD_CPP_20 #include <fstream> #include <string> #endif #ifdef MUD_MODULES module mud.refl; #else #include <infra/Vector.h> #include <refl/System.h> #include <refl/Module.h> #include <refl/Class.h> #endif #ifdef _WIN32 #include <windows.h> #define BINARY_EXT ".exe" #define MODULE_EXT ".dll" #else #include <dlfcn.h> #define BINARY_EXT "" #define MODULE_EXT ".so" #endif #ifdef _DEBUG #define BUILD_SUFFIX "_d" #else #define BUILD_SUFFIX "" #endif namespace mud { using string = std::string; void copyfile(const string& source, const string& dest) { std::ifstream file(source, std::ios::binary); std::ofstream destFile(dest, std::ios::binary); destFile << file.rdbuf(); } Module* load_module(cstring path) { string module_path = string(path) + BUILD_SUFFIX + MODULE_EXT; string loaded_path = string(path) + BUILD_SUFFIX + "_loaded" + MODULE_EXT; if(!std::ifstream(module_path, std::ios::binary).good()) { printf("ERROR: Module %s not found\n", module_path.c_str()); return nullptr; } copyfile(module_path, loaded_path); #ifdef _WIN32 HMODULE module_handle = LoadLibraryA(loaded_path.c_str()); #else void* module_handle = dlopen(loaded_path.c_str(), RTLD_NOW); #endif #ifdef _WIN32 GetModule get_module = (GetModule)GetProcAddress(module_handle, "getModule"); #else GetModule get_module = (GetModule)dlsym(module_handle, "getModule"); #endif Module& m = get_module(); m.m_handle = module_handle; m.m_path = module_path.c_str(); return &m; } void unload_module(Module& m) { #ifdef _WIN32 int result = FreeLibrary((HMODULE) m.m_handle); #else int result = dlclose(m.m_handle); #endif UNUSED(result); } void reload_module(Module& m) { #ifdef _WIN32 HANDLE module_file = CreateFile(m.m_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(module_file == INVALID_HANDLE_VALUE) return; uint64_t last_modified; GetFileTime(module_file, NULL, NULL, (FILETIME*)&last_modified); if(m.m_last_modified < last_modified) { // do reload } CloseHandle(module_file); #else UNUSED(m); #endif } FunctionPointer module_function(Module& module, cstring name) { #ifdef _WIN32 return (FunctionPointer)GetProcAddress((HMODULE)module.m_handle, name); #else return (FunctionPointer)dlsym(module.m_handle, name); #endif } System::System() { m_namespaces.reserve(100); } void System::launch_process(cstring path, cstring args) { string binary_path = string(path) + BUILD_SUFFIX + BINARY_EXT; #ifdef _WIN32 STARTUPINFO startupInfo = { sizeof(startupInfo) }; PROCESS_INFORMATION processInfo = {}; string cmd = string(path) + " " + string(args); std::vector<char> mutcmd(cmd.c_str(), cmd.c_str() + cmd.length() + 1); CreateProcess(path, mutcmd.data(), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo); WaitForSingleObject(processInfo.hProcess, INFINITE); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); #else UNUSED(binary_path); UNUSED(args); #endif } void System::load_modules(std::vector<Module*> modules) { for(Module* m : modules) this->load_module(*m); } bool System::has_module(Module& m) { return vector_has(m_modules, &m); } Module* System::open_module(cstring path) { return mud::load_module(path); } void System::load_module(Module& m) { if(vector_has(m_modules, &m)) return; m_modules.push_back(&m); for(Module* dep : m.m_deps) load_module(*dep); for(Type* type : m.m_types) m_types.push_back(type); for(Function* function : m.m_functions) m_functions.push_back(function); } void System::unload_module(Module& m) { vector_remove(m_modules, &m); for(Type* type : m.m_types) vector_remove(m_types, type); for(Function* function : m.m_functions) vector_remove(m_functions, function); mud::unload_module(m); } Module& System::reload_module(Module& m) { cstring path = m.m_path; this->unload_module(m); Module& reloaded = *this->open_module(path); this->load_module(reloaded); return reloaded; } Type* System::find_type(cstring name) { for(Type* type : m_types) if(strcmp(type->m_name, name) == 0) return type; return nullptr; } Function* System::find_function(cstring name) { for(Function* function : m_functions) if(strcmp(function->m_name, name) == 0) return function; return nullptr; } Function* System::find_function(cstring nemespace, cstring name) { for(Function* function : m_functions) if(function->m_namespace->m_name == string(nemespace) && function->m_name == string(name)) return function; return nullptr; } Function& System::function(FunctionPointer identity) { for(Function* func : m_functions) if(func->m_identity == identity) { return *func; } printf("ERROR: retrieving function\n"); return *m_functions[0]; } std::vector<cstring> System::meta_symbols() { std::vector<cstring> symbols; for(Function* function : System::instance().m_functions) symbols.push_back(function->m_name); for(Type* type : System::instance().m_types) symbols.push_back(type->m_name); return symbols; } void System::dump_meta_info() { for(Function* function : System::instance().m_functions) printf("INFO: Meta function %s\n", function->m_name); for(Type* type : System::instance().m_types) { printf("INFO: Meta type %s\n", type->m_name); if(!g_class[type->m_id]) continue; for(Member& member : cls(*type).m_members) if(member.m_object_type == type) printf(" Meta member %s::%s\n", member.m_object_type->m_name, member.m_name); for(Method& method : cls(*type).m_methods) if(method.m_object_type == type) printf(" Meta method %s::%s\n", method.m_object_type->m_name, method.m_name); for(Static& static_member : cls(*type).m_static_members) printf(" Meta static member %s::%s\n", static_member.m_value.m_type->m_name, static_member.m_name); } } void System::dump_memory_usage() { printf("LOG: memory usage\n"); printf("-----------------\n"); for(Type* type : m_types) { if(type->m_debug_count == 0) continue; printf("Type : %s\n", type->m_name); printf(" ----- Objects : %zu\n", type->m_debug_count); printf(" ----- Memory : %zu\n", type->m_debug_memory); } } bool compare(const std::vector<cstring>& first, const std::vector<cstring>& second) { if(first.size() != second.size()) return false; for(size_t i = 0; i < first.size(); ++i) if(strcmp(first[i], second[i]) != 0) return false; return true; } Namespace& System::get_namespace(std::vector<cstring> path) { for(Namespace& location : m_namespaces) if(compare(location.m_path, path)) { return location; } Namespace* parent = nullptr; cstring name = ""; if(!path.empty()) { name = vector_pop(path); parent = &namspc(path); } m_namespaces.push_back(Namespace{ name, parent }); return m_namespaces.back(); } }
JavierV8/MERN-E-commerce
client/src/components/orders/OrderDetails.js
import React from 'react'; import PropTypes from 'prop-types'; import { Progress } from 'reactstrap'; import OrderItems from './OrderItems'; const OrderDetails = props => { const { boxToggle, orderInfo } = props; const { DeliveryAddress, OrderDate, DeliveryTime, SubTotal, DeliveryFee, Total, products, } = orderInfo; return ( <div className="orders-orderDetails" id="prueba"> <div className="orders-orderDetails-up" id="prueba2"> <div className="orders-orderDetails-title"> <h4>Order Details</h4> <button onClick={boxToggle} type="button"> X </button> </div> <div className="orders-delivery-info"> <div className="orders-delivery-info-1"> <div> <p>Delivery Address:</p> <p>Order Date: </p> <p>Delivery Time: </p> </div> <div> <p>{DeliveryAddress}</p> <p>{OrderDate}</p> <p>{DeliveryTime}</p> </div> </div> <div className="orders-delivery-info-2"> <div> <p>Sub Total</p> <p>Delivery Fee</p> <p>Total</p> </div> <div> <p>{SubTotal}</p> <p>{DeliveryFee}</p> <p>{Total}</p> </div> </div> </div> <div className="orders-deliveryStatus"> <div className="orders-steps"> <div className="orders-circle orders-ticked"> <img src={ process.env.PUBLIC_URL + 'images/tick2.png' } className="orders-tick" alt="img" /> </div> <div className="orders-circle orders-ticked"> <img src={ process.env.PUBLIC_URL + 'images/tick2.png' } className="orders-tick" alt="img" /> </div> <div className="orders-circle">3</div> </div> <Progress value={50} className="orders-progress" /> <div className="orders-steps"> <p>Order Recived</p> <p>Order On The Way</p> <p>Order Delivered</p> </div> </div> </div> <div className="orders-orderDetails-down" id="prueba3"> <OrderItems products={products} /> </div> </div> ); }; OrderDetails.propTypes = { boxToggle: PropTypes.func.isRequired, // eslint-disable-next-line react/forbid-prop-types orderInfo: PropTypes.object.isRequired, }; export default OrderDetails;
baozongzi/test
public/assets/addons/filemanager/scripts/CodeMirror/src/util/browser.js
// Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. let userAgent = navigator.userAgent let platform = navigator.platform export let gecko = /gecko\/\d/i.test(userAgent) let ie_upto10 = /MSIE \d/.test(userAgent) let ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) export let ie = ie_upto10 || ie_11up export let ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]) export let webkit = /WebKit\//.test(userAgent) let qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) export let chrome = /Chrome\//.test(userAgent) export let presto = /Opera\//.test(userAgent) export let safari = /Apple Computer/.test(navigator.vendor) export let mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) export let phantom = /PhantomJS/.test(userAgent) export let ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) // This is woefully incomplete. Suggestions for alternative methods welcome. export let mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) export let mac = ios || /Mac/.test(platform) export let chromeOS = /\bCrOS\b/.test(userAgent) export let windows = /win/i.test(platform) let presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) if (presto_version) presto_version = Number(presto_version[1]) if (presto_version && presto_version >= 15) { presto = false; webkit = true } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X export let flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) export let captureRightClick = gecko || (ie && ie_version >= 9)
divyarya/ground-android
gnd/src/main/java/com/google/android/gnd/ui/offlinebasemap/OfflineBaseMapsViewModel.java
/* * Copyright 2020 Google LLC * * 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 * * https://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.google.android.gnd.ui.offlinebasemap; import android.view.View; import androidx.lifecycle.LiveData; import androidx.lifecycle.LiveDataReactiveStreams; import com.google.android.gnd.model.basemap.OfflineBaseMap; import com.google.android.gnd.repository.OfflineBaseMapRepository; import com.google.android.gnd.ui.common.AbstractViewModel; import com.google.android.gnd.ui.common.Navigator; import com.google.common.collect.ImmutableList; import io.reactivex.Flowable; import javax.inject.Inject; import timber.log.Timber; /** * View model for the offline area manager fragment. Handles the current list of downloaded areas. */ public class OfflineBaseMapsViewModel extends AbstractViewModel { private final LiveData<ImmutableList<OfflineBaseMap>> offlineAreas; private final LiveData<Integer> noAreasMessageVisibility; private final Navigator navigator; @Inject OfflineBaseMapsViewModel(Navigator navigator, OfflineBaseMapRepository offlineBaseMapRepository) { this.navigator = navigator; Flowable<ImmutableList<OfflineBaseMap>> offlineAreas = offlineBaseMapRepository .getOfflineAreasOnceAndStream() .doOnError( throwable -> Timber.e( throwable, "Unexpected error accessing offline basemaps in the local store.")) .onErrorReturnItem(ImmutableList.of()); this.offlineAreas = LiveDataReactiveStreams.fromPublisher(offlineAreas); this.noAreasMessageVisibility = LiveDataReactiveStreams.fromPublisher( offlineAreas.map(baseMaps -> baseMaps.isEmpty() ? View.VISIBLE : View.GONE)); } /** Navigate to the offline area selector UI from the offline basemaps UI. */ public void showOfflineAreaSelector() { navigator.navigate(OfflineBaseMapsFragmentDirections.showOfflineAreaSelector()); } /** * Returns the current list of downloaded offline basemaps available for viewing. If an unexpected * error accessing the local store is encountered, emits an empty list, circumventing the error. */ LiveData<ImmutableList<OfflineBaseMap>> getOfflineAreas() { return offlineAreas; } /** * Returns the visibility of a "no area" message based on the current number of available offline * basemaps. */ public LiveData<Integer> getNoAreasMessageVisibility() { return noAreasMessageVisibility; } }
takanori-ugai/smile
core/src/main/java/smile/anomaly/SVM.java
/* * Copyright (c) 2010-2021 <NAME>. All rights reserved. * * Smile 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. * * Smile 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 Smile. If not, see <https://www.gnu.org/licenses/>. */ package smile.anomaly; import smile.base.svm.KernelMachine; import smile.base.svm.OCSVM; import smile.math.kernel.MercerKernel; /** * One-class support vector machines for novelty detection. * One-class SVM relies on identifying the smallest hypersphere * consisting of all the data points. Therefore, it is sensitive to outliers. * If the training data is not contaminated by outliers, the model is best * suited for novelty detection. * * <h2>References</h2> * <ol> * <li><NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. Estimating the support of a high-dimensional distribution. Neural Computation, 2001.</li> * <li><NAME> and <NAME>. A Fast Learning Algorithm for One-Class Support Vector Machine. ICNC 2007.</li> * </ol> * * @author <NAME> */ public class SVM<T> extends KernelMachine<T> { /** * Constructor. * @param kernel Kernel function. * @param vectors The support vectors. * @param weight The weights of instances. * @param b The intercept; */ public SVM(MercerKernel<T> kernel, T[] vectors, double[] weight, double b) { super(kernel, vectors, weight, b); } /** * Fits an one-class SVM. * @param x training samples. * @param kernel the kernel function. * @param <T> the data type. * @return the model. */ public static <T> SVM<T> fit(T[] x, MercerKernel<T> kernel) { return fit(x, kernel, 0.5, 1E-3); } /** * Fits an one-class SVM. * @param x training samples. * @param kernel the kernel function. * @param nu the parameter sets an upper bound on the fraction of outliers * (training examples regarded out-of-class) and it is a lower * bound on the number of training examples used as Support Vector. * @param tol the tolerance of convergence test. * @param <T> the data type. * @return the model. */ public static <T> SVM<T> fit(T[] x, MercerKernel<T> kernel, double nu, double tol) { if (nu <= 0 || nu > 1) { throw new IllegalArgumentException("Invalid nu: " + nu); } if (tol <= 0) { throw new IllegalArgumentException("Invalid tol: " + tol); } OCSVM<T> svm = new OCSVM<>(kernel, nu, tol); KernelMachine<T> model = svm.fit(x); return new SVM<>(model.kernel(), model.vectors(), model.weights(), model.intercept()); } }
bentech/tquery
plugins/datguituner/tquery.datguituner.js
/** * * ok now you get something which is cool for interactive tunning * * #### Possible enhancement - object3d picking to support THREE.Vector3 property * * use object3d picking to select the material you need to tune * * good for material * * so either you do lights, or you do material or you pick the object you like * * #### Possible enhancement - save data and/or push that back in source * * now how to push back those value in the source ? * * is it possible to save in localStorage or so * * #### various possibilities * * may be a very nice bookmarklet * * add shaddow parameters in lights */ tQuery.registerStatic('DatguiTuner', function(opts){ // handle parameters polymorphism if( typeof(opts) === 'string' ) opts = { selector: opts }; // copy parameters opts = tQuery.extend(opts, {}); var gui = opts.gui || new dat.GUI(); var selector = opts.selector || console.assert(false, "selector opts is required.") // process every element tQuery(opts.selector).each(function(element){ if( element instanceof THREE.Light ){ addLightFolder(gui, element) }else if( element instanceof THREE.Material ){ addMaterialFolder(gui, element) } }); // return this for chained UI return this; /** * add a dat.gui folder for a light */ function addLightFolder(gui, light){ // sanity check console.assert( light instanceof THREE.Light ); // handle each type of lights if( light instanceof THREE.AmbientLight ){ var folder = gui.addFolder('AmbientLight-'+light.id); addColor(folder, light, 'color'); }else if( light instanceof THREE.DirectionalLight ){ var folder = gui.addFolder('DirectionalLight-'+light.id); addColor(folder, light, 'color'); folder.add(light, 'intensity'); }else if( light instanceof THREE.PointLight ){ var folder = gui.addFolder('PointLight-'+light.id); addColor(folder, light, 'color'); folder.add(light, 'intensity'); folder.add(light, 'distance'); }else if( light instanceof THREE.SpotLight ){ var folder = gui.addFolder('SpotLight-'+light.id); addColor(folder, light, 'color'); folder.add(light, 'intensity'); folder.add(light, 'distance'); folder.add(light, 'angle'); folder.add(light, 'exponent'); }else{ console.log('unknown type of light', light) } return folder; } /** * add a dat.gui folder for a material */ function addMaterialFolder(gui, material){ // sanity check console.assert( material instanceof THREE.Material); // handle type of material if( material instanceof THREE.MeshNormalMaterial ){ var folder = gui.addFolder('MeshNormalMaterial'+material.id); addShading(folder, material); }else if( material instanceof THREE.MeshBasicMaterial ){ var folder = gui.addFolder('MeshBasicMaterial'+material.id); addColor(folder, material, 'color'); addShading(folder, material); }else if( material instanceof THREE.MeshLambertMaterial ){ var folder = gui.addFolder('MeshLambertMaterial'+material.id); addColor(folder, material, 'color'); addColor(folder, material, 'ambient'); addColor(folder, material, 'emissive'); addShading(folder, material); }else if( material instanceof THREE.MeshPhongMaterial ){ var folder = gui.addFolder('MeshPhongMaterial'+material.id); addColor(folder, material, 'color'); addColor(folder, material, 'ambient'); addColor(folder, material, 'emissive'); addColor(folder, material, 'specular'); folder.add(material, 'shininess') folder.add(material, 'metal'); folder.add(material, 'perPixel') addShading(folder, material); }else console.warn('unhandled material') // by default, reinit the material material.needsUpdate = true; return folder; } /** * add a shading property */ function addShading(folder, material){ console.assert(material instanceof THREE.Material) folder.add(material, 'shading', { NoShading : THREE.NoShading, FlatShading : THREE.FlatShading, SmoothShading : THREE.SmoothShading }).onChange(function(value){ // the value is notified as a string... yet another dat.gui bug material.shading = parseInt(value); }); } /** * add a color property */ function addColor(folder, object, property){ var color = object[property]; console.assert( color instanceof THREE.Color ); // create a color that is understood by dat.gui var tmp = { color : { r : color.r * 255, g : color.g * 255, b : color.b * 255 }}; folder.addColor(tmp, 'color').onChange(function(value){ // workaround dat.gui bugs // sometime, not all the time, dat.gui report a string in css format. reason is unknown if( typeof(tmp.color) === 'string' ){ var colorHex = parseInt(tmp.color.substr(1), 16) tmp.color = { r : (colorHex >> 16) & 255, g : (colorHex >> 8) & 255, b : (colorHex >> 0) & 255 }; } color.r = tmp.color.r / 255; color.g = tmp.color.g / 255; color.b = tmp.color.b / 255; }).name(property); } });
gravel-st/gravel
src/main/java/st/gravel/support/compiler/ast/SystemMapping.java
<reponame>gravel-st/gravel<gh_stars>1-10 package st.gravel.support.compiler.ast; /* This file is automatically generated from typed smalltalk source. Do not edit by hand. (C) AG5.com */ import java.math.BigInteger; import st.gravel.support.jvm.NonLocalReturn; import st.gravel.support.compiler.ast.AbstractMapping; import st.gravel.support.compiler.ast.AbstractMapping.AbstractMapping_Factory; import st.gravel.support.compiler.ast.SystemNode; import st.gravel.support.compiler.ast.SystemMappingCompilerTools; import java.util.Map; import st.gravel.support.compiler.ast.ClassMapping; import st.gravel.support.compiler.ast.Reference; import st.gravel.support.compiler.ast.AbstractClassMapping; import st.gravel.support.compiler.ast.AbsoluteReference; import st.gravel.support.compiler.ast.SelectorConverter; import st.gravel.support.compiler.ast.SystemDefinitionNode; import java.util.Set; import st.gravel.support.compiler.ast.SystemDiff; import st.gravel.support.compiler.ast.SystemMappingUpdater; import st.gravel.support.compiler.ast.ClassDiff; import java.util.HashMap; import java.util.HashSet; import st.gravel.support.compiler.ast.SharedDeclarationNode; import st.gravel.support.compiler.ast.Node; import st.gravel.support.compiler.jvm.JVMClass; import st.gravel.support.compiler.jvm.JVMDefinedObjectType; import st.gravel.support.compiler.ast.BlockNode; import st.gravel.support.compiler.jvm.BlockInnerClass; import st.gravel.support.compiler.jvm.JVMClassCompiler; import st.gravel.support.compiler.ast.IntermediateNodeRewriter; import st.gravel.support.compiler.ast.NonLocalTempWritesToHolderConverter; import st.gravel.support.compiler.ast.VariableAccessToFieldAccessConverter; import st.gravel.support.compiler.ast.VariableDeclarationNode; import st.gravel.support.compiler.ast.NilLiteralNode; import st.gravel.support.compiler.jvm.JVMVariable; import st.gravel.support.compiler.ast.Parser; import st.gravel.support.compiler.ast.MethodNode; import st.gravel.support.compiler.jvm.JVMNonPrimitiveType; import st.gravel.support.compiler.ast.ClassDescriptionNode; import st.gravel.support.compiler.ast.ClassNode; import st.gravel.support.compiler.ast.Expression; import java.util.Date; import st.gravel.support.compiler.ast.AbstractMethodMapping; import st.gravel.support.compiler.ast.MethodMapping; import st.gravel.support.compiler.ast.NamespaceNode; import java.util.Map; import java.util.Map.*; import st.gravel.support.compiler.ast.AnonymousMethodMapping; import st.gravel.support.compiler.ast.EmptyTraitUsageNode; import st.gravel.support.compiler.ast.IdentityClassPartMapping; import st.gravel.support.compiler.ast.ExtensionClassPartMapping; import st.gravel.support.compiler.ast.InstVarMapping; import st.gravel.support.compiler.ast.PackageNodeMerger; public class SystemMapping extends AbstractMapping implements Cloneable { public static SystemMapping_Factory factory = new SystemMapping_Factory(); Map<Class, ClassMapping> _classMappingsByJavaClass; Map<Reference, AbstractClassMapping> _classMappingsByReference; SystemMappingCompilerTools _compilerTools; ClassMapping _nilClassMapping; SelectorConverter _selectorConverter; Map<AbsoluteReference, st.gravel.support.jvm.runtime.AlmostFinalValue> _singletonHolders; Map<Reference, java.util.Set<AbstractClassMapping>> _subclassMappingsCache; SystemDefinitionNode _systemDefinitionNode; SystemNode _systemNode; public static class SystemMapping_Factory extends AbstractMapping_Factory { public SystemMapping basicNew() { SystemMapping newInstance = new SystemMapping(); newInstance.initialize(); return newInstance; } public SystemMapping systemNode_compilerTools_(final SystemNode _aSystemNode, final SystemMappingCompilerTools _aMockSystemMappingCompilerTools) { return ((SystemMapping) this.basicNew().initializeSystemNode_compilerTools_(_aSystemNode, _aMockSystemMappingCompilerTools)); } } static public SystemMapping _systemNode_compilerTools_(Object receiver, final SystemNode _aSystemNode, final SystemMappingCompilerTools _aMockSystemMappingCompilerTools) { return factory.systemNode_compilerTools_(_aSystemNode, _aMockSystemMappingCompilerTools); } public ClassMapping addClassMapping_(final ClassMapping _aClassMapping) { final Class _identityClass; _identityClass = _aClassMapping.identityClass(); if (_identityClass == null) { st.gravel.support.jvm.ObjectExtensions.assert_(SystemMapping.this, _aClassMapping.classNode().isNilClass()); _nilClassMapping = _aClassMapping; } else { _classMappingsByJavaClass.put(_identityClass, _aClassMapping); } _classMappingsByReference.put(_aClassMapping.classNode().reference(), _aClassMapping); _systemNode = _systemNode.withClassDescriptionNode_(_aClassMapping.classNode()); this.resetCache(); return _aClassMapping; } public SystemMapping applyDiff_(final SystemDiff _aSystemDiff) { final SystemMappingUpdater[] _updater; _updater = new SystemMappingUpdater[1]; _updater[0] = this.newSystemMappingUpdater(); for (final ClassDiff _each : _aSystemDiff.classDiffs()) { _updater[0].visit_(_each); } _updater[0].setNamespaceNodes_(_aSystemDiff.namespaces()); _updater[0].link(); return this; } public ClassMapping bestClassMappingFor_(final Class _receiverClass) { final ClassMapping[] _best; _best = new ClassMapping[1]; _best[0] = null; this.concreteClassMappingsDo_(new st.gravel.support.jvm.Block1<Object, ClassMapping>() { @Override public Object value_(final ClassMapping _cm) { if (_compilerTools.isAssignable_from_(_cm.identityClass(), _receiverClass)) { if (_best[0] == null) { return _best[0] = _cm; } else { if (_compilerTools.isAssignable_from_(_best[0].identityClass(), _cm.identityClass())) { return _best[0] = _cm; } } } return SystemMapping.this; } }); return _best[0]; } public SystemMapping buildSubclassMappingsCache() { _subclassMappingsCache = new java.util.HashMap<Reference, java.util.Set<AbstractClassMapping>>(); for (final AbstractClassMapping _each : _classMappingsByReference.values()) { final Reference _scr; _scr = _each.superclassReference(); if (_scr != null) { java.util.Set<AbstractClassMapping> _temp1 = _subclassMappingsCache.get(_scr); if (_temp1 == null) { java.util.Set<AbstractClassMapping> _temp2 = new java.util.HashSet(); _subclassMappingsCache.put(_scr, _temp2); _temp1 = _temp2; } _temp1.add(_each); } } return this; } public ClassMapping classMappingAtJavaClass_ifAbsent_(final Class _aClass, final st.gravel.support.jvm.Block0<ClassMapping> _absentBlock) { if (_aClass == null) { return _nilClassMapping; } return st.gravel.support.jvm.DictionaryExtensions.at_ifAbsent_(_classMappingsByJavaClass, _aClass, _absentBlock); } public AbstractClassMapping classMappingAtReference_(final Reference _aReference) { return this.classMappingAtReference_ifAbsent_(_aReference, ((st.gravel.support.jvm.Block0<AbstractClassMapping>) (new st.gravel.support.jvm.Block0<AbstractClassMapping>() { @Override public AbstractClassMapping value() { throw new RuntimeException("Cannot find: " + _aReference.toString()); } }))); } public AbstractClassMapping classMappingAtReference_ifAbsent_(final Reference _aReference, final st.gravel.support.jvm.Block0<AbstractClassMapping> _absentBlock) { return st.gravel.support.jvm.DictionaryExtensions.at_ifAbsent_(_classMappingsByReference, _aReference, _absentBlock); } public ClassMapping classMappingForJavaClass_(final Class _receiverClass) { return this.classMappingAtJavaClass_ifAbsent_(_receiverClass, ((st.gravel.support.jvm.Block0<ClassMapping>) (new st.gravel.support.jvm.Block0<ClassMapping>() { @Override public ClassMapping value() { final ClassMapping _newClassMapping; _newClassMapping = SystemMapping.this.newClassMappingForJavaClass_(_receiverClass); _classMappingsByJavaClass.put(_receiverClass, _newClassMapping); return (ClassMapping) _newClassMapping; } }))); } public SystemMapping classMappingsDo_(final st.gravel.support.jvm.Block1<Object, AbstractClassMapping> _aBlock) { for (final AbstractClassMapping _temp1 : _classMappingsByReference.values()) { _aBlock.value_(_temp1); } return this; } public st.gravel.support.jvm.runtime.AlmostFinalValue classSharedSingletonHolderAtReference_ifAbsent_(final AbsoluteReference _reference, final st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue> _aBlock) { final Object _temp2 = new Object(); try { st.gravel.support.jvm.runtime.AlmostFinalValue _temp1 = _singletonHolders.get(_reference); if (_temp1 == null) { _temp1 = ((st.gravel.support.jvm.runtime.AlmostFinalValue) st.gravel.support.jvm.DictionaryExtensions.at_ifAbsent_(_singletonHolders, _reference.namespace().namespace().$slash$(_reference.name()), ((st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue>) (new st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue>() { @Override public st.gravel.support.jvm.runtime.AlmostFinalValue value() { final AbstractClassMapping _cm; final AbsoluteReference _superclassReference; final SharedDeclarationNode _sharedVariable; _cm = ((AbstractClassMapping) st.gravel.support.jvm.DictionaryExtensions.at_ifAbsent_(_classMappingsByReference, _reference.namespace(), ((st.gravel.support.jvm.Block0<AbstractClassMapping>) (new st.gravel.support.jvm.Block0<AbstractClassMapping>() { @Override public AbstractClassMapping value() { throw new NonLocalReturn(_aBlock.value(), _temp2); } })))); _sharedVariable = _cm.classNode().meta().sharedVariableAt_ifAbsent_(_reference.name().asString(), new st.gravel.support.jvm.Block0<SharedDeclarationNode>() { @Override public SharedDeclarationNode value() { return (SharedDeclarationNode) null; } }); if (_sharedVariable != null) { throw new RuntimeException("Shared not initialized: " + _reference.toString()); } _superclassReference = ((AbsoluteReference) _cm.superclassReference()); if (_superclassReference == null) { throw new NonLocalReturn(_aBlock.value(), _temp2); } return (st.gravel.support.jvm.runtime.AlmostFinalValue) SystemMapping.this.classSharedSingletonHolderAtReference_ifAbsent_(_superclassReference.$slash$(_reference.name()), _aBlock); } })))); } return ((st.gravel.support.jvm.runtime.AlmostFinalValue) _temp1); } catch (NonLocalReturn nlr) { if (nlr.marker == _temp2) { return (st.gravel.support.jvm.runtime.AlmostFinalValue) nlr.returnValue; } else { throw nlr; } } } public Class compileAndWriteExpression_reference_(final Node _anExpression, final Reference _aReference) { final JVMClass[] _jvmClasses; _jvmClasses = this.compileExpression_reference_(_anExpression, _aReference); return this.compileJVMClasses_(_jvmClasses); } public JVMClass[] compileExpressionSource_(final String _source) { return this.compileExpression_reference_(Parser.factory.parseExpression_(_source), Reference.factory.value_("st.gravel.lang.UndefinedObject")); } public JVMClass[] compileExpression_reference_(final Node _anExpression, final Reference _aReference) { final JVMDefinedObjectType _ownerType; final BlockNode _fieldAccessed; final BlockInnerClass _aBlockInnerClass; final BlockNode _intermediate; final BlockNode _holderized; final JVMClassCompiler _jvmClassCompiler; final JVMClass _blockClass; _intermediate = ((BlockNode) IntermediateNodeRewriter.factory.visit_(BlockNode.factory.expression_(_anExpression))); _holderized = ((BlockNode) NonLocalTempWritesToHolderConverter.factory.visit_(_intermediate)); _fieldAccessed = ((BlockNode) VariableAccessToFieldAccessConverter.factory.instVars_owner_ownerReference_(new VariableDeclarationNode[] {}, NilLiteralNode.factory.basicNew(), _aReference).visit_(_holderized)); _ownerType = JVMDefinedObjectType.factory.dottedClassName_("Expression$" + _compilerTools.nextExtensionPostfix()); _aBlockInnerClass = BlockInnerClass.factory.ownerType_blockNode_copiedVariables_(_ownerType, _fieldAccessed, new JVMVariable[] {}); _jvmClassCompiler = JVMClassCompiler.factory.classDescriptionNode_systemNode_systemMappingUpdater_isStatic_(null, _systemNode, this.newSystemMappingUpdater(), false); _jvmClassCompiler.ownerType_(JVMDefinedObjectType.factory.dottedClassName_("ExpressionContainer$" + _compilerTools.nextExtensionPostfix())); _blockClass = _jvmClassCompiler.compileBlockNoAdd_(_aBlockInnerClass); return _jvmClassCompiler.withContainerAndExtraClasses_(_blockClass); } public Class compileInlinedMethod_selfType_allowBlockInlining_(final MethodNode _aMethodNode, final JVMNonPrimitiveType _selfType, final boolean _allowBlockInlining) { final JVMClassCompiler _jvmClassCompiler; final JVMClass _inlinedMethodClass; final JVMClass[] _jvmClasses; _jvmClassCompiler = JVMClassCompiler.factory.classDescriptionNode_systemNode_systemMappingUpdater_isStatic_(null, _systemNode, this.newSystemMappingUpdater(), true); _jvmClassCompiler.allowBlockInlining_(_allowBlockInlining); _jvmClassCompiler.selfType_(_selfType); _jvmClassCompiler.superType_(JVMDefinedObjectType.factory.object()); _jvmClassCompiler.ownerType_(JVMDefinedObjectType.factory.dottedClassName_("InlinedMethod$" + _compilerTools.nextExtensionPostfix())); _inlinedMethodClass = _jvmClassCompiler.compileInlinedMethod_(_aMethodNode); _jvmClasses = st.gravel.support.jvm.ArrayExtensions.copyWith_(_jvmClassCompiler.extraClasses(), _inlinedMethodClass); return this.compileJVMClasses_(_jvmClasses); } public Class compileJVMClasses_(final JVMClass[] _jvmClasses) { final Class[] _last; _last = new Class[1]; _last[0] = null; for (final JVMClass _jvmClass : _jvmClasses) { _last[0] = _compilerTools.writeClass_(_jvmClass); } for (final JVMClass _jvmClass : _jvmClasses) { _compilerTools.runAstInit_(_jvmClass); } return _last[0]; } public SystemMappingCompilerTools compilerTools() { return _compilerTools; } public SystemMapping concreteClassMappingsDo_(final st.gravel.support.jvm.Block1<Object, ClassMapping> _aBlock) { for (final AbstractClassMapping _acm : _classMappingsByReference.values()) { _aBlock.value_(((ClassMapping) _acm)); } return this; } public SystemMapping copy() { try { SystemMapping _temp1 = (SystemMapping) this.clone(); _temp1.postCopy(); return _temp1; } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public ClassDescriptionNode definitionClassNodeAt_ifAbsent_(final Reference _reference, final st.gravel.support.jvm.Block0<ClassDescriptionNode> _aBlock) { final Object _temp1 = new Object(); try { if (_reference.isMeta()) { return ((ClassNode) SystemMapping.this.definitionClassNodeAt_ifAbsent_(_reference.nonmeta(), ((st.gravel.support.jvm.Block0<ClassDescriptionNode>) (new st.gravel.support.jvm.Block0<ClassDescriptionNode>() { @Override public ClassDescriptionNode value() { throw new NonLocalReturn(_aBlock.value(), _temp1); } })))).metaclassNode(); } return _systemDefinitionNode.classNodeAt_ifAbsent_(_reference, ((st.gravel.support.jvm.Block0<ClassNode>) (new st.gravel.support.jvm.Block0<ClassNode>() { @Override public ClassNode value() { throw new NonLocalReturn(_aBlock.value(), _temp1); } }))); } catch (NonLocalReturn nlr) { if (nlr.marker == _temp1) { return (ClassDescriptionNode) nlr.returnValue; } else { throw nlr; } } } public ClassDescriptionNode definitionOrObsoleteClassNodeAt_(final Reference _reference) { return this.definitionOrObsoleteClassNodeAt_ifAbsent_(_reference, ((st.gravel.support.jvm.Block0<ClassDescriptionNode>) (new st.gravel.support.jvm.Block0<ClassDescriptionNode>() { @Override public ClassDescriptionNode value() { throw new RuntimeException("Cannot find: " + _reference.toString()); } }))); } public ClassDescriptionNode definitionOrObsoleteClassNodeAt_ifAbsent_(final Reference _reference, final st.gravel.support.jvm.Block0<ClassDescriptionNode> _aBlock) { return this.definitionClassNodeAt_ifAbsent_(_reference, ((st.gravel.support.jvm.Block0<ClassDescriptionNode>) (new st.gravel.support.jvm.Block0<ClassDescriptionNode>() { @Override public ClassDescriptionNode value() { return (ClassDescriptionNode) SystemMapping.this.obsoleteClassNodeAt_ifAbsent_(_reference, ((st.gravel.support.jvm.Block0<ClassDescriptionNode>) (new st.gravel.support.jvm.Block0<ClassDescriptionNode>() { @Override public ClassDescriptionNode value() { throw new RuntimeException("Cannot find: " + _reference.toString()); } }))); } }))); } public Object evaluateExpression_reference_(final Expression _anExpression, final AbsoluteReference _aReference) { final Class _cl; _cl = this.compileAndWriteExpression_reference_(_anExpression, _aReference); return _compilerTools.evaluateBlock0Class_(_cl); } public SystemMapping_Factory factory() { return factory; } @Override public SystemMapping initialize() { _classMappingsByJavaClass = new java.util.HashMap<Class, ClassMapping>(); _classMappingsByReference = new java.util.HashMap<Reference, AbstractClassMapping>(); _singletonHolders = new java.util.HashMap<AbsoluteReference, st.gravel.support.jvm.runtime.AlmostFinalValue>(); _selectorConverter = SelectorConverter.factory.basicNew(); return this; } public SystemMapping initializeSystemNode_compilerTools_(final SystemNode _aSystemNode, final SystemMappingCompilerTools _aMockSystemMappingCompilerTools) { _systemNode = _aSystemNode; _compilerTools = _aMockSystemMappingCompilerTools; this.initialize(); return this; } public SystemMapping log_(final String _aString) { return this; } public SystemMapping log_while_(final String _aString, final st.gravel.support.jvm.Block0<Object> _aBlock) { final int _ms; this.log_(_aString + "..."); long _temp1 = new Date().getTime(); _aBlock.value(); long _temp2 = new Date().getTime(); _ms = (int) (_temp2 - _temp1); this.log_(_aString + " Done in " + "" + _ms + " ms"); return this; } public java.lang.invoke.MethodHandle methodHandleForNil_(final String _methodName) { final st.gravel.core.Symbol _sel; final ClassMapping _classMapping; _classMapping = this.nilClassMapping(); _sel = _selectorConverter.functionNameAsSelector_(_methodName); return this.methodHandleFrom_selector_(_classMapping, _sel); } public java.lang.invoke.MethodHandle methodHandleFor_methodName_(final Class _receiverClass, final String _methodName) { final st.gravel.core.Symbol _sel; final ClassMapping _classMapping; _classMapping = this.classMappingForJavaClass_(_receiverClass); _sel = _selectorConverter.functionNameAsSelector_(_methodName); return this.methodHandleFrom_selector_(_classMapping, _sel); } public java.lang.invoke.MethodHandle methodHandleFrom_selector_(final ClassMapping _classMapping, final st.gravel.core.Symbol _sel) { final AbstractMethodMapping _methodMapping; _methodMapping = this.methodMappingFrom_selector_(_classMapping, _sel); if (_methodMapping == null) { return null; } return _methodMapping.methodHandle(); } public MethodMapping methodMappingForNil_(final String _methodName) { final st.gravel.core.Symbol _sel; final ClassMapping _classMapping; _classMapping = this.nilClassMapping(); _sel = _selectorConverter.functionNameAsSelector_(_methodName); return ((MethodMapping) this.methodMappingFrom_selector_(_classMapping, _sel)); } public MethodMapping methodMappingFor_methodName_(final Class _receiverClass, final String _methodName) { final st.gravel.core.Symbol _sel; final ClassMapping _classMapping; _classMapping = this.classMappingForJavaClass_(_receiverClass); _sel = _selectorConverter.functionNameAsSelector_(_methodName); return ((MethodMapping) this.methodMappingFrom_selector_(_classMapping, _sel)); } public AbstractMethodMapping methodMappingFrom_selector_(final ClassMapping _classMapping, final st.gravel.core.Symbol _sel) { return _classMapping.methodMappingAt_ifAbsent_(_sel, ((st.gravel.support.jvm.Block0<AbstractMethodMapping>) (new st.gravel.support.jvm.Block0<AbstractMethodMapping>() { @Override public AbstractMethodMapping value() { final Reference _superclassReference; AbstractMethodMapping _mapping; _superclassReference = _classMapping.superclassReferenceForMethodLookup(); if (_superclassReference == null) { _mapping = null; } else { _mapping = SystemMapping.this.methodMappingFrom_selector_(((ClassMapping) SystemMapping.this.classMappingAtReference_(_superclassReference)), _sel); } return (AbstractMethodMapping) _mapping; } }))); } public st.gravel.support.jvm.runtime.AlmostFinalValue namespacedSingletonHolderAtReference_ifAbsent_(final AbsoluteReference _reference, final st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue> _aBlock) { final Object _temp1 = new Object(); try { final NamespaceNode _nsNode; _nsNode = _systemNode.namespaceNodeAt_ifAbsent_(_reference.namespace().namespace(), ((st.gravel.support.jvm.Block0<NamespaceNode>) (new st.gravel.support.jvm.Block0<NamespaceNode>() { @Override public NamespaceNode value() { return (NamespaceNode) null; } }))); if (_nsNode != null) { _nsNode.allImportsIn_do_(_systemNode, new st.gravel.support.jvm.Block1<Object, NamespaceNode>() { @Override public Object value_(final NamespaceNode _importNS) { final st.gravel.support.jvm.runtime.AlmostFinalValue _sh; final SharedDeclarationNode _shared; _shared = _importNS.sharedVariableAt_ifAbsent_(_reference.name().asString(), ((st.gravel.support.jvm.Block0<SharedDeclarationNode>) (new st.gravel.support.jvm.Block0<SharedDeclarationNode>() { @Override public SharedDeclarationNode value() { return (SharedDeclarationNode) null; } }))); if (_shared != null) { throw new NonLocalReturn(SystemMapping.this.singletonAtReference_initialize_(_importNS.reference().$slash$(_reference.name()), _shared), _temp1); } st.gravel.support.jvm.runtime.AlmostFinalValue _temp2 = _singletonHolders.get(_importNS.reference().$slash$(_reference.name())); _sh = ((st.gravel.support.jvm.runtime.AlmostFinalValue) _temp2); if (_sh != null) { throw new NonLocalReturn(_sh, _temp1); } return SystemMapping.this; } }); } return _aBlock.value(); } catch (NonLocalReturn nlr) { if (nlr.marker == _temp1) { return (st.gravel.support.jvm.runtime.AlmostFinalValue) nlr.returnValue; } else { throw nlr; } } } public SystemMapping namespaceGlobalsAndInitializersDo_(final st.gravel.support.jvm.Block2<Object, AbsoluteReference, SharedDeclarationNode> _aBlock) { for (final Map.Entry<Reference, NamespaceNode> _temp1 : _systemNode.namespaceNodes().entrySet()) { Reference _reference = _temp1.getKey(); NamespaceNode _namespaceNode = _temp1.getValue(); for (final SharedDeclarationNode _sharedVariable : _namespaceNode.sharedVariables()) { _aBlock.value_value_(((AbsoluteReference) _reference).$slash$(st.gravel.core.Symbol.value(_sharedVariable.name())), _sharedVariable); } } return this; } public ClassMapping newClassMappingForJavaClass_(final Class _receiverClass) { final Map<st.gravel.core.Symbol, AbstractMethodMapping>[] _methodMappings; final ClassNode _classNode; final ClassMapping _superMapping; final java.util.Set<st.gravel.core.Symbol>[] _allSelectors; _allSelectors = new java.util.Set[1]; _methodMappings = new Map[1]; _superMapping = this.bestClassMappingFor_(_receiverClass); _allSelectors[0] = _superMapping.allSelectorsIn_(this); _methodMappings[0] = new java.util.HashMap<st.gravel.core.Symbol, AbstractMethodMapping>(); _compilerTools.methodNamesIn_do_(_receiverClass, new st.gravel.support.jvm.Block2<Object, String, Integer>() { @Override public Object value_value_(final String _methodName, final Integer _numArgs) { final st.gravel.core.Symbol _sel; _sel = _selectorConverter.functionNameAsSelector_(_methodName); if (st.gravel.support.jvm.IntegerExtensions.equals_(_sel.numArgs(), _numArgs) && _allSelectors[0].contains(_sel)) { final java.lang.invoke.MethodHandle _methodHandle; _methodHandle = _compilerTools.methodHandleAt_numArgs_in_identityClass_isStatic_(_methodName, _sel.numArgs(), _receiverClass, _receiverClass, false); if (_methodHandle != null) { return _methodMappings[0].put(_sel, AnonymousMethodMapping.factory.methodHandle_definingClass_(_methodHandle, _receiverClass)); } } return SystemMapping.this; } }); _classNode = ClassNode.factory.name_superclassPath_properties_instVars_classInstVars_sharedVariables_methods_classMethods_namespace_isExtension_isTrait_traitUsage_classTraitUsage_(_superMapping.classNode().name(), _superMapping.reference().toString(), new java.util.HashMap<String, String>(), new VariableDeclarationNode[] {}, new VariableDeclarationNode[] {}, new SharedDeclarationNode[] {}, new MethodNode[] {}, new MethodNode[] {}, _superMapping.classNode().namespace(), false, false, EmptyTraitUsageNode.factory.basicNew(), EmptyTraitUsageNode.factory.basicNew()); return ClassMapping.factory.identityMapping_extensions_instVarMappings_classNode_(IdentityClassPartMapping.factory.javaClass_isGenerated_(_receiverClass, false).withMethodMappings_(_methodMappings[0]), new ExtensionClassPartMapping[] {}, new java.util.HashMap<String, InstVarMapping>(), _classNode); } public SystemMappingUpdater newSystemMappingUpdater() { return SystemMappingUpdater.factory.systemMapping_compilerTools_(this, _compilerTools); } public ClassMapping nilClassMapping() { return _nilClassMapping; } public ClassDescriptionNode obsoleteClassNodeAt_ifAbsent_(final Reference _aReference, final st.gravel.support.jvm.Block0<ClassDescriptionNode> _absentBlock) { final Object _temp1 = new Object(); try { return this.classMappingAtReference_ifAbsent_(_aReference, ((st.gravel.support.jvm.Block0<AbstractClassMapping>) (new st.gravel.support.jvm.Block0<AbstractClassMapping>() { @Override public AbstractClassMapping value() { throw new NonLocalReturn(_absentBlock.value(), _temp1); } }))).classNode(); } catch (NonLocalReturn nlr) { if (nlr.marker == _temp1) { return (ClassDescriptionNode) nlr.returnValue; } else { throw nlr; } } } public st.gravel.core.Symbol[] packageNames() { return _systemDefinitionNode.packageNames(); } public SystemMapping resetCache() { _subclassMappingsCache = null; return this; } public st.gravel.support.jvm.runtime.AlmostFinalValue resolveSingletonHolder_(final AbsoluteReference _reference) { return this.resolveSingletonHolder_ifAbsent_(_reference, ((st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue>) (new st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue>() { @Override public st.gravel.support.jvm.runtime.AlmostFinalValue value() { throw new RuntimeException("Singleton not found:" + _reference.toString()); } }))); } public st.gravel.support.jvm.runtime.AlmostFinalValue resolveSingletonHolder_ifAbsent_(final AbsoluteReference _reference, final st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue> _aBlock) { return this.namespacedSingletonHolderAtReference_ifAbsent_(_reference, ((st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue>) (new st.gravel.support.jvm.Block0<st.gravel.support.jvm.runtime.AlmostFinalValue>() { @Override public st.gravel.support.jvm.runtime.AlmostFinalValue value() { return (st.gravel.support.jvm.runtime.AlmostFinalValue) SystemMapping.this.classSharedSingletonHolderAtReference_ifAbsent_(_reference, _aBlock); } }))); } public SelectorConverter selectorConverter() { return _selectorConverter; } public SystemMapping setNamespaceNodes_(final Map<Reference, NamespaceNode> _aDictionary) { final Map<Reference, NamespaceNode>[] _dict; _dict = new Map[1]; _dict[0] = new java.util.HashMap<Reference, NamespaceNode>(); st.gravel.support.jvm.DictionaryExtensions.syncWith(_systemNode.namespaceNodes(), _aDictionary, new st.gravel.support.jvm.Block2<Object, NamespaceNode, NamespaceNode>() { @Override public Object value_value_(final NamespaceNode _old, final NamespaceNode _new) { return _dict[0].put(_new.reference(), _old.mergeWith_(_new)); } }, new st.gravel.support.jvm.Block1<Object, NamespaceNode>() { @Override public Object value_(final NamespaceNode _nsNode) { return _dict[0].put(_nsNode.reference(), _nsNode); } }, new st.gravel.support.jvm.Block1<Object, NamespaceNode>() { @Override public Object value_(final NamespaceNode _nsNode) { return _dict[0].put(_nsNode.reference(), _nsNode); } }); _systemNode = _systemNode.withNamespaceNodes_(_dict[0]); return this; } public Object singletonAtReferenceString_(final String _aString) { return this.singletonAtReference_(((AbsoluteReference) Reference.factory.value_(_aString))); } public Object singletonAtReference_(final AbsoluteReference _reference) { final st.gravel.support.jvm.runtime.AlmostFinalValue _holder; st.gravel.support.jvm.runtime.AlmostFinalValue _temp1 = _singletonHolders.get(_reference); if (_temp1 == null) { throw new RuntimeException("Singleton not found:" + _reference.toString()); } _holder = ((st.gravel.support.jvm.runtime.AlmostFinalValue) _temp1); return _compilerTools.valueOfSingletonHolder_(_holder); } public st.gravel.support.jvm.runtime.AlmostFinalValue singletonAtReference_ifAbsentInitialize_(final AbsoluteReference _reference, final st.gravel.support.jvm.Block0<Object> _aBlock) { st.gravel.support.jvm.runtime.AlmostFinalValue _temp1 = _singletonHolders.get(_reference); if (_temp1 == null) { st.gravel.support.jvm.runtime.AlmostFinalValue _temp2 = _compilerTools.newSingletonHolder_initializer_(_reference, _aBlock); _singletonHolders.put(_reference, _temp2); _temp1 = _temp2; } return _temp1; } public st.gravel.support.jvm.runtime.AlmostFinalValue singletonAtReference_ifAbsentPut_(final AbsoluteReference _reference, final st.gravel.support.jvm.Block0<Object> _aBlock) { st.gravel.support.jvm.runtime.AlmostFinalValue _temp1 = _singletonHolders.get(_reference); if (_temp1 == null) { st.gravel.support.jvm.runtime.AlmostFinalValue _temp2 = _compilerTools.newSingletonHolder_value_(_reference, _aBlock.value()); _singletonHolders.put(_reference, _temp2); _temp1 = _temp2; } return _temp1; } public st.gravel.support.jvm.runtime.AlmostFinalValue singletonAtReference_initialize_(final AbsoluteReference _reference, final SharedDeclarationNode _sharedVariable) { return this.singletonAtReference_ifAbsentPut_(_reference, new st.gravel.support.jvm.Block0<Object>() { @Override public Object value() { if (_sharedVariable.initializer() != null) { return SystemMapping.this.evaluateExpression_reference_(_sharedVariable.initializer(), _reference); } return SystemMapping.this; } }); } public SystemMapping subclassMappingsFor_do_(final Reference _aReference, final st.gravel.support.jvm.Block1<Object, AbstractClassMapping> _aBlock) { final java.util.Set<AbstractClassMapping> _c; if (_subclassMappingsCache == null) { SystemMapping.this.buildSubclassMappingsCache(); } java.util.Set<AbstractClassMapping> _temp1 = _subclassMappingsCache.get(_aReference); _c = ((java.util.Set<AbstractClassMapping>) _temp1); if (_c == null) { return null; } for (final AbstractClassMapping _temp2 : _c) { _aBlock.value_(_temp2); } return this; } public AbstractMethodMapping superMethodMappingFor_methodName_(final Reference _aReference, final String _methodName) { final st.gravel.core.Symbol _sel; final ClassMapping _classMapping; final Reference _superclassReference; _classMapping = ((ClassMapping) this.classMappingAtReference_(_aReference)); _superclassReference = _classMapping.superclassReference(); if (_superclassReference == null) { return null; } _sel = _selectorConverter.functionNameAsSelector_(_methodName); return this.methodMappingFrom_selector_(((ClassMapping) this.classMappingAtReference_(_superclassReference)), _sel); } public SystemDefinitionNode systemDefinitionNode() { return _systemDefinitionNode; } public SystemNode systemNode() { return _systemNode; } public SystemMapping updateTo_(final SystemDefinitionNode _newSystemDefinitionNode) { final SystemDiff[] _diff; final SystemNode[] _newSystemNode; _newSystemNode = new SystemNode[1]; _diff = new SystemDiff[1]; _newSystemNode[0] = PackageNodeMerger.factory.systemDefinitionNode_(_newSystemDefinitionNode).load(); this.log_while_("Calculating diff", new st.gravel.support.jvm.Block0<Object>() { @Override public Object value() { return _diff[0] = _systemNode.diffTo_(_newSystemNode[0]); } }); this.log_while_("Applying diff", new st.gravel.support.jvm.Block0<Object>() { @Override public Object value() { return SystemMapping.this.applyDiff_(_diff[0]); } }); _systemDefinitionNode = _newSystemDefinitionNode; this.resetCache(); return this; } }
canh7antt8a/strapi
packages/core/strapi/lib/services/server/middleware.js
'use strict'; const path = require('path'); const { propOr, isArray, isNil } = require('lodash/fp'); const getMiddlewareConfig = propOr([], 'config.middlewares'); const resolveRouteMiddlewares = (route, strapi) => { const middlewaresConfig = getMiddlewareConfig(route); if (!isArray(middlewaresConfig)) { throw new Error('Route middlewares config must be an array'); } const middlewares = resolveMiddlewares(middlewaresConfig, strapi); return middlewares.map(({ handler }) => handler); }; /** * Initialize every configured middlewares * @param {MiddlewaresConfig} config * @param {Strapi} strapi * @returns {Middlewares} */ const resolveMiddlewares = (config, strapi) => { const middlewares = []; for (const item of config) { if (typeof item === 'function') { middlewares.push({ name: null, handler: item, }); continue; } if (typeof item === 'string') { const middlewareFactory = strapi.middleware(item); if (!middlewareFactory) { throw new Error(`Middleware ${item} not found.`); } middlewares.push({ name: item, handler: middlewareFactory({}, { strapi }), }); continue; } if (typeof item === 'object' && item !== null) { const { name, resolve, config = {} } = item; if (name) { const middlewareFactory = strapi.middleware(name); middlewares.push({ name, handler: middlewareFactory(config, { strapi }), }); continue; } if (resolve) { middlewares.push({ name: resolve, handler: resolveCustomMiddleware(resolve, strapi)(config, { strapi }), }); continue; } throw new Error('Invalid middleware configuration. Missing name or resolve properties.'); } throw new Error( 'Middleware config must either be a string or an object {name?: string, resolve?: string, config: any}.' ); } middlewares.forEach(middleware => { // NOTE: we replace null middlewares by a dumb one to avoid having to filter later on if (isNil(middleware.handler)) { middleware.handler = (_, next) => next(); } }); return middlewares; }; /** * Resolve middleware from package name or path * @param {string} resolve * @param {Strapi} strapi */ const resolveCustomMiddleware = (resolve, strapi) => { let modulePath; try { modulePath = require.resolve(resolve); } catch (error) { if (error.code === 'MODULE_NOT_FOUND') { modulePath = path.resolve(strapi.dirs.root, resolve); } else { throw error; } } try { return require(modulePath); } catch (err) { throw new Error(`Could not load middleware "${modulePath}".`); } }; module.exports = { resolveRouteMiddlewares, resolveMiddlewares, };
sankhesh/tomviz
tomviz/DoubleSpinBox.cxx
<reponame>sankhesh/tomviz<filename>tomviz/DoubleSpinBox.cxx /* This source file is part of the Tomviz project, https://tomviz.org/. It is released under the 3-Clause BSD License, see "LICENSE". */ #include "DoubleSpinBox.h" #include <QMouseEvent> #include <QStyle> #include <QStyleOptionSpinBox> namespace tomviz { DoubleSpinBox::DoubleSpinBox(QWidget* p) : QDoubleSpinBox(p), pressInUp(false), pressInDown(false) {} void DoubleSpinBox::mousePressEvent(QMouseEvent* event) { QDoubleSpinBox::mousePressEvent(event); QStyleOptionSpinBox opt; this->initStyleOption(&opt); if (this->style() ->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxUp) .contains(event->pos())) { this->pressInUp = true; } else if (this->style() ->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxDown) .contains(event->pos())) { this->pressInDown = true; } else { this->pressInUp = this->pressInDown = false; } if (this->pressInUp || this->pressInDown) { this->connect(this, SIGNAL(valueChanged(double)), this, SIGNAL(editingFinished())); } } void DoubleSpinBox::mouseReleaseEvent(QMouseEvent* event) { QDoubleSpinBox::mouseReleaseEvent(event); if (this->pressInUp || this->pressInDown) { this->disconnect(this, SIGNAL(valueChanged(double)), this, SIGNAL(editingFinished())); } QStyleOptionSpinBox opt; this->initStyleOption(&opt); if (this->style() ->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxUp) .contains(event->pos())) { if (this->pressInUp) { emit this->editingFinished(); } } else if (this->style() ->subControlRect(QStyle::CC_SpinBox, &opt, QStyle::SC_SpinBoxDown) .contains(event->pos())) { if (this->pressInDown) { emit this->editingFinished(); } } this->pressInUp = this->pressInDown = false; } } // namespace tomviz
glennji/openlumify
core/core/src/main/java/org/openlumify/core/ingest/MetadataGraphPropertyWorker.java
package org.openlumify.core.ingest; import org.openlumify.core.ingest.graphProperty.GraphPropertyWorkData; import org.openlumify.core.ingest.graphProperty.GraphPropertyWorker; import org.openlumify.core.model.Description; import org.openlumify.core.model.Name; import org.openlumify.core.model.properties.OpenLumifyProperties; import org.openlumify.web.clientapi.model.VisibilityJson; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import org.vertexium.Element; import org.vertexium.Metadata; import org.vertexium.Property; import org.vertexium.Visibility; import org.vertexium.mutation.ElementMutation; import org.vertexium.property.StreamingPropertyValue; import java.io.IOException; import java.io.InputStream; import static com.google.common.base.Preconditions.checkNotNull; @Name("Metadata Processor") @Description("Adds properties to a vertex from a metadata JSON document") public class MetadataGraphPropertyWorker extends GraphPropertyWorker { @Override public void execute(InputStream in, GraphPropertyWorkData data) throws Exception { JSONObject metadataJson = getMetadataJson(data); JSONArray propertiesJson = metadataJson.optJSONArray("properties"); if (propertiesJson == null) { return; } for (int i = 0; i < propertiesJson.length(); i++) { JSONObject propertyJson = propertiesJson.getJSONObject(i); setProperty(propertyJson, data); } getGraph().flush(); for (int i = 0; i < propertiesJson.length(); i++) { JSONObject propertyJson = propertiesJson.getJSONObject(i); queueProperty(propertyJson, data); } } public void queueProperty(JSONObject propertyJson, GraphPropertyWorkData data) { String propertyKey = propertyJson.optString("key"); if (propertyKey == null) { propertyKey = ElementMutation.DEFAULT_KEY; } String propertyName = propertyJson.optString("name"); getWorkQueueRepository().pushGraphPropertyQueue(data.getElement(), propertyKey, propertyName, data.getPriority()); } private void setProperty(JSONObject propertyJson, GraphPropertyWorkData data) { String propertyKey = propertyJson.optString("key", null); if (propertyKey == null) { propertyKey = ElementMutation.DEFAULT_KEY; } String propertyName = propertyJson.optString("name", null); checkNotNull(propertyName, "name is required: " + propertyJson.toString()); String propertyValue = propertyJson.optString("value", null); checkNotNull(propertyValue, "value is required: " + propertyJson.toString()); String visibilitySource = propertyJson.optString("visibilitySource", null); Visibility visibility; if (visibilitySource == null) { visibility = data.getVisibility(); } else { visibility = getVisibilityTranslator().toVisibility(visibilitySource).getVisibility(); } Metadata metadata = new Metadata(); OpenLumifyProperties.VISIBILITY_JSON_METADATA.setMetadata(metadata, VisibilityJson.updateVisibilitySource(null, visibilitySource), getVisibilityTranslator().getDefaultVisibility()); data.getElement().addPropertyValue(propertyKey, propertyName, propertyValue, metadata, visibility, getAuthorizations()); } public JSONObject getMetadataJson(GraphPropertyWorkData data) throws IOException { StreamingPropertyValue metadataJsonValue = OpenLumifyProperties.METADATA_JSON.getPropertyValue(data.getElement()); try (InputStream metadataJsonIn = metadataJsonValue.getInputStream()) { String metadataJsonString = IOUtils.toString(metadataJsonIn); return new JSONObject(metadataJsonString); } } @Override public boolean isHandled(Element element, Property property) { if (property != null) { return false; } StreamingPropertyValue mappingJson = OpenLumifyProperties.METADATA_JSON.getPropertyValue(element); if (mappingJson == null) { return false; } return true; } }
xillio/xill-platform
plugin-web/src/test/java/nl/xillio/xill/plugins/web/data/PageVariableTest.java
<reponame>xillio/xill-platform<filename>plugin-web/src/test/java/nl/xillio/xill/plugins/web/data/PageVariableTest.java<gh_stars>1-10 /** * Copyright (C) 2014 Xillio (<EMAIL>) * * 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 nl.xillio.xill.plugins.web.data; import nl.xillio.xill.plugins.web.data.PageVariable; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Test the {@link PageVariable}. */ public class PageVariableTest { /** * Test getTextPreview method. */ @Test public void testPageTextPreview() { // mock String data = "Some page content"; WebDriver driver = mock(WebDriver.class); when(driver.getPageSource()).thenReturn(data); PageVariable pageVariable = new PageVariable(driver, null); // run String result = pageVariable.getTextPreview(); Assert.assertEquals(result, data); } }
samiulshuvo/fastmri-reproducible-benchmark
fastmri_recon/tests/models/utils/attention_test.py
import pytest import tensorflow as tf from fastmri_recon.models.utils.attention import ChannelAttentionBlock @pytest.mark.parametrize('kwargs',[ {}, {'activation': 'prelu'}, {'activation': 'lrelu'}, {'dense': True}, {'dense': True, 'activation': 'prelu'}, ]) def test_channel_attention_block_call(kwargs): ca_block = ChannelAttentionBlock(**kwargs) inputs = tf.random.normal([2, 32, 32, 16]) ca_block(inputs)
krisds/cobol-codeql
extractor/src/com/semmle/cobol/generator/types/ListType.java
package com.semmle.cobol.generator.types; import com.semmle.cobol.extractor.CobolExtractor; public class ListType extends NamedType implements Type, TrappableType, PersistentType { private String itemTypeName; private String tableName; public ListType(String name, String itemType) { super(name); this.itemTypeName = itemType; this.tableName = name + "s"; } @Override public boolean isAssignableFrom(Type type) { return this == type || type instanceof ListType && getItemType() .isAssignableFrom(((ListType) type).getItemType()); } public Type getItemType() { return CobolExtractor.getType(itemTypeName); } public String getItemTypeName() { return itemTypeName; } public void setItemTypeName(String itemTypeName) { this.itemTypeName = itemTypeName; } @Override public String getRelationName() { return tableName; } @Override public void setRelationName(String tableName) { this.tableName = tableName; } @Override public PersistentType getPersistentType() { return this; } }
viennagrid/viennagrid-dev
viennagrid/meta/typelist.hpp
<reponame>viennagrid/viennagrid-dev #ifndef VIENNAGRID_META_TYPELIST_HPP #define VIENNAGRID_META_TYPELIST_HPP /* ======================================================================= Copyright (c) 2011-2014, Institute for Microelectronics, Institute for Analysis and Scientific Computing, TU Wien. ----------------- ViennaGrid - The Vienna Grid Library ----------------- License: MIT (X11), see file LICENSE in the base directory ======================================================================= */ #include "viennagrid/meta/utils.hpp" /** @file viennagrid/meta/typelist.hpp @brief Defines typelists and provides algorithms for their manipulation */ namespace viennagrid { /** @brief Implementation of a typelist as described by Alexandrescu in his book "Modern C++ Programming" */ template <class HeadT, class TailT> struct typelist { typedef HeadT head; typedef TailT tail; }; // C++11 version // template<typename ... types> // struct make_typelist; // // template<> // struct make_typelist<> // { // typedef viennagrid::null_type type; // }; // // template<typename head, typename ... tail> // struct make_typelist<head, tail...> // { // typedef viennagrid::typelist<head, typename make_typelist<tail...>::type> type; // }; /** @brief Convenience meta function for creating a typelist out of the provided types */ template< typename T01 = viennagrid::null_type, typename T02 = viennagrid::null_type, typename T03 = viennagrid::null_type, typename T04 = viennagrid::null_type, typename T05 = viennagrid::null_type, typename T06 = viennagrid::null_type, typename T07 = viennagrid::null_type, typename T08 = viennagrid::null_type, typename T09 = viennagrid::null_type, typename T10 = viennagrid::null_type, typename T11 = viennagrid::null_type, typename T12 = viennagrid::null_type, typename T13 = viennagrid::null_type, typename T14 = viennagrid::null_type, typename T15 = viennagrid::null_type, typename T16 = viennagrid::null_type, typename T17 = viennagrid::null_type, typename T18 = viennagrid::null_type, typename T19 = viennagrid::null_type, typename T20 = viennagrid::null_type > struct make_typelist { typedef typelist< T01, typename make_typelist<T02, T03, T04, T05, T06, T07, T08, T09, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>::type > type; }; /** \cond */ template<> struct make_typelist< viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type, viennagrid::null_type> { typedef viennagrid::null_type type; }; /** \endcond */ namespace detail { namespace result_of { // size of a typelist template <typename typelist> struct size; template <> struct size<null_type> { static const int value = 0; }; template <typename head, typename tail> struct size< typelist<head, tail> > { static const int value = 1 + size<tail>::value; }; // index access template <typename typelist, int index> struct at { typedef out_of_range type; }; template <typename head, typename tail> struct at<typelist<head, tail>, 0> { typedef head type; }; template <typename head, typename tail, int i> struct at<typelist<head, tail>, i> { typedef typename at<tail, i - 1>::type type; }; // returns the index of the first type in the typelist template <typename typelist, typename to_find> struct index_of; template <typename to_find> struct index_of<null_type, to_find> { static const int value = -1; }; template <typename to_find, typename tail> struct index_of<typelist<to_find, tail>, to_find> { static const int value = 0; }; template <typename head, typename tail, typename to_find> struct index_of<typelist<head, tail>, to_find> { private: static const int temp = index_of<tail, to_find>::value; public: static const int value = (temp == -1 ? -1 : 1 + temp); }; // push back a single type template <typename typelist, typename to_add> struct push_back; template <> struct push_back<null_type, null_type> { typedef null_type type; }; template <typename to_add> struct push_back<null_type, to_add> { typedef typelist<to_add, null_type> type; }; template <typename head, typename tail, typename to_add> struct push_back<typelist<head, tail>, to_add> { typedef typelist<head, typename push_back<tail, to_add>::type> type; }; // push back list template <typename typelist, typename typelisto_add> struct push_back_list; template <> struct push_back_list<null_type, null_type> { typedef null_type type; }; template <typename head, typename tail> struct push_back_list<null_type, typelist<head, tail> > { typedef typelist<head, tail> type; }; template <typename head, typename tail> struct push_back_list<typelist<head, tail>, null_type > { typedef typelist<head, tail> type; }; template <typename head1, typename tail1, typename head2, typename tail2> struct push_back_list<typelist<head1, tail1>, typelist<head2, tail2> > { typedef typename push_back_list< typename push_back< typelist<head1, tail1>, head2>::type, tail2 >::type type; }; // erase_at the type at index template <typename typelist, int index_to_erase> struct erase_at; template <int index_to_erase> struct erase_at<null_type, index_to_erase> { typedef null_type type; }; template <typename head, typename tail> struct erase_at< typelist<head, tail>, 0> { typedef tail type; }; template <typename head, typename tail, int index_to_erase> struct erase_at< typelist<head, tail>, index_to_erase> { typedef typelist<head, typename erase_at<tail, index_to_erase-1>::type> type; }; // erase the first type template <typename typelist, typename to_erase> struct erase; template <typename to_erase> struct erase<null_type, to_erase> { typedef null_type type; }; template <typename to_erase, typename tail> struct erase< typelist<to_erase, tail>, to_erase> { typedef tail type; }; template <typename head, typename tail, typename to_erase> struct erase< typelist<head, tail>, to_erase> { typedef typelist<head, typename erase<tail, to_erase>::type> type; }; // erase all types template <typename typelist, typename to_erase> struct erase_all; template <typename to_erase> struct erase_all<null_type, to_erase> { typedef null_type type; }; template <typename to_erase, typename tail> struct erase_all< typelist<to_erase, tail>, to_erase> { // Go all the way down the list removing the type typedef typename erase_all<tail, to_erase>::type type; }; template <typename head, typename tail, typename to_erase> struct erase_all< typelist<head, tail>, to_erase> { // Go all the way down the list removing the type typedef typelist<head, typename erase_all<tail, to_erase>::type> type; }; // reverse template <typename typelist> struct reverse; template <> struct reverse<null_type> { typedef null_type type; }; template <typename head, typename tail> struct reverse< typelist<head, tail> > { typedef typelist<head, tail> t_list; public: typedef typelist< typename at< t_list, size<t_list>::value-1 >::type, typename reverse< typename erase_at< t_list, size<t_list>::value-1 >::type >::type > type; }; // no duplicate types template <typename typelist> struct no_duplicates; template <> struct no_duplicates<null_type> { typedef null_type type; }; template <typename head, typename tail> struct no_duplicates< typelist<head, tail> > { private: typedef typename no_duplicates<tail>::type L1; typedef typename erase<L1, head>::type L2; public: typedef typelist<head, L2> type; }; // replace the type at index by another type template <typename typelist, int index_to_replace, typename replaced> struct replace_at; template <typename replaced> struct replace_at<null_type, -1, replaced> { typedef null_type type; }; template <typename head, typename tail, typename replaced> struct replace_at<typelist<head, tail>, -1, replaced> { typedef null_type type; }; template <int index_to_replace, typename replaced> struct replace_at<null_type, index_to_replace, replaced> { typedef null_type type; }; template <typename head, typename tail, typename replaced> struct replace_at<typelist<head, tail>, 0, replaced> { typedef typelist<replaced, tail> type; }; template <typename head, typename tail, int index_to_replace, typename replaced> struct replace_at<typelist<head, tail>, index_to_replace, replaced> { typedef typelist<head, typename replace_at<tail, index_to_replace-1, replaced>::type> type; }; // replace the first type by another type template <typename typelist, typename to_replace, typename replaced> struct replace; template <typename to_replace, typename replaced> struct replace<null_type, to_replace, replaced> { typedef null_type type; }; template <typename to_replace, typename tail, typename replaced> struct replace<typelist<to_replace, tail>, to_replace, replaced> { typedef typelist<replaced, tail> type; }; template <typename head, typename tail, typename to_replace, typename replaced> struct replace<typelist<head, tail>, to_replace, replaced> { typedef typelist<head, typename replace<tail, to_replace, replaced>::type> type; }; // replace all types by another type template <typename typelist, typename to_replace, typename replaced> struct replace_all; template <typename to_replace, typename replaced> struct replace_all<null_type, to_replace, replaced> { typedef null_type type; }; template <typename to_replace, typename tail, typename replaced> struct replace_all<typelist<to_replace, tail>, to_replace, replaced> { typedef typelist<replaced, typename replace_all<tail, to_replace, replaced>::type> type; }; template <typename head, typename tail, typename to_replace, typename replaced> struct replace_all<typelist<head, tail>, to_replace, replaced> { typedef typelist<head, typename replace_all<tail, to_replace, replaced>::type> type; }; // returns only those types which are in both typelists template<typename typelist1, typename typelist2> struct intersection {}; template<> struct intersection<null_type, null_type> { typedef null_type type; }; template<typename head1, typename tail1> struct intersection<typelist<head1, tail1>, null_type> { typedef null_type type; }; template<typename head2, typename tail2> struct intersection<null_type, typelist<head2, tail2> > { typedef null_type type; }; template<typename head1, typename tail1, typename head2, typename tail2> struct intersection< typelist<head1, tail1>, typelist<head2, tail2> > { typedef typelist<head1, tail1> typelist1; typedef typelist<head2, tail2> typelist2; static const int search_result = index_of< typelist2, head1 >::value; static const bool found = (search_result >= 0); //otherwise there are parsing problems with Doxygen 1.7.6.1 typedef typename IF< found, typename erase_at<typelist2, search_result>::type, typelist2 >::type new_typelist2; typedef typename IF< found, typelist<head1, typename intersection<tail1, new_typelist2>::type >, typename intersection<tail1, new_typelist2>::type >::type type; }; } } // namespace detail } // namespace viennagrid #endif // end file guardian
pf-aics-riken/kmr
src/kmrbase.c
<reponame>pf-aics-riken/kmr<gh_stars>1-10 /* kmrbase.c (2014-02-04) */ /* Copyright (C) 2012-2018 RIKEN R-CCS */ /** \file kmrbase.c KMR Base Implementation (on-memory operations). KMR aims at fast shuffling and scalability, and provides modest utilities for programming with map-reduce. This part implements on-memory operations. */ /* NOTE: (1) KMR and KMR_KVS are handled collectively (allocated, modified, and freed). */ #include <mpi.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <limits.h> #include <errno.h> #include <assert.h> #include <ctype.h> #ifdef _OPENMP #include <omp.h> #endif #include "../config.h" #include "kmr.h" #include "kmrimpl.h" #include "kmrtrace.h" int KMR_API_ID = 0; const int kmr_version = KMR_H; #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) #define NEVERHERE 0 /* Default unit of allocation of memory block for key-value pairs. See preset_block_size in struct kmr_ctx. */ #define BLOCK_SIZE (64 * 1024 * 1024) /* Default of the number of entries pooled before calling a map-function. See mapper_park_size in struct kmr_ctx. */ #define MAP_PARK_SIZE (1024) /* Default block size of a push-off key-value stream. See See pushoff_block_size in struct kmr_ctx. */ #define PUSHOFF_SIZE (64 * 1024) /* Checks if an end-of-block marker is properly placed. It only checks when a key-value stream consists of a single preallocated block. */ static inline void kmr_assert_on_tail_marker(KMR_KVS *kvs) { if (kvs != 0 && kvs->c.block_count == 1) { struct kmr_kvs_block *b = kvs->c.first_block; size_t netsz = kvs->c.storage_netsize; struct kmr_kvs_entry *e = kmr_kvs_entry_at(kvs, b, netsz); assert((((intptr_t)e) & 3) == 0 && e->klen == -1 && e->vlen == -1); } } /* Sets up the environment (nothing currently). It checks the data sizes in C meets the KMR assumptions. It also checks MPI_LONG has 8-byte size, that is assumed in all-to-all communication. It calls an OMP function, to initialize the threads environment here. */ int kmr_init_2(int ignore) { int cc; assert(sizeof(long) == sizeof(size_t) && sizeof(long) == sizeof(ssize_t) && sizeof(long) == sizeof(off_t) && sizeof(long) == sizeof(uint64_t) && sizeof(long) >= sizeof(intptr_t) && sizeof(long) >= sizeof(void *)); assert(kmr_check_alignment(offsetof(struct kmr_kvs_entry, c))); assert(kmr_check_alignment(offsetof(struct kmr_kvs_block, data))); assert(kmr_check_alignment(offsetof(struct kmr_ntuple_entry, len))); assert(sizeof(struct kmr_option) == sizeof(long) && sizeof(struct kmr_file_option) == sizeof(long) && sizeof(struct kmr_spawn_option) == sizeof(long)); MPI_Aint lb; MPI_Aint extent; cc = MPI_Type_get_extent(MPI_LONG, &lb, &extent); assert(cc == MPI_SUCCESS); assert(lb == 0 && extent == 8); #if 0 KMR_OMP_PARALLEL_ { int tid = omp_get_thread_num(); assert(tid >= 0); } #endif return MPI_SUCCESS; } /** Sets up the environment, and checks the constant definitions in C and Fortran are consistent. */ int kmr_init_ff(int kf, struct kmr_option opt, struct kmr_file_option fopt) { union {struct kmr_option o; unsigned long i;} opt0 = {.o = opt}; union {struct kmr_file_option o; unsigned long i;} fopt0 = {.o = fopt}; opt0.o.rank_zero = 0; fopt0.o.shuffle_names = 0; assert(kf == KMR_KV_POINTER_UNMANAGED && opt.rank_zero && fopt.shuffle_names && opt0.i == 0 && fopt0.i == 0); kmr_init_2(0); return MPI_SUCCESS; } /** Clears the environment. */ int kmr_fin(void) { return MPI_SUCCESS; } /** Checks the initialization state of MPI, and initializes MPI when not. It returns 1, or 0 when something is wrong. It is for the Python binding. */ int kmr_initialize_mpi(int *refargc, char ***refargv) { int cc; int ok; cc = MPI_Initialized(&ok); if (cc == MPI_SUCCESS && ok != 0) { return 1; } else if (cc == MPI_SUCCESS && ok == 0) { int thlv; cc = MPI_Init_thread(refargc, refargv, MPI_THREAD_SERIALIZED, &thlv); return (cc == MPI_SUCCESS); } else { return 0; } } /** Makes a new KMR context (a context has type KMR). A KMR context is a record of common information to all key-value streams. COMM is a communicator for use inside. It dups the given communicator inside, to avoid conflicts with other calls to MPI functions. MPI should be initialized with a thread support level of either MPI_THREAD_SERIALIZED or MPI_THREAD_MULTIPLE. CONF specifies configuration options. It should be freed after a call. The options can differ on each rank, (in this version). The configuration options are first taken from a file with a name specified by the environment variable "KMROPTION" on rank0, and they are merged with the explicitly given ones. The KMROPTION file has the file format of Java properties (but only in Latin characters). Refer to JDK documents on "java.util.Properties" (on "load" method) for the file format. The explicitly given ones have precedence. IDENTIFYING_NAME is just recorded in the context, and has no specific use. It may be null. */ KMR * kmr_create_context(const MPI_Comm comm, const MPI_Info conf, const char *identifying_name) { int cc; KMR *mr = kmr_malloc(sizeof(struct kmr_ctx)); KMR_DEBUGX(memset(mr, 0, sizeof(struct kmr_ctx))); cc = MPI_Comm_size(comm, &mr->nprocs); assert(cc == MPI_SUCCESS); cc = MPI_Comm_rank(comm, &mr->rank); assert(cc == MPI_SUCCESS); cc = MPI_Comm_dup(comm, &mr->comm); if (cc != MPI_SUCCESS) { kmr_error_mpi(mr, "MPI_Comm_dup", cc); MPI_Abort(MPI_COMM_WORLD, 1); } #ifdef _OPENMP int omp_thrd = omp_get_thread_limit(); #else int omp_thrd = 1; #endif assert(omp_thrd >= 1); int mpi_thrd; cc = MPI_Query_thread(&mpi_thrd); assert(cc == MPI_SUCCESS); assert(mpi_thrd == MPI_THREAD_SINGLE || mpi_thrd == MPI_THREAD_FUNNELED || mpi_thrd == MPI_THREAD_SERIALIZED || mpi_thrd == MPI_THREAD_MULTIPLE); if (mpi_thrd == MPI_THREAD_SINGLE || mpi_thrd == MPI_THREAD_FUNNELED) { if (omp_thrd > 1) { char ee[80]; char *s = ((mpi_thrd == MPI_THREAD_SINGLE) ? "MPI_THREAD_SINGLE" : "MPI_THREAD_FUNNELED"); snprintf(ee, sizeof(ee), "Thread support of MPI is low: %s", s); kmr_warning(mr, 1, ee); } } mr->kvses.head = 0; mr->kvses.tail = 0; mr->ckpt_kvs_id_counter = 0; mr->ckpt_ctx = 0; mr->ckpt_enable = 0; mr->ckpt_selective = 0; mr->ckpt_no_fsync = 0; mr->kvt_ctx = 0; mr->log_traces = 0; mr->atwork = 0; mr->spawn_size = 0; mr->spawn_comms = 0; mr->mapper_park_size = MAP_PARK_SIZE; mr->preset_block_size = BLOCK_SIZE; mr->malloc_overhead = (int)sizeof(void *); mr->atoa_threshold = 512; mr->atoa_size_limit = 0; mr->atoa_requests_limit = 0; mr->sort_trivial = 100000; mr->sort_threshold = 100L; mr->sort_sample_factor = 10000; mr->sort_threads_depth = 5; mr->file_io_block_size = (1024 * 1024); mr->rlimit_nofile = -1; mr->pushoff_block_size = PUSHOFF_SIZE; mr->pushoff_poll_rate = 0; #if defined(KMRLIBDIR) mr->kmr_installation_path = KMRLIBDIR; #else mr->kmr_installation_path = 0; #endif mr->spawn_watch_program = 0; mr->spawn_watch_prefix = 0; mr->spawn_watch_host_name = 0; mr->spawn_max_processes = 0; mr->spawn_watch_af = 4; mr->spawn_watch_port_range[0] = 0; mr->spawn_watch_port_range[1] = 0; mr->spawn_gap_msec[0] = 1000; mr->spawn_gap_msec[1] = 10000; mr->spawn_watch_accept_onhold_msec = (60 * 1000); mr->spawn_self = MPI_COMM_NULL; mr->spawn_retry_limit = 20; mr->spawn_retry_gap_msec = (15 * 1000); mr->simple_workflow = 0; mr->swf_spawner_so = 0; mr->swf_spawner_library = 0; mr->swf_args_size = 0; mr->swf_exec_so = 0; mr->swf_record_history = 1; mr->swf_debug_master = 0; mr->verbosity = 5; mr->onk = 1; mr->single_thread = 0; mr->one_step_sort = 0; mr->step_sync = 0; mr->trace_sorting = 0; mr->trace_file_io = 0; mr->trace_map_ms = 0; mr->trace_map_spawn = 0; mr->trace_alltoall = 0; mr->trace_kmrdp = 0; mr->trace_iolb = 0; mr->std_abort = 0; mr->file_io_dummy_striping = 1; mr->file_io_always_alltoallv = 0; mr->map_ms_use_exec = 0; mr->map_ms_abort_on_signal = 0; mr->spawn_sync_at_startup = 0; mr->spawn_watch_all = 0; mr->spawn_disconnect_early = 0; mr->spawn_disconnect_but_free = 0; mr->spawn_pass_intercomm_in_argument = 0; mr->keep_fds_at_fork = 0; mr->mpi_thread_support = (mpi_thrd == MPI_THREAD_SERIALIZED || mpi_thrd == MPI_THREAD_MULTIPLE); mr->stop_at_some_check_globally = 0; mr->pushoff_hang_out = 0; mr->pushoff_fast_notice = 0; mr->pushoff_stat = 1; memset(&mr->pushoff_statistics, 0, sizeof(mr->pushoff_statistics)); mr->kmrviz_trace = 0; if (identifying_name != 0) { size_t s = strlen(identifying_name); assert(s < KMR_JOB_NAME_LEN); strncpy(mr->identifying_name, identifying_name, KMR_JOB_NAME_LEN); mr->identifying_name[KMR_JOB_NAME_LEN - 1] = 0; } else { mr->identifying_name[0] = 0; } /* KMR is now usable (with default setting). */ /* Load and merge MPI infos. */ cc = MPI_Info_create(&mr->conf); assert(cc == MPI_SUCCESS); cc = kmr_load_preference(mr, mr->conf); assert(cc == MPI_SUCCESS); if (conf != MPI_INFO_NULL) { cc = kmr_copy_mpi_info(conf, mr->conf); assert(cc == MPI_SUCCESS); } kmr_check_options(mr, mr->conf); /* Initialize checkpoint context. */ kmr_ckpt_create_context(mr); /* Initialize KMRViz trace */ kmr_trace_initialize(mr); return mr; } KMR * kmr_create_context_world() { KMR *mr = kmr_create_context(MPI_COMM_WORLD, MPI_INFO_NULL, ""); return mr; } KMR * kmr_create_context_ff(const int fcomm, const int finfo, const char *identifying_name) { MPI_Comm comm = MPI_Comm_f2c(fcomm); MPI_Info info = MPI_Info_f2c(finfo); KMR *mr = kmr_create_context(comm, info, identifying_name); return mr; } /** Releases a context created with kmr_create_context(). */ int kmr_free_context(KMR *mr) { int cc; if (mr->kvses.head != 0 || mr->kvses.tail != 0) { kmr_warning(mr, 1, "Some key-value streams remain unfreed"); for (KMR_KVS *p = mr->kvses.head; p != 0; p = p->c.link.next) { if (!KMR_KVS_MAGIC_OK(p->c.magic)) { kmr_warning(mr, 1, "- unfreed kvs in bad state"); } else if (p->c.magic == KMR_KVS_ONCORE) { if (p->c.info_line0.file != 0) { char ee[80]; snprintf(ee, 80, "- kvs allocated at %s:%d: %s", p->c.info_line0.file, p->c.info_line0.line, p->c.info_line0.func); kmr_warning(mr, 1, ee); } } else { kmr_warning(mr, 1, "- unfreed kvs in bad state"); } } } if (mr->spawn_self != MPI_COMM_NULL && mr->spawn_self != MPI_COMM_SELF) { cc = MPI_Comm_free(&mr->spawn_self); assert(cc == MPI_SUCCESS); } /* Finalize KMRViz trace. */ kmr_trace_finalize(mr); /* Free checkpoint context. */ kmr_ckpt_free_context(mr); if (mr->log_traces != 0) { cc = fclose(mr->log_traces); if (cc == EOF) { char ee[80]; char *m = strerror(errno); snprintf(ee, sizeof(ee), "Closing log file failed: %s", m); kmr_warning(mr, 1, ee); } mr->log_traces = 0; } cc = MPI_Comm_free(&mr->comm); assert(cc == MPI_SUCCESS); if (mr->conf != MPI_INFO_NULL) { cc = MPI_Info_free(&mr->conf); assert(cc == MPI_SUCCESS); } if (mr->spawn_watch_program != 0) { kmr_free_string(mr->spawn_watch_program); mr->spawn_watch_program = 0; } assert(mr->spawn_comms == 0); /*mr->kmr_installation_path;*/ /*mr->spawn_watch_prefix;*/ /*mr->spawn_watch_host_name;*/ if (mr->simple_workflow != 0) { kmr_finish_swf(mr); mr->simple_workflow = 0; } assert(mr->swf_spawner_so == 0); if (mr->swf_spawner_library != 0) { kmr_free_string(mr->swf_spawner_library); mr->swf_spawner_library = 0; } kmr_free(mr, sizeof(struct kmr_ctx)); return MPI_SUCCESS; } KMR * kmr_get_context_of_kvs(KMR_KVS const *kvs) { KMR *mr = kvs->c.mr; return mr; } /* Unlinks a key-value stream from a list on a context. */ static inline void kmr_unlink_kvs(KMR_KVS *kvs) { KMR *mr = kvs->c.mr; KMR_KVS *prev = kvs->c.link.prev; KMR_KVS *next = kvs->c.link.next; if (prev != 0) { prev->c.link.next = next; } else { assert(mr->kvses.head == kvs); mr->kvses.head = next; } if (next != 0) { next->c.link.prev = prev; } else { assert(mr->kvses.tail == kvs); mr->kvses.tail = prev; } } /** Makes a new key-value stream (type KMR_KVS). It allocates by the size of the union, which may be larger than the necessary. */ static KMR_KVS * kmr_create_raw_kvs(KMR *mr, const KMR_KVS *_similar) { xassert(mr != 0); /*assert(similar->c.mr == mr);*/ KMR_KVS *kvs = kmr_malloc(sizeof(KMR_KVS)); KMR_DEBUGX(memset(kvs, 0, sizeof(KMR_KVS))); kvs->c.magic = KMR_KVS_ONCORE; kvs->c.mr = mr; kmr_link_kvs(kvs); if (kmr_ckpt_enabled(mr)) { mr->ckpt_kvs_id_counter++; kvs->c.ckpt_kvs_id = mr->ckpt_kvs_id_counter; kvs->c.ckpt_generated_op = 0; kvs->c.ckpt_consumed_op = 0; } kvs->c.key_data = KMR_KV_BAD; kvs->c.value_data = KMR_KV_BAD; kvs->c.element_count = 0; kvs->c.oncore = 1; kvs->c.stowed = 0; kvs->c.nogrow = 0; kvs->c.sorted = 0; kvs->c.shuffled_in_pushoff = 0; kvs->c._uniformly_sized_ = 0; kvs->c.block_size = (mr->preset_block_size - mr->malloc_overhead); kvs->c.element_size_limit = (kvs->c.block_size / 4); kvs->c.storage_netsize = 0; kvs->c.block_count = 0; kvs->c.first_block = 0; kvs->c.ms = 0; /* Transient fields: */ kvs->c.under_threaded_operation = 0; kvs->c.current_block = 0; kvs->c.adding_point = 0; kvs->c.temporary_data = 0; //KMR_OMP_INIT_LOCK(&kvs->c.mutex); return kvs; } /* Clears the slots of the structure. It keeps the fields of the a link and checkpointing. */ void kmr_init_kvs_oncore(KMR_KVS *kvs, KMR *mr) { assert(mr != 0); kvs->c.magic = KMR_KVS_ONCORE; kvs->c.mr = mr; /*kmr_link_kvs(kvs);*/ /*kvs->c.ckpt_kvs_id = 0;*/ /*kvs->c.ckpt_generated_op = 0;*/ /*kvs->c.ckpt_consumed_op = 0;*/ kvs->c.key_data = KMR_KV_BAD; kvs->c.value_data = KMR_KV_BAD; kvs->c.element_count = 0; kvs->c.oncore = 1; kvs->c.stowed = 0; kvs->c.nogrow = 0; kvs->c.sorted = 0; kvs->c.shuffled_in_pushoff = 0; kvs->c._uniformly_sized_ = 0; kvs->c.block_size = (mr->preset_block_size - mr->malloc_overhead); kvs->c.element_size_limit = (kvs->c.block_size / 4); kvs->c.storage_netsize = 0; kvs->c.block_count = 0; kvs->c.first_block = 0; kvs->c.ms = 0; /* Transient fields: */ kvs->c.under_threaded_operation = 0; kvs->c.current_block = 0; kvs->c.adding_point = 0; kvs->c.temporary_data = 0; } /** Makes a new key-value stream with the specified field data-types. */ KMR_KVS * kmr_create_kvs7(KMR *mr, enum kmr_kv_field kf, enum kmr_kv_field vf, struct kmr_option opt, const char *file, const int line, const char *func) { KMR_KVS *kvs = kmr_create_raw_kvs(mr, 0); kvs->c.key_data = kf; kvs->c.value_data = vf; kvs->c.info_line0.file = file; kvs->c.info_line0.func = func; kvs->c.info_line0.line = line; if (kmr_ckpt_enabled(mr)) { kmr_ckpt_restore_ckpt(kvs); } return kvs; } /** Moves the contents of the input KVI to the output KVO. It consumes the input KVI. Calling kmr_map() with a null map-function has the same effect. Effective-options: TAKE_CKPT. See struct kmr_option. */ int kmr_move_kvs(KMR_KVS *kvi, KMR_KVS *kvo, struct kmr_option opt) { assert(kvi != 0 && kvo != 0 && kvi->c.magic == KMR_KVS_ONCORE && kvo->c.magic == KMR_KVS_ONCORE && kvi->c.oncore && kvo->c.oncore); assert(kvi->c.key_data == kvo->c.key_data && kvi->c.value_data == kvo->c.value_data); assert(kvi->c.stowed && !kvo->c.stowed); // struct kmr_option kmr_supported = {.take_ckpt = 1}; // kmr_check_fn_options(kvo->c.mr, kmr_supported, opt, __func__); if (kmr_ckpt_enabled(kvo->c.mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { kvi->c.first_block = 0; kvi->c.ms = 0; kmr_free_kvs(kvi); return MPI_SUCCESS; } } /* Copy state. */ kvo->c.stowed = kvi->c.stowed; kvo->c.nogrow = kvi->c.nogrow; kvo->c.sorted = kvi->c.sorted; kvo->c.element_count = kvi->c.element_count; kvo->c.storage_netsize = kvi->c.storage_netsize; kvo->c.block_count = kvi->c.block_count; kvo->c.first_block = kvi->c.first_block; kvo->c.ms = kvi->c.ms; if (kmr_ckpt_enabled(kvo->c.mr)) { kmr_ckpt_save_kvo_whole(kvo->c.mr, kvo); } /* Dispose of input. */ kvi->c.first_block = 0; kvi->c.ms = 0; int cc = kmr_free_kvs(kvi); assert(cc == MPI_SUCCESS); if (kmr_ckpt_enabled(kvo->c.mr)) { kmr_ckpt_progress_fin(kvo->c.mr); } return MPI_SUCCESS; } static inline int kmr_free_kvs_oncore(KMR_KVS *kvs) { struct kmr_kvs_block *b = kvs->c.first_block; while (b != 0) { struct kmr_kvs_block *bn = b->next; kmr_free(b, b->size); b = bn; } if (kvs->c.ms != 0) { long cnt = kvs->c.element_count; size_t sz = (sizeof(struct kmr_map_ms_state) + (sizeof(char) * (size_t)cnt)); kmr_free(kvs->c.ms, sz); } if (kvs->c.temporary_data != 0) { kmr_free(kvs->c.temporary_data, 0); } kvs->c.magic = KMR_KVS_BAD; /* Delete checkpoint file if exists. */ if (kmr_ckpt_enabled(kvs->c.mr)) { kmr_ckpt_remove_ckpt(kvs); } kmr_free(kvs, sizeof(struct kmr_kvs_oncore)); return MPI_SUCCESS; } /** Releases a key-value stream (type KMR_KVS). Normally, mapper/shuffler/reducer consumes and frees the input key-value stream, and explicit calls are unnecessary. Here, mapper/shuffler/reducer includes kmr_map(), kmr_map_on_rank_zero(), kmr_map_ms(), kmr_shuffle(), kmr_replicate(), kmr_reduce(), and kmr_reduce_as_one(). */ int kmr_free_kvs(KMR_KVS *kvs) { if (!KMR_KVS_MAGIC_OK(kvs->c.magic)) { kmr_error(0, "kmr_free_kvs: kvs already freed or corrupted"); } kmr_unlink_kvs(kvs); int cc; if (kvs->c.magic == KMR_KVS_ONCORE) { cc = kmr_free_kvs_oncore(kvs); return cc; } else if (kvs->c.magic == KMR_KVS_PUSHOFF) { cc = kmr_free_kvs_pushoff(kvs, 1); return cc; } else { assert((kvs->c.magic == KMR_KVS_ONCORE) || (kvs->c.magic == KMR_KVS_PUSHOFF)); assert(NEVERHERE); return 0; } } /* ================================================================ */ /* Allocates a new block of storage as a current-block. When the SIZE=1, it allocates a block by the pre-specified block-size, and allows it to glow incrementally. When the SIZE!=1, it allocates a block by that size after increasing it for the spaces of a header and an end-of-block marker. It sets the STORAGE_NETSIZE field, and places an end-of-block marker, because all key-value pairs should fit in the given size. It accepts zero as a legitimate size. */ int kmr_allocate_block(KMR_KVS *kvs, size_t size) { if (size != 1) { assert(kvs->c.element_count == 0 && kvs->c.storage_netsize == 0 && kvs->c.block_count == 0 && kvs->c.first_block == 0 && kvs->c.current_block == 0 && kvs->c.adding_point == 0); } size_t netsz; size_t sz; if (size == 0) { kvs->c.block_size = 0; kvs->c.nogrow = 1; return MPI_SUCCESS; } else if (size == 1) { netsz = 0; sz = kvs->c.block_size; assert(kvs->c.nogrow == 0); } else { assert(kvs->c.first_block == 0 && kvs->c.current_block == 0 && kvs->c.block_count == 0 && kvs->c.adding_point == 0); assert(size >= kmr_kvs_entry_header); netsz = size; sz = (netsz + kmr_kvs_block_header + kmr_kvs_entry_header); kvs->c.block_size = sz; kvs->c.storage_netsize = netsz; kvs->c.nogrow = 1; } struct kmr_kvs_block *b = kmr_malloc(sz); kmr_kvs_reset_block(kvs, b, sz, netsz); kmr_kvs_insert_block(kvs, b); return MPI_SUCCESS; } /* Adjusts the adding-point to the end for putting key-value pairs at once. It is only called when the whole key-value stream size is known in advance. */ static inline void kmr_kvs_adjust_adding_point(KMR_KVS *kvs) { if (kvs->c.block_count == 0) { assert(kvs->c.current_block == 0 && kvs->c.adding_point == 0); } else { assert(kvs->c.current_block != 0 && kvs->c.adding_point != 0); struct kmr_kvs_block *b = kvs->c.current_block; assert(kmr_kvs_first_entry(kvs, b) == kvs->c.adding_point); kvs->c.adding_point = kmr_kvs_last_entry_limit(kvs, b); assert(kvs->c.adding_point == kmr_kvs_adding_point(b)); } } /* Adds a key-value pair. It is a body of kmr_add_kv(), without a mutex. It modifies kmr_kv_box XKV (when non-null) to return the pointers to the opaque fields, when a key or a value is opaque. It does not move actual data when RESERVE_SPACE_ONLY=1. */ static inline int kmr_add_kv_nomutex(KMR_KVS *kvs, const struct kmr_kv_box kv, struct kmr_kv_box *xkv, _Bool reserve_space_only) { kmr_assert_kv_sizes(kvs, kv); assert(!kvs->c.nogrow || kvs->c.storage_netsize != 0); KMR *mr = kvs->c.mr; int cc; size_t sz = kmr_kvs_entry_size_of_box(kvs, kv); if (sz > (kvs->c.element_size_limit)) { char ee[80]; snprintf(ee, 80, "key-value too large (size=%zd)", sz); kmr_error(mr, ee); } if (kvs->c.first_block == 0) { assert(kvs->c.element_count == 0); cc = kmr_allocate_block(kvs, 1); assert(cc == MPI_SUCCESS); } if (!kmr_kvs_entry_fits_in_block(kvs, kvs->c.current_block, sz)) { assert(!kvs->c.nogrow); kmr_kvs_mark_entry_tail(kvs->c.adding_point); cc = kmr_allocate_block(kvs, 1); assert(cc == MPI_SUCCESS); } struct kmr_kvs_entry *e = kvs->c.adding_point; kmr_poke_kv(e, kv, xkv, kvs, reserve_space_only); if (!kvs->c.nogrow) { kvs->c.storage_netsize += kmr_kvs_entry_netsize(e); } kvs->c.current_block->partial_element_count++; kvs->c.current_block->fill_size += kmr_kvs_entry_size(kvs, e); kvs->c.adding_point = kmr_kvs_next_entry(kvs, e); kvs->c.element_count++; return MPI_SUCCESS; } /** Adds a key-value pair. (It is with serialization when a map-function is threaded). */ int kmr_add_kv(KMR_KVS *kvs, const struct kmr_kv_box kv) { kmr_assert_kvs_ok(0, kvs, 0, 1); int cc; if (kvs->c.magic == KMR_KVS_ONCORE) { KMR_OMP_CRITICAL_ { cc = kmr_add_kv_nomutex(kvs, kv, 0, 0); } return cc; } else if (kvs->c.magic == KMR_KVS_PUSHOFF) { KMR_OMP_CRITICAL_ { cc = kmr_add_kv_pushoff(kvs, kv); } return cc; } else { assert((kvs->c.magic == KMR_KVS_ONCORE) || (kvs->c.magic == KMR_KVS_PUSHOFF)); assert(NEVERHERE); return 0; } } /** Adds a key-value pair as given directly by a pointer. An integer or a double be passed by a pointer (thus like &v). */ int kmr_add_kv1(KMR_KVS *kvs, void *k, int klen, void *v, int vlen) { union kmr_unit_sized xk; switch (kvs->c.key_data) { case KMR_KV_BAD: xassert(kvs->c.key_data != KMR_KV_BAD); xk.i = 0; break; case KMR_KV_INTEGER: xk.i = *(long *)k; break; case KMR_KV_FLOAT8: xk.d = *(double *)k; break; case KMR_KV_OPAQUE: case KMR_KV_CSTRING: case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: xk.p = k; break; default: xassert(NEVERHERE); xk.i = 0; break; } union kmr_unit_sized xv; switch (kvs->c.value_data) { case KMR_KV_BAD: xassert(kvs->c.value_data != KMR_KV_BAD); xv.i = 0; break; case KMR_KV_INTEGER: xv.i = *(long *)v; break; case KMR_KV_FLOAT8: xv.d = *(double *)v; break; case KMR_KV_OPAQUE: case KMR_KV_CSTRING: case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: xv.p = v; break; default: xassert(NEVERHERE); xv.i = 0; break; } struct kmr_kv_box kv = {.klen = klen, .vlen = vlen, .k = xk, .v = xv}; int cc; cc = kmr_add_kv(kvs, kv); return cc; } /** Adds a key-value pair, but only allocates a space and returns the pointers to the key and the value parts. It may enable to create a large key/value data directly in the space. It does not return a proper value if a key/value field is not a pointer. (It cannot be used with a "push-off" key-value stream, because its buffer will be sent out and late fill-in the buffer causes a race). */ int kmr_add_kv_space(KMR_KVS *kvs, const struct kmr_kv_box kv, void **keyp, void **valuep) { kmr_assert_kvs_ok(0, kvs, 0, 1); assert(kvs->c.magic == KMR_KVS_ONCORE); int cc; struct kmr_kv_box xkv = { .k.p = 0, .v.p = 0 }; KMR_OMP_CRITICAL_ { cc = kmr_add_kv_nomutex(kvs, kv, &xkv, 1); } if (keyp != 0) { *keyp = (void *)xkv.k.p; } if (valuep != 0) { *valuep = (void *)xkv.v.p; } return cc; } int kmr_add_kv_quick_(KMR_KVS *kvs, const struct kmr_kv_box kv) { int cc = kmr_add_kv_nomutex(kvs, kv, 0, 0); return cc; } /** Marks finished adding key-value pairs. Further addition will be prohibited. Normally, mapper/shuffler/reducer finishes the output key-value stream by itself, and explicit calls are unnecessary. Here, mapper/shuffler/reducer includes kmr_map(), kmr_map_on_rank_zero(), kmr_map_ms(), kmr_shuffle(), kmr_replicate(), and kmr_reduce(). */ int kmr_add_kv_done(KMR_KVS *kvs) { kmr_assert_kvs_ok(0, kvs, 0, 1); if (kvs->c.magic == KMR_KVS_ONCORE) { if (kvs->c.stowed) { kmr_error(kvs->c.mr, "kmr_add_kv_done: may be called already"); } if (kvs->c.element_count == 0) { assert(kvs->c.current_block == 0 && kvs->c.adding_point == 0); } else { assert(kvs->c.current_block != 0 && kvs->c.adding_point != 0); kmr_kvs_mark_entry_tail(kvs->c.adding_point); } kvs->c.stowed = 1; kvs->c.current_block = 0; kvs->c.adding_point = 0; assert(kvs->c.block_count == 0 || kvs->c.first_block != 0); } else if (kvs->c.magic == KMR_KVS_PUSHOFF) { kmr_add_kv_done_pushoff(kvs); } else { assert((kvs->c.magic == KMR_KVS_ONCORE) || (kvs->c.magic == KMR_KVS_PUSHOFF)); assert(NEVERHERE); return 0; } return MPI_SUCCESS; } /** Adds a key-value pair of strings. The key and value fields should be of opaque data. */ int kmr_add_string(KMR_KVS *kvs, const char *k, const char *v) { if (!((kvs->c.key_data == KMR_KV_OPAQUE || kvs->c.key_data == KMR_KV_CSTRING) && (kvs->c.value_data == KMR_KV_OPAQUE || kvs->c.value_data == KMR_KV_CSTRING))) { kmr_error(kvs->c.mr, "key-value data-types need be opaque for strings"); } size_t klen = (strlen(k) + 1); size_t vlen = (strlen(v) + 1); assert(klen <= INT_MAX && vlen <= INT_MAX); struct kmr_kv_box kv; kv.klen = (int)klen; kv.k.p = k; kv.vlen = (int)vlen; kv.v.p = v; int cc = kmr_add_kv(kvs, kv); return cc; } /** Adds a given key-value pair unmodified. It is a map-function. */ int kmr_add_identity_fn(const struct kmr_kv_box kv, const KMR_KVS *kvi, KMR_KVS *kvo, void *arg, const long i) { kmr_add_kv(kvo, kv); return MPI_SUCCESS; } /* Packs fields as opaque. When key or value field is a pointer, fields need to be packed to make data-exchanges easy. */ static int kmr_collapse_as_opaque(KMR_KVS *kvi, KMR_KVS *kvo, _Bool inspectp) { assert(kvi != 0 && kvo != 0); assert(kmr_fields_pointer_p(kvi) || kvi->c.block_count > 1); int cc; cc = kmr_allocate_block(kvo, kvi->c.storage_netsize); assert(cc == MPI_SUCCESS); struct kmr_option collapse = {.collapse = 1, .inspect = inspectp}; cc = kmr_map(kvi, kvo, 0, collapse, kmr_add_identity_fn); assert(cc == MPI_SUCCESS); return MPI_SUCCESS; } /** Packs locally the contents of a key-value stream to a byte array. It is used to save or to send a key-value stream. It returns the allocated memory with its size, and it should be freed by the user. It may fail on allocating a buffer, and then it returns MPI_ERR_BUFFER. Its reverse is performed by kmr_restore_kvs(). */ int kmr_save_kvs(KMR_KVS *kvs, void **dataq, size_t *szq, struct kmr_option opt) { if (kvs == 0) { kmr_error_at_site(0, "Null input kvs", 0); } else if (!KMR_KVS_MAGIC_OK(kvs->c.magic)) { kmr_error_at_site(0, "Bad input kvs (freed or corrupted)", 0); } assert(kvs->c.magic == KMR_KVS_ONCORE); kmr_check_fn_options(kvs->c.mr, kmr_noopt, opt, __func__); /*assert(kvs->c.current_block == 0 && kvs->c.adding_point == 0);*/ if (kvs->c.ms != 0 || kvs->c.temporary_data != 0) { kmr_warning(kvs->c.mr, 5, "Some fields in KVS may be lost in saved image"); } int cc; if (kmr_fields_pointer_p(kvs) || (kvs->c.block_count > 1)) { enum kmr_kv_field keyf = kmr_unit_sized_or_opaque(kvs->c.key_data); enum kmr_kv_field valf = kmr_unit_sized_or_opaque(kvs->c.value_data); KMR_KVS *kvs1 = kmr_create_kvs(kvs->c.mr, keyf, valf); cc = kmr_collapse_as_opaque(kvs, kvs1, 0); assert(cc == MPI_SUCCESS); assert(!kmr_fields_pointer_p(kvs1) && kvs->c.block_count <= 1); cc = kmr_save_kvs(kvs1, dataq, szq, kmr_noopt); assert(cc == MPI_SUCCESS); kmr_free_kvs(kvs1); return MPI_SUCCESS; } assert(!kmr_fields_pointer_p(kvs)); size_t netsz = kvs->c.storage_netsize; size_t blocksz = (netsz + kmr_kvs_block_header + kmr_kvs_entry_header); size_t sz = (sizeof(KMR_KVS) + blocksz); unsigned char *b = malloc(sz); if (b == 0) { return MPI_ERR_BUFFER; } KMR_KVS *h = (void *)b; struct kmr_kvs_block *s = (void *)(b + sizeof(KMR_KVS)); memcpy(h, kvs, sizeof(KMR_KVS)); h->c.magic = KMR_KVS_ONCORE_PACKED; h->c.mr = 0; h->c.link.next = 0; h->c.link.prev = 0; h->c.block_count = 1; h->c.first_block = 0; h->c.current_block = 0; h->c.adding_point = 0; h->c.ms = 0; h->c.temporary_data = 0; if (kvs->c.block_count == 0) { /*nothing*/ } else if (kvs->c.block_count == 1) { memcpy(s, kvs->c.first_block, blocksz); s->size = blocksz; } else { xassert(NEVERHERE); } *dataq = b; *szq = sz; return MPI_SUCCESS; } /** Unpacks locally the contents of a key-value stream from a byte array. It is a reverse of kmr_save_kvs(). */ int kmr_restore_kvs(KMR_KVS *kvo, void *data, size_t sz_, struct kmr_option opt) { assert(kvo != 0 && kvo->c.magic == KMR_KVS_ONCORE); kmr_check_fn_options(kvo->c.mr, kmr_noopt, opt, __func__); int cc; unsigned char *b = data; KMR_KVS *h = (void *)b; unsigned char *s = (b + sizeof(KMR_KVS)); if (h->c.magic != KMR_KVS_ONCORE_PACKED) { kmr_warning(kvo->c.mr, 1, "Bad packed data, magic mismatch"); return MPI_ERR_TYPE; } size_t netsz = h->c.storage_netsize; size_t blocksz = (netsz + kmr_kvs_block_header + kmr_kvs_entry_header); cc = kmr_allocate_block(kvo, netsz); assert(cc == MPI_SUCCESS); if (netsz != 0) { memcpy(kvo->c.first_block, s, blocksz); } kvo->c.key_data = h->c.key_data; kvo->c.value_data = h->c.value_data; assert(kvo->c.sorted == 0); kvo->c.element_count = h->c.element_count; kmr_kvs_adjust_adding_point(kvo); kmr_add_kv_done(kvo); return MPI_SUCCESS; } /* ================================================================ */ /* Calls a map-function on entries in aggregate. EV holds EVCNT entries. MAPCOUNT is a counter of mapped entries from the beginning. */ static inline int kmr_map_parked(struct kmr_kv_box *ev, long evcnt, long mapcount, _Bool k_reclaim, _Bool v_reclaim, KMR_KVS *kvi, KMR_KVS *kvo, kmr_mapfn_t m, void *arg, struct kmr_option opt) { int cc; KMR *mr = kvi->c.mr; long cnt = kvi->c.element_count; if (mr->single_thread || opt.nothreading) { for (long i = 0; i < evcnt; i++) { double t0 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); cc = (*m)(ev[i], kvi, kvo, arg, (mapcount + i)); double t1 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); if (cc != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Map-fn returned with error cc=%d", cc); kmr_error(mr, ee); } if (mr->log_traces != 0) { kmr_log_map(mr, kvi, &ev[i], (mapcount + 1), cnt, m, (t1 - t0)); } } } else { if (kvo != 0) { kvo->c.under_threaded_operation = 1; } KMR_OMP_PARALLEL_FOR_ for (long i = 0; i < evcnt; i++) { double t0 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); int ccx = (*m)(ev[i], kvi, kvo, arg, (mapcount + i)); double t1 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); if (ccx != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Map-fn returned with error cc=%d", ccx); kmr_error(mr, ee); } if (mr->log_traces != 0) { kmr_log_map(mr, kvi, &ev[i], (mapcount + 1), cnt, m, (t1 - t0)); } } if (kvo != 0) { kvo->c.under_threaded_operation = 0; } } for (long i = 0; i < evcnt; i++) { if (k_reclaim) { kmr_free((void *)ev[i].k.p, (size_t)ev[i].klen); } if (v_reclaim) { kmr_free((void *)ev[i].v.p, (size_t)ev[i].vlen); } } return MPI_SUCCESS; } /** Maps by skipping the number of entries. It calls a map-function on entries from FROM, skipping by STRIDE, up to LIMIT non-inclusive. See kmr_map(). */ int kmr_map_skipping(long from, long stride, long limit, _Bool stop_when_some_added, KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_mapfn_t m) { kmr_assert_kvs_ok(kvi, kvo, 1, 0); assert(from >= 0 && stride > 0 && limit >= 0); assert(kvi->c.current_block == 0); limit = ((limit != 0) ? limit : LONG_MAX); KMR *mr = kvi->c.mr; if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)){ if (kvo != 0 && !opt.keep_open) { kmr_add_kv_done(kvo); } if (!opt.inspect) { kmr_free_kvs(kvi); } return MPI_SUCCESS; } from = kmr_ckpt_first_unprocessed_kv(mr); kmr_ckpt_save_kvo_block_init(mr, kvo); } int cc; if (mr->step_sync) { cc = MPI_Barrier(mr->comm); assert(MPI_SUCCESS); } if (kvo != 0 && opt.collapse) { assert(!kmr_fields_pointer_p(kvo)); } _Bool k_reclaim = (!opt.inspect && (kmr_key_pointer_p(kvi))); _Bool v_reclaim = (!opt.inspect && (kmr_value_pointer_p(kvi))); long evsz = mr->mapper_park_size; struct kmr_kv_box * ev = kmr_malloc((sizeof(struct kmr_kv_box) * (size_t)evsz)); long evcnt = 0; long mapcount = 0; long nextindex = from; long index = 0; kvi->c.current_block = kvi->c.first_block; while (index < kvi->c.element_count) { assert(kvi->c.current_block != 0); struct kmr_kvs_block *b = kvi->c.current_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvi, b); for (int i = 0; i < b->partial_element_count; i++) { assert(e != 0); if (index == nextindex && index < limit) { ev[evcnt++] = kmr_pick_kv(e, kvi); nextindex = (index + stride); if (k_reclaim) { union kmr_unit_sized *w = kmr_point_key(e); w->p = 0; } if (v_reclaim) { union kmr_unit_sized *w = kmr_point_value(e); w->p = 0; } } else { if (k_reclaim) { union kmr_unit_sized *w = kmr_point_key(e); kmr_free((void *)w->p, (size_t)e->klen); w->p = 0; } if (v_reclaim) { union kmr_unit_sized *w = kmr_point_value(e); kmr_free((void *)w->p, (size_t)e->vlen); w->p = 0; } } if (evcnt >= evsz) { cc = kmr_map_parked(ev, evcnt, mapcount, k_reclaim, v_reclaim, kvi, kvo, m, arg, opt); assert(cc == MPI_SUCCESS); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_block_add(mr, kvo, evcnt); } mapcount += evcnt; evcnt = 0; if (stop_when_some_added) { _Bool done; if (mr->stop_at_some_check_globally) { done = 0; } else { done = (kvo->c.element_count != 0); } if (done) { /* Fake as if go to the end. */ index = (kvi->c.element_count - 1); while (b->next != 0) { b = b->next; } } } } e = kmr_kvs_next(kvi, e, 1); index++; } kvi->c.current_block = b->next; } assert(kvi->c.current_block == 0); if (evcnt > 0) { cc = kmr_map_parked(ev, evcnt, mapcount, k_reclaim, v_reclaim, kvi, kvo, m, arg, opt); assert(cc == MPI_SUCCESS); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_block_add(mr, kvo, evcnt); } mapcount += evcnt; evcnt = 0; } if (kvo != 0 && !opt.keep_open) { kmr_add_kv_done(kvo); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_block_fin(mr, kvo); } if (!opt.inspect) { kmr_free_kvs(kvi); } if (ev != 0) { kmr_free(ev, (sizeof(struct kmr_kv_box) * (size_t)evsz)); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_progress_fin(mr); } return MPI_SUCCESS; } /** Maps simply. It consumes the input key-value stream KVI unless INSPECT option is marked. The output key-value stream KVO can be null, but in that case, a map-function cannot add key-value pairs. The pointer ARG is just passed to a map-function as a general argument, where accesses to it should be race-free, since a map-function is called by threads by default. M is the map-function. See the description on the type ::kmr_mapfn_t. It copeis the contents of the input KVI to the output KVO, when a map-function is null. During processing, it first makes an array pointing to the key-value entries in each data block, and works on it for ease threading/parallelization. Effective-options: NOTHREADING, INSPECT, KEEP_OPEN, COLLAPSE, TAKE_CKPT. See struct kmr_option. */ int kmr_map9(_Bool stop_when_some_added, KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_mapfn_t m, const char *file, const int line, const char *func) { int cc; kmr_assert_kvs_ok(kvi, kvo, 1, 0); KMR *mr = kvi->c.mr; struct kmr_option kmr_supported = {.nothreading = 1, .inspect = 1, .keep_open = 1, .collapse = 1, .take_ckpt = 1}; kmr_check_fn_options(mr, kmr_supported, opt, __func__); kmr_trace_entry_t * kte_start = 0; if (mr->kmrviz_trace) { kte_start = kmr_trace_add_entry(mr, KMR_TRACE_EVENT_MAP, 0, kvi, kvo); } struct kmr_code_line info; if (mr->atwork == 0) { info.file = file; info.func = func; info.line = line; mr->atwork = &info; } if (m != 0) { cc = kmr_map_skipping(0, 1, 0, stop_when_some_added, kvi, kvo, arg, opt, m); } else { assert(!opt.inspect && !opt.keep_open); cc = kmr_move_kvs(kvi, kvo, opt); } if (mr->atwork == &info) { mr->atwork = 0; } if (mr->kmrviz_trace) { if (!opt.inspect) { kvi = 0; } kmr_trace_add_entry(mr, KMR_TRACE_EVENT_MAP, kte_start, kvi, kvo); } return cc; } /** Maps sequentially with rank by rank for debugging. See kmr_map. */ int kmr_map_rank_by_rank(KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_mapfn_t m) { KMR *mr = kvi->c.mr; int nprocs = mr->nprocs; int cc; if (mr->rank != 0) { cc = MPI_Recv(0, 0, MPI_INT, (mr->rank - 1), KMR_TAG_MAP_BY_RANK, mr->comm, MPI_STATUS_IGNORE); assert(cc == MPI_SUCCESS); } cc = kmr_map(kvi, kvo, arg, opt, m); assert(cc == MPI_SUCCESS); fflush(0); if (mr->rank != (nprocs - 1)) { usleep(1 * 1000); cc = MPI_Send(0, 0, MPI_INT, (mr->rank + 1), KMR_TAG_MAP_BY_RANK, mr->comm); assert(cc == MPI_SUCCESS); } return MPI_SUCCESS; } /** Extracts a single key-value pair locally in the key-value stream KVI. It is an error when zero or more than one entries are in the KVI. It does not consume the input KVS (INSPECT IMPLIED). The returned key-value entry must be used before freeing the input KVS, when it points to an opaque data. */ int kmr_take_one(KMR_KVS *kvi, struct kmr_kv_box *kv) { kmr_assert_kvs_ok(kvi, 0, 1, 0); assert(kvi->c.current_block == 0); KMR *mr = kvi->c.mr; kvi->c.current_block = kvi->c.first_block; if (kvi->c.element_count == 1) { assert(kvi->c.current_block != 0); struct kmr_kvs_block *b = kvi->c.current_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvi, b); assert(b->partial_element_count == 1); assert(e != 0); *kv = kmr_pick_kv(e, kvi); kvi->c.current_block = 0; return MPI_SUCCESS; } else { if (kvi->c.element_count == 0) { kmr_warning(mr, 1, "kmr_take_one for no entries"); /*return MPI_ERR_COUNT;*/ } else { kmr_warning(mr, 1, "kmr_take_one for multiple entries"); /*return MPI_ERR_COUNT;*/ } MPI_Abort(MPI_COMM_WORLD, 1); return MPI_SUCCESS; } } /** Maps once. It calls a map-function once with a dummy key-value stream and a dummy key-value pair. See kmr_map(). Effective-options: KEEP_OPEN, TAKE_CKPT. See struct kmr_option. */ int kmr_map_once(KMR_KVS *kvo, void *arg, struct kmr_option opt, _Bool rank_zero_only, kmr_mapfn_t m) { kmr_assert_kvs_ok(0, kvo, 0, 1); KMR *mr = kvo->c.mr; struct kmr_option kmr_supported = {.keep_open = 1, .take_ckpt = 1}; kmr_check_fn_options(mr, kmr_supported, opt, __func__); int rank = mr->rank; int cc; kmr_trace_entry_t * kte_start = 0; if (mr->kmrviz_trace) { kte_start = kmr_trace_add_entry(mr, KMR_TRACE_EVENT_MAP_ONCE, 0, 0, kvo); } if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(0, kvo, opt)) { kmr_add_kv_done(kvo); return MPI_SUCCESS; } } if (!rank_zero_only || rank == 0) { struct kmr_kv_box kv = {.klen = 0, .vlen = 0, .k.i = 0, .v.i = 0}; cc = (*m)(kv, 0, kvo, arg, 0); if (cc != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Map-fn returned with error cc=%d", cc); kmr_error(mr, ee); } } if (!opt.keep_open) { cc = kmr_add_kv_done(kvo); assert(cc == MPI_SUCCESS); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_whole(mr, kvo); kmr_ckpt_progress_fin(mr); } if (mr->kmrviz_trace) { kmr_trace_add_entry(mr, KMR_TRACE_EVENT_MAP_ONCE, kte_start, 0, kvo); } return MPI_SUCCESS; } /** Maps on rank0 only. It calls a map-function once with a dummy key-value stream and a dummy key-value pair. It is used to avoid low-level conditionals like (myrank==0). See kmr_map(). Effective-options: KEEP_OPEN, TAKE_CKPT. See struct kmr_option. */ int kmr_map_on_rank_zero(KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_mapfn_t m) { int cc; cc = kmr_map_once(kvo, arg, opt, 1, m); assert(cc == MPI_SUCCESS); return MPI_SUCCESS; } /* ================================================================ */ #if 1 /* Hashes. (MurmurHash3; http://code.google.com/p/smhasher). */ static inline unsigned long kmr_hash_key_opaque(const unsigned char *p, int n) { #define ROT(X,N) ((X) << (N) | (X) >> (64-(N))) #define KEY(V) (k = (V), k *= 0x87c37b91114253d5UL, \ k = ROT(k, 31), k *= 0x4cf5ad432745937fUL) #define MIX() (h ^= k, h = ROT(h, 31), h = h * 5 + 0xe6546b64) #define FIN() (h ^= (h >> 33), h *= 0xff51afd7ed558ccdUL, h ^= (h >> 33), \ h *= 0xc4ceb9fe1a85ec53UL, h ^= (h >> 33)) unsigned long h = 0x85ebca6bUL; /*c2b2ae35*/ unsigned long k; const unsigned long *v = (void *)p; int n8 = (n / 8); int rn = (n - (8 * n8)); const unsigned char *r = &p[(8 * n8)]; for (int i = 0; i < n8; i++) { KEY(v[i]); MIX(); } union {unsigned long i; unsigned char c[8];} u = {.i = 0UL}; for (int i = 0; i < rn; i++) { u.c[i] = r[i]; } KEY(u.i); MIX(); FIN(); return h; #undef ROT #undef KEY #undef MIX #undef FIN } #elif 0 /* (java 1.2 hash). */ static inline unsigned long kmr_hash_key_opaque(const unsigned char *p, int n) { unsigned long hash = 0; for (i = 0 ; i < n ; i++) { hash *= 31; hash += p[i]; } return hash; } #else /* (java 1.0 hash). */ static inline unsigned long kmr_hash_key_opaque(const unsigned char *p, int n) { unsigned long hash = 0; int m, k, i; if (n <= 15) { m = 1; for (i = 0 ; i < n ; i++) { hash += (p[i] * m); m *= 37; } } else { m = 1; k = n / 8; for (i = 0 ; i < n ; i += k) { hash += (p[i] * m); m *= 39; } } return hash; } #endif /* Makes an integer key for a key-value pair for shuffling. It returns the long bit representation for float. This hash is OK for the key_as_rank option. (kmr_hash_key() is for shuffling, and kmr_stable_key() is for sorting). */ static inline signed long kmr_hash_key(const KMR_KVS *kvs, const struct kmr_kv_box kv) { switch (kvs->c.key_data) { case KMR_KV_BAD: xassert(kvs->c.key_data != KMR_KV_BAD); return -1; case KMR_KV_OPAQUE: case KMR_KV_CSTRING: return (signed long)kmr_hash_key_opaque((void *)kv.k.p, kv.klen); case KMR_KV_INTEGER: return kv.k.i; case KMR_KV_FLOAT8: return kv.k.i; case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: xassert(kvs->c.key_data != KMR_KV_POINTER_OWNED && kvs->c.key_data != KMR_KV_POINTER_UNMANAGED); return -1; default: xassert(NEVERHERE); return -1; } } /* Returns an integer of the first 8 bytes, shifted to the right by one-bit to make it positive. It is consistent with the ordering by memcmp(). */ static inline long kmr_stable_key_opaque(const struct kmr_kv_box kv) { unsigned char *p = (unsigned char *)kv.k.p; int n = kv.klen; unsigned long hash = 0; for (int i = 0; i < (int)sizeof(long); i++) { unsigned char v = ((i < n) ? p[i] : 0); hash = ((hash << 8) + v); } return (long)(hash >> 1); } /* Makes an integer key for a key-value pair for sorting. It returns a signed value for comparing integers. It is consistent with the ordering by memcmp() for opaque keys. (kmr_hash_key() is for shuffling, and kmr_stable_key() is for sorting). */ signed long kmr_stable_key(const struct kmr_kv_box kv, const KMR_KVS *kvs) { switch (kvs->c.key_data) { case KMR_KV_BAD: xassert(kvs->c.key_data != KMR_KV_BAD); return -1; case KMR_KV_OPAQUE: case KMR_KV_CSTRING: return kmr_stable_key_opaque(kv); case KMR_KV_INTEGER: return kv.k.i; case KMR_KV_FLOAT8: { long v0 = kv.k.i; long v1 = ((v0 >= 0L) ? v0 : ((-v0) | (1L << 63))); /*assert(v0 >= 0 || v1 < 0);*/ return v1; } case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: xassert(kvs->c.key_data != KMR_KV_POINTER_OWNED && kvs->c.key_data != KMR_KV_POINTER_UNMANAGED); return -1; default: xassert(NEVERHERE); return -1; } } /* Determines a rank to which this key-value entry is directed. It is bases on the hashed keys. */ int kmr_pitch_rank(const struct kmr_kv_box kv, KMR_KVS *kvs) { unsigned int nprocs = (unsigned int)kvs->c.mr->nprocs; unsigned long v = (unsigned long)kmr_hash_key(kvs, kv); unsigned int h = (((v >> 32) ^ v) & ((1L << 32) - 1)); return (int)(h % nprocs); } /* Compares in three-way, returning -1, 0, or 1. */ #define KMR_CMP3(X, Y) (((X) == (Y)) ? 0 : ((X) < (Y)) ? -1 : 1) /* Compares byte strings lexicographically. This is compatible to memcmp() when the lengths are equal, for the terasort requirement. */ static inline int kmr_compare_lexicographically(const unsigned char *p, const int plen, const unsigned char *q, const int qlen) { int s = MIN(plen, qlen); #if 0 for (int i = 0; i < s; i++) { if (p[i] != q[i]) { return (p[i] - q[i]); } } #endif int cc = memcmp(p, q, (size_t)s); if (cc != 0) { return cc; } else { return (plen - qlen); } } /* Compares keys lexicographically as byte strings. */ static int kmr_compare_opaque(const struct kmr_kv_box *p, const struct kmr_kv_box *q) { return kmr_compare_lexicographically((unsigned char *)p->k.p, p->klen, (unsigned char *)q->k.p, q->klen); } static int kmr_compare_integer(const struct kmr_kv_box *p0, const struct kmr_kv_box *p1) { return KMR_CMP3(p0->k.i, p1->k.i); } static int kmr_compare_float8(const struct kmr_kv_box *p0, const struct kmr_kv_box *p1) { return KMR_CMP3(p0->k.d, p1->k.d); } /* Compares keys lexicographically as byte strings. */ static int kmr_compare_record_opaque(const struct kmr_keyed_record *p0, const struct kmr_keyed_record *p1) { struct kmr_kv_box b0 = kmr_pick_kv2(p0->e, KMR_KV_OPAQUE, KMR_KV_OPAQUE); struct kmr_kv_box b1 = kmr_pick_kv2(p1->e, KMR_KV_OPAQUE, KMR_KV_OPAQUE); return kmr_compare_lexicographically((unsigned char *)b0.k.p, b0.klen, (unsigned char *)b1.k.p, b1.klen); } /* (UNUSED) Sorting uses the key part of the record and it does not peek in the kmr_kv_box. */ static int kmr_compare_record_integer_(const struct kmr_keyed_record *p0, const struct kmr_keyed_record *p1) { assert(NEVERHERE); struct kmr_kv_box b0 = kmr_pick_kv2(p0->e, KMR_KV_OPAQUE, KMR_KV_OPAQUE); struct kmr_kv_box b1 = kmr_pick_kv2(p1->e, KMR_KV_OPAQUE, KMR_KV_OPAQUE); long v0 = b0.k.i; long v1 = b1.k.i; return KMR_CMP3(v0, v1); } /* (UNUSED) Sorting uses the key part of the record and it does not peek in the kmr_kv_box. */ static int kmr_compare_record_float8_(const struct kmr_keyed_record *p0, const struct kmr_keyed_record *p1) { assert(NEVERHERE); struct kmr_kv_box b0 = kmr_pick_kv2(p0->e, KMR_KV_OPAQUE, KMR_KV_OPAQUE); struct kmr_kv_box b1 = kmr_pick_kv2(p1->e, KMR_KV_OPAQUE, KMR_KV_OPAQUE); double v0 = b0.k.d; double v1 = b1.k.d; return KMR_CMP3(v0, v1); } /* Returns an appropriate comparator for kmr_kv_box. */ kmr_sorter_t kmr_choose_sorter(const KMR_KVS *kvs) { switch (kvs->c.key_data) { case KMR_KV_BAD: xassert(kvs->c.key_data != KMR_KV_BAD); return 0; case KMR_KV_INTEGER: return kmr_compare_integer; case KMR_KV_FLOAT8: return kmr_compare_float8; case KMR_KV_OPAQUE: case KMR_KV_CSTRING: case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: return kmr_compare_opaque; default: xassert(NEVERHERE); return 0; } } /* Returns an appropriate comparator for keyed-records. It is only called for KMR_KV_OPAQUE. */ static kmr_record_sorter_t kmr_choose_record_sorter(const KMR_KVS *kvs) { switch (kvs->c.key_data) { case KMR_KV_BAD: xassert(kvs->c.key_data != KMR_KV_BAD); return 0; case KMR_KV_INTEGER: assert(NEVERHERE); return kmr_compare_record_integer_; case KMR_KV_FLOAT8: assert(NEVERHERE); return kmr_compare_record_float8_; case KMR_KV_OPAQUE: case KMR_KV_CSTRING: case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: return kmr_compare_record_opaque; default: xassert(NEVERHERE); return 0; } } #if 0 /* Copies the entries as keyed-records with hashed keys for shuffling. */ static int kmr_copy_record_shuffle_fn(const struct kmr_kv_box kv, const KMR_KVS *kvi, KMR_KVS *kvo, void *p, const long i) { return MPI_SUCCESS; } /* Copies the entries as keyed-records with stable keys for sorting. */ static int kmr_copy_record_sorting_fn(const struct kmr_kv_box kv, const KMR_KVS *kvi, KMR_KVS *kvo, void *p, const long i) { return MPI_SUCCESS; } #endif /** Compares the key field of keyed-records for qsort/bsearch. */ static int kmr_icmp(const void *a0, const void *a1) { const struct kmr_keyed_record *p0 = a0; const struct kmr_keyed_record *p1 = a1; long v0 = p0->v; long v1 = p1->v; return KMR_CMP3(v0, v1); } static int kmr_sort_locally_lo(KMR_KVS *kvi, KMR_KVS *kvo, _Bool shuffling, _Bool ranking, struct kmr_option opt) { kmr_assert_kvs_ok(kvi, kvo, 1, 1); assert(kmr_shuffle_compatible_p(kvo, kvi)); KMR *mr = kvi->c.mr; kmr_trace_entry_t * kte_start = 0; if (mr->kmrviz_trace) { kte_start = kmr_trace_add_entry(mr, KMR_TRACE_EVENT_SORT, 0, kvi, kvo); } if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { kmr_add_kv_done(kvo); kvo->c.sorted = 1; if (!opt.inspect) { kmr_free_kvs(kvi); } return MPI_SUCCESS; } } _Bool twostep = !mr->one_step_sort; _Bool primekey = ((kvi->c.key_data == KMR_KV_INTEGER) || (kvi->c.key_data == KMR_KV_FLOAT8)); double timestamp[5]; int cc; long cnt = kvi->c.element_count; timestamp[0] = MPI_Wtime(); size_t evsz = (sizeof(struct kmr_keyed_record) * (size_t)cnt); struct kmr_keyed_record *ev = kmr_malloc(evsz); #if 0 struct kmr_option inspect = { .inspect = 1, .nothreading = opt.nothreading }; if (shuffling) { cc = kmr_map(kvi, 0, ev, inspect, kmr_copy_record_shuffle_fn); assert(cc == MPI_SUCCESS); } else { cc = kmr_map(kvi, 0, ev, inspect, kmr_copy_record_sorting_fn); assert(cc == MPI_SUCCESS); } #else cc = kmr_retrieve_keyed_records(kvi, ev, cnt, shuffling, ranking); assert(cc == MPI_SUCCESS); #endif timestamp[1] = MPI_Wtime(); if (shuffling || twostep || primekey) { if (mr->single_thread || opt.nothreading) { qsort(ev, (size_t)cnt, sizeof(struct kmr_keyed_record), kmr_icmp); } else { kmr_isort(ev, (size_t)cnt, sizeof(struct kmr_keyed_record), mr->sort_threads_depth); } } timestamp[2] = MPI_Wtime(); if (!shuffling && !primekey) { /* Sort the array sorted by hashed keys, again by true keys. */ long *runs = kmr_malloc(sizeof(long) * (size_t)cnt); long nruns = 0; if (twostep) { long i = 0; while (i < cnt) { do { i++; if (i == cnt) { break; } cc = KMR_CMP3(ev[i - 1].v, ev[i].v); } while (cc == 0); assert(nruns < cnt); runs[nruns] = i; nruns++; } assert(i == cnt && (cnt == 0 || runs[nruns - 1] == cnt)); } else { nruns = (cnt == 0 ? 0 : 1); runs[0] = cnt; } kmr_record_sorter_t cmp1 = kmr_choose_record_sorter(kvi); if (mr->single_thread || opt.nothreading) { for (long k = 0; k < nruns; k++) { long j = (k == 0 ? 0 : runs[k - 1]); long i = runs[k]; assert(j < i); if ((i - j) > 1) { qsort(&ev[j], (size_t)(i - j), sizeof(struct kmr_keyed_record), (kmr_qsorter_t)cmp1); } } } else { KMR_OMP_PARALLEL_FOR_ for (long k = 0; k < nruns; k++) { long j = (k == 0 ? 0 : runs[k - 1]); long i = runs[k]; assert(j < i); if ((i - j) > 1) { qsort(&ev[j], (size_t)(i - j), sizeof(struct kmr_keyed_record), (kmr_qsorter_t)cmp1); } } } kmr_free(runs, (sizeof(long) * (size_t)cnt)); } timestamp[3] = MPI_Wtime(); size_t sz = kvi->c.storage_netsize; cc = kmr_allocate_block(kvo, sz); assert(cc == MPI_SUCCESS); /*NEED-THREADING*/ for (long i = 0 ; i < cnt; i++) { struct kmr_kv_box kv = kmr_pick_kv(ev[i].e, kvi); kmr_add_kv_nomutex(kvo, kv, 0, 0); } timestamp[4] = MPI_Wtime(); assert(sz == 0 || kmr_kvs_entry_tail_p(kvo->c.adding_point)); assert(sz == 0 || kvo->c.block_count == 1); kmr_add_kv_done(kvo); kmr_assert_on_tail_marker(kvo); kvo->c.sorted = 1; kmr_free(ev, evsz); _Bool tracing = mr->trace_sorting; if (tracing && (5 <= mr->verbosity)) { fprintf(stderr, (";;KMR [%05d] kmr_sort_locally" " time=(%f %f %f %f) (msec)\n"), mr->rank, ((timestamp[1] - timestamp[0]) * 1e3), ((timestamp[2] - timestamp[1]) * 1e3), ((timestamp[3] - timestamp[2]) * 1e3), ((timestamp[4] - timestamp[3]) * 1e3)); fflush(0); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_whole(mr, kvo); } if (!opt.inspect) { kmr_free_kvs(kvi); kvi = 0; } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_progress_fin(mr); } if (mr->kmrviz_trace) { kmr_trace_add_entry(mr, KMR_TRACE_EVENT_SORT, kte_start, kvi, kvo); } return MPI_SUCCESS; } /** Reorders key-value pairs in a single rank. It sorts pairs when SHUFFLING is false, or gathers pairs with the same hashed keys adjacent when SHUFFLING is true. It only respects for not ordering but just equality when shuffling. The sort-keys for shuffling are destination ranks for shuffling (taking a modulo of the hashed key with nprocs). As a sorting, it is NOT-STABLE due to quick-sort used inside. It converts pointer keys and values to opaque ones for sending.\n Sorting on a key-value stream is by memcmp(), unless the keys are integer or floating-point numbers (ordering on integers and memcmp() are different). Sorting on non-numbers is performed in two steps: the first step sorts by the integer rankings, and the second by the specified comparator. And thus, the comparator is required to have a corresponding generator of integer rankings. It consumes the input key-value stream. Effective-options: NOTHREADING, INSPECT, KEY_AS_RANK. */ int kmr_sort_locally(KMR_KVS *kvi, KMR_KVS *kvo, _Bool shuffling, struct kmr_option opt) { kmr_assert_kvs_ok(kvi, kvo, 1, 1); assert(kmr_shuffle_compatible_p(kvo, kvi)); struct kmr_option kmr_supported = {.nothreading = 1, .inspect = 1, .key_as_rank = 1}; kmr_check_fn_options(kvi->c.mr, kmr_supported, opt, __func__); _Bool ranking = opt.key_as_rank; kmr_sort_locally_lo(kvi, kvo, shuffling, ranking, opt); return MPI_SUCCESS; } /* ================================================================ */ /* Counts the number of entries in the key-value stream. If BOUND_IN_BLOCK is true, it counts only ones in a single data block. */ static inline long kmr_count_entries(KMR_KVS *kvs, _Bool bound_in_block) { kvs->c.current_block = kvs->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvs, kvs->c.first_block); long cnt = 0; while (e != 0) { /*struct kmr_kv_box kv = kmr_pick_kv(e, kvs);*/ /*printf("entry %d %d %s %s\n", kv.klen, kv.vlen, kv.k.p, kv.v.p);*/ cnt++; e = kmr_kvs_next(kvs, e, bound_in_block); } return cnt; } /** Shuffles key-value pairs to the appropriate destination ranks. It first sorts pairs by the destination ranks of the keys, and then exchanges pairs with all-to-all communication. It converts pointer keys and values to opaque ones for sending during the sorting stage. Note that the key-value pairs are sorted by the hash-values prior to exchange. Effective-options: INSPECT, KEY_AS_RANK, TAKE_CKPT. See struct kmr_option. */ int kmr_shuffle(KMR_KVS *kvi, KMR_KVS *kvo, struct kmr_option opt) { kmr_assert_kvs_ok(kvi, kvo, 1, 1); assert(kmr_shuffle_compatible_p(kvo, kvi)); KMR *mr = kvi->c.mr; struct kmr_option kmr_supported = {.inspect = 1, .key_as_rank = 1, .take_ckpt = 1}; kmr_check_fn_options(mr, kmr_supported, opt, __func__); _Bool ranking = opt.key_as_rank; kmr_trace_entry_t * kte_start = 0; if (mr->kmrviz_trace) { kte_start = kmr_trace_add_entry(mr, KMR_TRACE_EVENT_SHUFFLE, 0, kvi, kvo); } /* SKIP SHUFFLING IF MARKED AS SHUFFLED. */ if (kvi->c.magic == KMR_KVS_PUSHOFF) { kmr_pushoff_make_stationary(kvi); } if (kvi->c.shuffled_in_pushoff) { assert(!mr->ckpt_enable); int cc = kmr_move_kvs(kvi, kvo, opt); return cc; } if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { kmr_add_kv_done(kvo); if (!opt.inspect) { kmr_free_kvs(kvi); } return MPI_SUCCESS; } } int kcdc = kmr_ckpt_disable_ckpt(mr); /* Sort for shuffling. */ enum kmr_kv_field keyf = kmr_unit_sized_or_opaque(kvi->c.key_data); enum kmr_kv_field valf = kmr_unit_sized_or_opaque(kvi->c.value_data); struct kmr_option n_opt = opt; n_opt.inspect = 1; KMR_KVS *kvs1 = kmr_create_kvs(mr, keyf, valf); kmr_sort_locally_lo(kvi, kvs1, 1, ranking, n_opt); assert(kvs1->c.stowed); /*kmr_dump_kvs(kvs1, 0);*/ /*kmr_guess_communication_pattern_(kvs1, opt);*/ assert(!kmr_fields_pointer_p(kvs1)); assert(kvs1->c.block_count <= 1); int cc; int nprocs = mr->nprocs; long cnt = kvs1->c.element_count; long *ssz = kmr_malloc(sizeof(long) * (size_t)nprocs); long *sdp = kmr_malloc(sizeof(long) * (size_t)nprocs); long *rsz = kmr_malloc(sizeof(long) * (size_t)nprocs); long *rdp = kmr_malloc(sizeof(long) * (size_t)nprocs); for (int r = 0; r < nprocs; r++) { ssz[r] = 0; rsz[r] = 0; } int rank = 0; assert(kvs1->c.current_block == 0); kvs1->c.current_block = kvs1->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvs1, kvs1->c.first_block); for (long i = 0; i < cnt; i++) { assert(e != 0); struct kmr_kv_box kv = kmr_pick_kv(e, kvs1); int r = (ranking ? (int)kv.k.i : kmr_pitch_rank(kv, kvs1)); assert(0 <= r && r < nprocs); if (ranking && !(0 <= r && r < nprocs)) { kmr_error(mr, "key entries are not ranks"); } if (r < rank) { kmr_error(mr, "key-value entries are not sorted (internal error)"); } ssz[r] += (long)kmr_kvs_entry_netsize(e); rank = r; e = kmr_kvs_next(kvs1, e, 0); } /* Exchange send-receive counts. */ cc = kmr_exchange_sizes(mr, ssz, rsz); assert(cc == MPI_SUCCESS); long sendsz = 0; long recvsz = 0; for (int r = 0; r < nprocs; r++) { sdp[r] = sendsz; sendsz += ssz[r]; rdp[r] = recvsz; recvsz += rsz[r]; } cc = kmr_allocate_block(kvo, (size_t)recvsz); assert(cc == MPI_SUCCESS); struct kmr_kvs_block *sb = kvs1->c.first_block; struct kmr_kvs_entry *sbuf = kmr_kvs_first_entry(kvs1, sb); struct kmr_kvs_block *rb = kvo->c.first_block; struct kmr_kvs_entry *rbuf = kmr_kvs_first_entry(kvo, rb); cc = kmr_alltoallv(mr, sbuf, ssz, sdp, rbuf, rsz, rdp); assert(cc == MPI_SUCCESS); long ocnt = kmr_count_entries(kvo, 1); assert(kvo->c.sorted == 0); kvo->c.element_count = ocnt; if (recvsz != 0) { assert(kvo->c.block_count == 1); rb->partial_element_count = ocnt; rb->fill_size = (size_t)recvsz; } kmr_kvs_adjust_adding_point(kvo); kmr_add_kv_done(kvo); kmr_ckpt_enable_ckpt(mr, kcdc); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_whole(mr, kvo); } if (!opt.inspect) { kmr_free_kvs(kvi); kvi = 0; } assert(kvo->c.element_count == 0 || kvo->c.storage_netsize != 0); xassert(!kmr_fields_pointer_p(kvo)); kmr_free_kvs(kvs1); kmr_free(ssz, (sizeof(long) * (size_t)nprocs)); kmr_free(sdp, (sizeof(long) * (size_t)nprocs)); kmr_free(rsz, (sizeof(long) * (size_t)nprocs)); kmr_free(rdp, (sizeof(long) * (size_t)nprocs)); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_progress_fin(mr); } if (mr->kmrviz_trace) { kmr_trace_add_entry(mr, KMR_TRACE_EVENT_SHUFFLE, kte_start, kvi, kvo); } return MPI_SUCCESS; } /** Replicates key-value pairs to be visible on all ranks, that is, it has the effect of bcast or all-gather. It gathers pairs on rank0 only by the option RANK_ZERO. It moves stably, keeping the ordering of ranks and the ordering of local key-value pairs. Effective-options: INSPECT, RANK_ZERO, TAKE_CKPT. See struct kmr_option. */ int kmr_replicate(KMR_KVS *kvi, KMR_KVS *kvo, struct kmr_option opt) { kmr_assert_kvs_ok(kvi, kvo, 1, 1); KMR *mr = kvi->c.mr; struct kmr_option kmr_supported = {.inspect = 1, .rank_zero = 1, .take_ckpt = 1}; kmr_check_fn_options(mr, kmr_supported, opt, __func__); int nprocs = mr->nprocs; int rank = mr->rank; int cc; KMR_KVS *kvs1; kmr_trace_entry_t * kte_start = 0; if (mr->kmrviz_trace) { kte_start = kmr_trace_add_entry(mr, KMR_TRACE_EVENT_REPLICATE, 0, kvi, kvo); } if (kmr_fields_pointer_p(kvi) || kvi->c.block_count > 1) { enum kmr_kv_field keyf = kvi->c.key_data; enum kmr_kv_field valf = kvi->c.value_data; kvs1 = kmr_create_kvs(mr, keyf, valf); int kcdc = kmr_ckpt_disable_ckpt(mr); cc = kmr_collapse_as_opaque(kvi, kvs1, 1); assert(cc == MPI_SUCCESS); kmr_ckpt_enable_ckpt(mr, kcdc); } else { kvs1 = kvi; } kmr_assert_on_tail_marker(kvs1); assert(kvs1->c.block_count <= 1); if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { kmr_add_kv_done(kvo); if (kvs1 != kvi) { cc = kmr_free_kvs(kvs1); assert(cc == MPI_SUCCESS); } if (!opt.inspect) { cc = kmr_free_kvs(kvi); assert(cc == MPI_SUCCESS); } return MPI_SUCCESS; } } long *rsz = kmr_malloc(sizeof(long) * (size_t)nprocs); long *rdp = kmr_malloc(sizeof(long) * (size_t)nprocs); /* Exchange send-receive counts. */ long ssz = (long)kvs1->c.storage_netsize; cc = kmr_gather_sizes(mr, ssz, rsz); assert(cc == MPI_SUCCESS); long recvsz = 0; if (!opt.rank_zero || rank == 0) { for (int r = 0; r < nprocs; r++) { rdp[r] = recvsz; recvsz += rsz[r]; } } if (!(kvo->c.key_data == kvs1->c.key_data && kvo->c.value_data == kvs1->c.value_data)) { kmr_error(mr, "key-data or value-data types mismatch"); } cc = kmr_allocate_block(kvo, (size_t)recvsz); assert(cc == MPI_SUCCESS); struct kmr_kvs_block *sb = kvs1->c.first_block; struct kmr_kvs_entry *sbuf = kmr_kvs_first_entry(kvs1, sb); struct kmr_kvs_block *rb = kvo->c.first_block; struct kmr_kvs_entry *rbuf = kmr_kvs_first_entry(kvo, rb); cc = kmr_allgatherv(mr, opt.rank_zero, sbuf, ssz, rbuf, rsz, rdp); assert(cc == MPI_SUCCESS); assert(kvo->c.element_count == 0); long ocnt = kmr_count_entries(kvo, 1); kvo->c.element_count = ocnt; if (recvsz != 0) { rb->partial_element_count = ocnt; rb->fill_size = (size_t)recvsz; } kmr_kvs_adjust_adding_point(kvo); cc = kmr_add_kv_done(kvo); assert(cc == MPI_SUCCESS); kmr_assert_on_tail_marker(kvo); assert(kvo->c.element_count == 0 || kvo->c.storage_netsize != 0); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_whole(mr, kvo); } if (kvs1 != kvi) { cc = kmr_free_kvs(kvs1); assert(cc == MPI_SUCCESS); } if (!opt.inspect) { cc = kmr_free_kvs(kvi); assert(cc == MPI_SUCCESS); kvi = 0; } kmr_free(rsz, (sizeof(long) * (size_t)nprocs)); kmr_free(rdp, (sizeof(long) * (size_t)nprocs)); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_progress_fin(mr); } if (mr->kmrviz_trace) { kmr_trace_add_entry(mr, KMR_TRACE_EVENT_REPLICATE, kte_start, kvi, kvo); } return MPI_SUCCESS; } /* ================================================================ */ /* Copies the entires as the keyed-records. The keyed-records hould hashed keys for sorting. */ static int kmr_copy_record_fn(const struct kmr_kv_box kv, const KMR_KVS *kvi, KMR_KVS *kvo, void *p, const long i) { struct kmr_kv_box *ev = p; ev[i] = kv; return MPI_SUCCESS; } /* Reduces key-value pairs. The version "nothreading" uses less memory for sort-records than the version "threading". */ static int kmr_reduce_nothreading(KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_redfn_t r) { xassert(kvi->c.current_block == 0); kmr_sorter_t cmp = kmr_choose_sorter(kvi); KMR *mr = kvi->c.mr; long cnt = kvi->c.element_count; int cc; struct kmr_kv_box *ev = 0; long evsz = 0; kvi->c.current_block = kvi->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvi, kvi->c.first_block); long index = 0; long redcount = 0; if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { if (kvo != 0) { kmr_add_kv_done(kvo); } return MPI_SUCCESS; } long start_from = kmr_ckpt_first_unprocessed_kv(mr); while (index < start_from) { e = kmr_kvs_next(kvi, e, 1); index++; } kmr_ckpt_save_kvo_block_init(mr, kvo); } for (;;) { struct kmr_kvs_entry *ej = e; long n = 0; while (e != 0) { assert(index < cnt); e = kmr_kvs_next(kvi, e, 1); n++; index++; if (e == 0) { break; } //struct kmr_keyed_record s0 = {.v = 0, .e = kmr_pick_kv(ej, kvi)}; //struct kmr_keyed_record s1 = {.v = 0, .e = kmr_pick_kv(e, kvi)}; struct kmr_kv_box kv0 = kmr_pick_kv(ej, kvi); struct kmr_kv_box kv1 = kmr_pick_kv(e, kvi); cc = (*cmp)(&kv0, &kv1); if (cc != 0) { break; } } if (n == 0) { assert(ej == 0 && e == 0); break; } assert(n > 0); if (n > evsz) { evsz = n; ev = kmr_realloc(ev, (sizeof(struct kmr_kv_box) * (size_t)evsz)); assert(ev != 0); } e = ej; for (long i = 0; i < n; i++) { assert(e != 0); ev[i] = kmr_pick_kv(e, kvi); e = kmr_kvs_next(kvi, e, 1); } double t0 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); cc = (*r)(ev, n, kvi, kvo, arg); double t1 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); if (cc != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Reduce-fn returned with error cc=%d", cc); kmr_error(mr, ee); } if (mr->log_traces != 0) { kmr_log_reduce(mr, kvi, ev, n, r, (t1 - t0)); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_block_add(mr, kvo, n); } redcount += n; } assert(index == cnt); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_block_fin(mr, kvo); } if (kvo != 0) { kmr_add_kv_done(kvo); } if (ev != 0) { kmr_free(ev, (sizeof(struct kmr_kv_box) * (size_t)evsz)); } return MPI_SUCCESS; } static int kmr_reduce_threading(_Bool stop_when_some_added, KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_redfn_t r) { int cc; if (kmr_ckpt_enabled(kvi->c.mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { if (kvo != 0) { kmr_add_kv_done(kvo); } return MPI_SUCCESS; } } struct kmr_option inspect = { .inspect = 1, .nothreading = opt.nothreading }; assert(kvi->c.current_block == 0); long cnt = kvi->c.element_count; struct kmr_kv_box * ev = kmr_malloc(sizeof(struct kmr_kv_box) * (size_t)cnt); int kcdc = kmr_ckpt_disable_ckpt(kvi->c.mr); cc = kmr_map(kvi, 0, ev, inspect, kmr_copy_record_fn); assert(cc == MPI_SUCCESS); kmr_ckpt_enable_ckpt(kvi->c.mr, kcdc); kmr_sorter_t cmp = kmr_choose_sorter(kvi); long *runs = kmr_malloc(sizeof(long) * (size_t)cnt); long nruns = 0; { long i = 0; #if 0 if (kmr_ckpt_enabled(kvi->c.mr)) { i = kmr_ckpt_first_unprocessed_kv(kvi->c.mr); kmr_ckpt_save_kvo_block_init(kvi->c.mr, kvo); } #endif while (i < cnt) { do { i++; if (i == cnt) { break; } cc = (*cmp)(&ev[i - 1], &ev[i]); assert(cc <= 0); } while (cc == 0); assert(nruns < cnt); runs[nruns] = i; nruns++; } assert(i == cnt && (cnt == 0 || runs[nruns - 1] == cnt)); } { if (kvo != 0) { kvo->c.under_threaded_operation = 1; } KMR *mr = kvi->c.mr; _Bool skip = 0; KMR_OMP_PARALLEL_FOR_ for (long k = 0; k < nruns; k++) { /* (Access to stop is sloppy). */ if (!skip) { long j = (k == 0 ? 0 : runs[k - 1]); long i = runs[k]; assert(j < i); double t0 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); int ccx = (*r)(&ev[j], (i - j), kvi, kvo, arg); double t1 = ((mr->log_traces == 0) ? 0.0 : MPI_Wtime()); if (ccx != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Reduce-fn returned with error cc=%d", ccx); kmr_error(mr, ee); } if (mr->log_traces != 0) { kmr_log_reduce(mr, kvi, ev, (i - j), r, (t1 - t0)); } #if 0 if (kmr_ckpt_enabled(mr)) { KMR_OMP_CRITICAL_ { kmr_ckpt_save_kvo_block_add(mr, kvo, (i - j)); } } #endif if (stop_when_some_added) { _Bool done; if (mr->stop_at_some_check_globally) { done = 0; } else { done = (kvo->c.element_count != 0); } if (done) { KMR_OMP_CRITICAL_ { skip = 1; } } } } } if (kvo != 0) { kvo->c.under_threaded_operation = 0; } } if (kmr_ckpt_enabled(kvi->c.mr)) { #if 0 kmr_ckpt_save_kvo_block_fin(mr, kvo); #endif kmr_ckpt_save_kvo_whole(kvi->c.mr, kvo); } if (kvo != 0) { kmr_add_kv_done(kvo); } kmr_free(runs, (sizeof(long) * (size_t)cnt)); kmr_free(ev, (sizeof(struct kmr_kv_box) * (size_t)cnt)); return MPI_SUCCESS; } /** Reduces key-value pairs. It does not include shuffling, and thus, it requires being preceded by shuffling. Or, it works on local data (as a local combiner), if it is not preceded by shuffling. It always consumes the input key-value stream KVI. An output key-value stream KVO can be null. It passes an array of key-value pairs to a reduce-function whose keys are all equal (equality is by bits). The pointer ARG is just passed to a reduce-function as a general argument, where accesses to it should be race-free, since a reduce-function is called by threads by default. R is a reduce-function. See the description on the type ::kmr_redfn_t. A reduce-function may see a different input key-value stream (internally created one) instead of the one given. During reduction, it first scans adjacent equal keys, then calls a given reduce-function. Effective-options: NOTHREADING, INSPECT, TAKE_CKPT. See struct kmr_option. */ int kmr_reduce9(_Bool stop_when_some_added, KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_redfn_t r, const char *file, const int line, const char *func) { kmr_assert_kvs_ok(kvi, kvo, 1, 0); KMR *mr = kvi->c.mr; struct kmr_option kmr_supported = {.nothreading = 1, .inspect = 1, .take_ckpt = 1}; kmr_check_fn_options(mr, kmr_supported, opt, __func__); struct kmr_option i_opt = kmr_copy_options_i_part(opt); struct kmr_option o_opt = kmr_copy_options_o_part(opt); kmr_trace_entry_t * kte_start = 0; if (mr->kmrviz_trace) { kte_start = kmr_trace_add_entry(mr, KMR_TRACE_EVENT_REDUCE, 0, kvi, kvo); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_lock_start(mr); } /* Sort for reduction. */ enum kmr_kv_field keyf = kmr_unit_sized_or_opaque(kvi->c.key_data); enum kmr_kv_field valf = kmr_unit_sized_or_opaque(kvi->c.value_data); KMR_KVS *kvs1 = kmr_create_kvs(mr, keyf, valf); /* Make checkpoint for kvi and kvs1. */ kmr_sort_locally_lo(kvi, kvs1, 0, 0, i_opt); KMR_DEBUGX(kmr_assert_sorted(kvs1, 1, 0, 0)); /* Make checkpoint for kvs1 and kvo. */ struct kmr_code_line info; if (mr->atwork == 0) { info.file = file; info.func = func; info.line = line; mr->atwork = &info; } int cc; if (mr->single_thread || opt.nothreading) { cc = kmr_reduce_nothreading(kvs1, kvo, arg, o_opt, r); } else { cc = kmr_reduce_threading(stop_when_some_added, kvs1, kvo, arg, o_opt, r); } if (mr->atwork == &info) { mr->atwork = 0; } //kmr_assert_on_tail_marker(kvo); kmr_assert_on_tail_marker(kvs1); kmr_free_kvs(kvs1); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_progress_fin(mr); kmr_ckpt_lock_finish(mr); } if (mr->kmrviz_trace) { if (!opt.inspect) { kvi = 0; } kmr_trace_add_entry(mr, KMR_TRACE_EVENT_REDUCE, kte_start, kvi, kvo); } return cc; } /** Calls a reduce-function once as if all key-value pairs had the same key. See kmr_reduce(). Effective-options: INSPECT, TAKE_CKPT. See struct kmr_option. */ int kmr_reduce_as_one(KMR_KVS *kvi, KMR_KVS *kvo, void *arg, struct kmr_option opt, kmr_redfn_t r) { kmr_assert_kvs_ok(kvi, kvo, 1, 0); KMR *mr = kvi->c.mr; assert(kvi->c.current_block == 0); struct kmr_option kmr_supported = {.inspect = 1, .take_ckpt = 1}; kmr_check_fn_options(mr, kmr_supported, opt, __func__); if (kmr_ckpt_enabled(mr)) { if (kmr_ckpt_progress_init(kvi, kvo, opt)) { if (kvo != 0) { kmr_add_kv_done(kvo); } if (!opt.inspect) { kmr_free_kvs(kvi); } return MPI_SUCCESS; } } int kcdc = kmr_ckpt_disable_ckpt(mr); long cnt = kvi->c.element_count; struct kmr_kv_box * ev = kmr_malloc(sizeof(struct kmr_kv_box) * (size_t)cnt); if (cnt > 0) { int cc; struct kmr_option inspect = {.inspect = 1}; cc = kmr_map(kvi, 0, ev, inspect, kmr_copy_record_fn); assert(cc == MPI_SUCCESS); cc = (*r)(&ev[0], cnt, kvi, kvo, arg); if (cc != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Reduce-fn returned with error cc=%d", cc); kmr_error(mr, ee); } } kmr_ckpt_enable_ckpt(mr, kcdc); if (kmr_ckpt_enabled(mr)) { kmr_ckpt_save_kvo_whole(mr, kvo); } if (kvo != 0) { kmr_add_kv_done(kvo); } kmr_free(ev, (sizeof(struct kmr_kv_box) * (size_t)cnt)); if (!opt.inspect) { kmr_free_kvs(kvi); } if (kmr_ckpt_enabled(mr)) { kmr_ckpt_progress_fin(mr); } return MPI_SUCCESS; } /* ================================================================ */ /** Concatenates a number of KVSes to one. Inputs are consumed. (It is fast because the key-value data is stored internally as a list of data blocks, and this routine just links them). Note that concatenating KVS can in effect be performed by consecutive calls to kmr_map() with the KEEP_OPEN option using the same output KVS. Effective-options: none. */ int kmr_concatenate_kvs(KMR_KVS *kvs[], int nkvs, KMR_KVS *kvo, struct kmr_option opt) { for (int i = 0; i < nkvs; i++) { kmr_assert_i_kvs_ok(kvs[i], 1); } kmr_assert_o_kvs_ok(kvo, 1); if (kvo->c.element_count > 0) { KMR *mr = kvo->c.mr; kmr_error(mr, "kmr_concatenate_kvs: Output kvs has entries"); } kmr_check_fn_options(kvo->c.mr, kmr_noopt, opt, __func__); struct kmr_kvs_block *storage = 0; long elements = 0; size_t netsize = 0; long blocks = 0; struct kmr_kvs_block *p = 0; for (int i = 0; i < nkvs; i++) { elements += kvs[i]->c.element_count; netsize += kvs[i]->c.storage_netsize; blocks += kvs[i]->c.block_count; struct kmr_kvs_block *bb = kvs[i]->c.first_block; if (bb != 0) { kvs[i]->c.first_block = 0; if (p == 0) { assert(storage == 0); p = bb; storage = bb; } else { assert(blocks != 0 && p->next == 0); p->next = bb; } } if (p != 0) { while (p->next != 0) { p = p->next; } } kmr_free_kvs(kvs[i]); } kvo->c.first_block = storage; kvo->c.element_count = elements; kvo->c.storage_netsize = netsize; kvo->c.block_count = blocks; /*kmr_add_kv_done(kvo);*/ kvo->c.stowed = 1; kvo->c.current_block = 0; kvo->c.adding_point = 0; assert(kvo->c.block_count == 0 || kvo->c.first_block != 0); return MPI_SUCCESS; } /** Finds the last entry of a key-value stream. It returns null when a key-value stream is empty. It sequentially scans all the entries and slow. */ struct kmr_kvs_entry * kmr_find_kvs_last_entry(KMR_KVS *kvs) { kmr_assert_kvs_ok(kvs, 0, 1, 0); assert(kvs->c.magic == KMR_KVS_ONCORE); #if 0 long cnt = kvs->c.element_count; kvs->c.current_block = kvs->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvs, kvs->c.first_block); struct kmr_kvs_entry *o = 0; for (long i = 0; i < cnt && e != 0; i++) { o = e; e = kmr_kvs_next(kvs, e, 0); } kvs->c.current_block = 0; return o; #else if (kvs->c.element_count == 0) { return 0; } else { struct kmr_kvs_block *b; for (b = kvs->c.first_block; b->next != 0; b = b->next); kvs->c.current_block = b; struct kmr_kvs_entry *e; struct kmr_kvs_entry *o; e = kmr_kvs_first_entry(kvs, b); o = 0; long cnt = b->partial_element_count; for (long i = 0; i < cnt && e != 0; i++) { o = e; e = kmr_kvs_next(kvs, e, 1); } kvs->c.current_block = 0; return o; } #endif } /** Fills local key-value entries in an array for inspection. The returned pointers point to the inside of the KVS. It returns up to N entries, and the array EV should be as large as N. It implies inspect. */ int kmr_retrieve_kvs_entries(KMR_KVS *kvs, struct kmr_kvs_entry **ev, long n) { kmr_assert_kvs_ok(kvs, 0, 1, 0); assert(kvs->c.magic == KMR_KVS_ONCORE); long cnt = MIN(n, kvs->c.element_count); kvs->c.current_block = kvs->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvs, kvs->c.first_block); for (long i = 0; i < cnt && e != 0; i++) { ev[i] = e; e = kmr_kvs_next(kvs, e, 0); } kvs->c.current_block = 0; return MPI_SUCCESS; } /** Fills local key-value entries in an array of kmr_kv_box for inspection. While kmr_retrieve_kvs_entries() returns raw entries but kmr_retrieve_kv_box_entries() returns entries of kmr_kv_box. The returned pointers point to the inside of the KVS. It returns up to N entries, and the array EV should be as large as N. It implies inspect. */ int kmr_retrieve_kv_box_entries(KMR_KVS *kvs, struct kmr_kv_box *ev, long n) { kmr_assert_kvs_ok(kvs, 0, 1, 0); assert(kvs->c.magic == KMR_KVS_ONCORE); long cnt = MIN(n, kvs->c.element_count); kvs->c.current_block = kvs->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvs, kvs->c.first_block); for (long i = 0; i < cnt && e != 0; i++) { ev[i] = kmr_pick_kv(e, kvs); e = kmr_kvs_next(kvs, e, 0); } kvs->c.current_block = 0; return MPI_SUCCESS; } /** Fills keyed records in an array for sorting. The array EV should be as large as N. It implies inspect. */ int kmr_retrieve_keyed_records(KMR_KVS *kvs, struct kmr_keyed_record *ev, long n, _Bool shuffling, _Bool ranking) { kmr_assert_kvs_ok(kvs, 0, 1, 0); assert(kvs->c.magic == KMR_KVS_ONCORE); long cnt = MIN(n, kvs->c.element_count); kvs->c.current_block = kvs->c.first_block; struct kmr_kvs_entry *e = kmr_kvs_first_entry(kvs, kvs->c.first_block); for (long i = 0; i < cnt && e != 0; i++) { struct kmr_kv_box kv = kmr_pick_kv(e, kvs); if (shuffling) { ev[i].v = (ranking ? kv.k.i : kmr_pitch_rank(kv, kvs)); ev[i].e = e; } else { ev[i].v = kmr_stable_key(kv, kvs); ev[i].e = e; } e = kmr_kvs_next(kvs, e, 0); } kvs->c.current_block = 0; return MPI_SUCCESS; } /** Returns a minimum byte size of the field: 8 for INTEGER and FLOAT8, 0 for others. */ int kmr_legal_minimum_field_size(KMR *mr, enum kmr_kv_field f) { switch (f) { case KMR_KV_BAD: kmr_error(mr, "kmr_legal_minimum_field_size: Bad field"); return 0; case KMR_KV_INTEGER: return sizeof(long); case KMR_KV_FLOAT8: return sizeof(double); case KMR_KV_OPAQUE: case KMR_KV_CSTRING: case KMR_KV_POINTER_OWNED: case KMR_KV_POINTER_UNMANAGED: return 0; default: kmr_error(mr, "kmr_legal_minimum_field_size: Bad field"); return 0; } } /** Scans every key-value with a reduce-function locally (independently on each rank). It works in the order in the KVS. It ignores differences of the keys. It gets the start value from CARRYIN and puts the final value to CARRYOUT. The output has the same number of entries as the input. The carry-in and carry-out have one entry. The carry-out can be null. The reduce-function is called on each key-value pair as the right operand with the previous value as the left operand, and it should output a single value. The key part of the output is ignored and a pair is stored under the original key. */ int kmr_scan_locally(KMR_KVS *kvi, KMR_KVS *carryin, KMR_KVS *kvo, KMR_KVS *carryout, kmr_redfn_t r) { int cc; KMR *mr = kvo->c.mr; enum kmr_kv_field keyf = kvi->c.key_data; enum kmr_kv_field valf = kvi->c.value_data; long cnt = kvi->c.element_count; size_t evsz = (sizeof(struct kmr_keyed_record) * (size_t)cnt); struct kmr_keyed_record *ev = kmr_malloc(evsz); cc = kmr_retrieve_keyed_records(kvi, ev, cnt, 0, 0); assert(cc == MPI_SUCCESS); KMR_KVS *lastvalue = carryin; for (long i = 0; i < cnt; i++) { struct kmr_kv_box kv; cc = kmr_take_one(lastvalue, &kv); assert(cc == MPI_SUCCESS); struct kmr_kv_box bx[2]; bx[0] = kv; bx[1] = kmr_pick_kv(ev[i].e, kvi); KMR_KVS *xs = kmr_create_kvs(mr, keyf, valf); cc = (*r)(bx, 2, kvi, xs, 0); if (cc != MPI_SUCCESS) { char ee[80]; snprintf(ee, sizeof(ee), "Reduce-fn returned with error cc=%d", cc); kmr_error(mr, ee); } cc = kmr_add_kv_done(xs); assert(cc == MPI_SUCCESS); /* Put the last value as it is a non-inclusive scan. */ bx[0].klen = bx[1].klen; bx[0].k = bx[1].k; cc = kmr_add_kv(kvo, bx[0]); assert(cc == MPI_SUCCESS); kmr_free_kvs(lastvalue); lastvalue = xs; } cc = kmr_add_kv_done(kvo); assert(cc == MPI_SUCCESS); if (carryout != 0) { struct kmr_kv_box kv; cc = kmr_take_one(lastvalue, &kv); assert(cc == MPI_SUCCESS); cc = kmr_add_kv(carryout, kv); assert(cc == MPI_SUCCESS); cc = kmr_add_kv_done(carryout); assert(cc == MPI_SUCCESS); } kmr_free_kvs(lastvalue); kmr_free_kvs(kvi); if (ev != 0) { kmr_free(ev, evsz); } return MPI_SUCCESS; } /* Copyright (C) 2012-2018 RIKEN R-CCS This library is distributed WITHOUT ANY WARRANTY. This library can be redistributed and/or modified under the terms of the BSD 2-Clause License. */
pulasthi/twister2
deeplearning/pytorch/src/main/python/test/test_DLTSet.py
<filename>deeplearning/pytorch/src/main/python/test/test_DLTSet.py from twister2 import TSetContext from twister2.Twister2Environment import Twister2Environment from twister2.tset.fn.SourceFunc import SourceFunc import numpy as np env = Twister2Environment(resources=[{"cpu": 1, "ram": 512, "instances": 4}]) print("Hello from worker %d" % env.worker_id) class IntSource(SourceFunc): def __init__(self): super().__init__() self.i = 0 def has_next(self): return self.i < 10 def next(self): res = self.i self.i = self.i + 1 return np.array([res, res + 1, res + 2]) def read_test_tuples(itr, collector, ctx: TSetContext): for item in itr: print(type(item), item) collector.collect(item.tolist()) source_x = env.create_source(IntSource(), 4) data = source_x.cache() d = data.get_data() for p in d.get_partitions(): for v in p.consumer(): print("v ", v)
abs-hm-intake24/survey-frontend
SurveyClient/src/main/java/uk/ac/ncl/openlab/intake24/client/survey/prompts/simple/DrinkScalePromptDef.java
<reponame>abs-hm-intake24/survey-frontend /* This file is part of Intake24. © Crown copyright, 2012, 2013, 2014. This software is licensed under the Open Government Licence 3.0: http://www.nationalarchives.gov.uk/doc/open-government-licence/ */ package uk.ac.ncl.openlab.intake24.client.survey.prompts.simple; import com.google.gwt.safehtml.shared.SafeHtml; import uk.ac.ncl.openlab.intake24.client.api.foods.DrinkScale; public class DrinkScalePromptDef { final public DrinkScale scaleDef; final public SafeHtml message; final public String lessLabel; final public String moreLabel; final public String acceptLabel; final public double initialLevel; final public double limit; public DrinkScalePromptDef(DrinkScale scaleDef, SafeHtml message, String lessLabel, String moreLabel, String acceptLabel, double limit, double initialLevel) { this.scaleDef = scaleDef; this.message = message; this.lessLabel = lessLabel; this.moreLabel = moreLabel; this.acceptLabel = acceptLabel; this.limit = limit; this.initialLevel = initialLevel; } @Override public String toString() { return "DrinkScalePromptDef{" + "scaleDef=" + scaleDef + ", message=" + message + ", lessLabel='" + lessLabel + '\'' + ", moreLabel='" + moreLabel + '\'' + ", acceptLabel='" + acceptLabel + '\'' + ", initialLevel=" + initialLevel + ", limit=" + limit + '}'; } }
sensecollective/bioinformatics_scripts
relatedness.py
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- #Description: VCF summary from optparse import OptionParser import os __author__ = "<NAME>" __copyright__ = "Copyright 2011, The Exome Pipeline" __credits__ = ["<NAME>"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Production" parser = OptionParser() parser.add_option('-i', help='vcf', dest='vcffile') #, nargs=2 (options, args) = parser.parse_args() vcffile=options.vcffile filename = ".".join(vcffile.split("/")[-1].split(".")[:-1]) #vcf export command = "export PERL5LIB=/lgc/programs/vcftools_0.1.10/lib/perl5/site_perl/" os.system(command) #calculate kinship command = "/lgc/programs/vcftools_0.1.10/bin/vcftools --vcf %s --het --relatedness --out %s" % (vcffile,filename) os.system(command)
CyberFlameGO/exposure-notifications-android
app/src/main/java/com/google/android/apps/exposurenotification/privateanalytics/metrics/KeysUploadedWithReportTypeMetric.java
/* * Copyright 2021 Google LLC * * 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 * * https://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.google.android.apps.exposurenotification.privateanalytics.metrics; import androidx.annotation.VisibleForTesting; import com.google.android.apps.exposurenotification.storage.DiagnosisEntity.TestResult; import com.google.android.apps.exposurenotification.storage.ExposureNotificationSharedPreferences; import com.google.android.libraries.privateanalytics.PrivateAnalyticsMetric; import com.google.common.primitives.Ints; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.List; import javax.inject.Inject; import org.threeten.bp.Duration; import org.threeten.bp.Instant; /** * Class for generating an output vector that captures, when keys are uploaded, what report type was * associated with the upload * <p><ul> * Bins signification: * <li> 0: report type unknown * <li> 1: report type confirmedTest * <li> 2: report type confirmedClinicalDiagnosis * <li> 3: report type selfReported * <li> 4: report type recursive * <li> 5: report type revoked * </ul> */ public class KeysUploadedWithReportTypeMetric implements PrivateAnalyticsMetric { private static final String VERSION = "v2"; public static final String METRIC_NAME = "KeysUploadedWithReportType14d-" + VERSION; private static final Duration NUM_DAYS = Duration.ofDays(14); private static final int UNKNOWN_BIN = 0; private static final int CONFIRMED_TEST_BIN = 1; private static final int CONFIRMED_CLINICAL_DIAGNOSIS_BIN = 2; private static final int SELF_REPORTED_BIN = 3; private static final int RECURSIVE_BIN = 4; // Unused private static final int REVOKED_BIN = 5; @VisibleForTesting static final int BIN_LENGTH = 6; private final ExposureNotificationSharedPreferences exposureNotificationSharedPreferences; @Inject KeysUploadedWithReportTypeMetric( ExposureNotificationSharedPreferences exposureNotificationSharedPreferences) { this.exposureNotificationSharedPreferences = exposureNotificationSharedPreferences; } @Override public ListenableFuture<List<Integer>> getDataVector() { int[] data = new int[BIN_LENGTH]; Instant lastSubmittedKeysTime = exposureNotificationSharedPreferences .getPrivateAnalyticsLastSubmittedKeysTime(); Instant workerLastTime = exposureNotificationSharedPreferences .getPrivateAnalyticsWorkerLastTimeForBiweekly(); if (lastSubmittedKeysTime.isAfter(workerLastTime)) { // Keys have been submitted since the last analytics upload. TestResult testResult = exposureNotificationSharedPreferences .getPrivateAnalyticsLastReportType(); if (testResult == null) { data[UNKNOWN_BIN] = 1; } else { switch (testResult) { case CONFIRMED: data[CONFIRMED_TEST_BIN] = 1; break; case LIKELY: data[CONFIRMED_CLINICAL_DIAGNOSIS_BIN] = 1; break; case USER_REPORT: data[SELF_REPORTED_BIN] = 1; break; case NEGATIVE: data[REVOKED_BIN] = 1; break; default: data[UNKNOWN_BIN] = 1; } } } return Futures.immediateFuture(Ints.asList(data)); } @Override public String getMetricName() { return METRIC_NAME; } @Override public int getMetricHammingWeight() { return 0; } }
poppycokey/simpleframework
simple-test/src/test/java/org/simpleframework/http/validate/ReportTest.java
package org.simpleframework.http.validate; import java.io.InputStream; import java.io.PushbackInputStream; import junit.framework.TestCase; import org.simpleframework.common.buffer.ArrayBuffer; import org.simpleframework.common.buffer.Buffer; import org.simpleframework.xml.core.Persister; public class ReportTest extends TestCase { private static final String HEADER = "HTTP/1.1 200 OK\r\n"+ "Content-Type: text/plain\r\n"+ "Server: Apache/2.1\r\n"+ "Content-Length: 10\r\n"+ "Connection: keep-alive\r\n"+ "\r\n"+ "0123456789"; public void testReport() throws Exception { Persister persister = new Persister(); Extractor extractor = new Extractor(true); Buffer buffer = new ArrayBuffer(1024); buffer.append(HEADER.getBytes("ISO-8859-1")); InputStream stream = buffer.open(); PushbackInputStream pushback = new PushbackInputStream(stream, 2048); Result response = extractor.extractResponse(pushback); Report report = new Report(response, "HTTP/1.1 404 Not Found"); assertEquals(report.getStatusLine(), "HTTP/1.1 200 OK"); assertEquals(report.isError(), false); persister.write(report, System.out); } }
mwiszniewski/website
src/components/ErrorMessage.js
<reponame>mwiszniewski/website<gh_stars>10-100 import styled from '@emotion/styled'; const ErrorMessage = styled.div` height: 2rem; font-size: ${props => props.theme.fontSizes.small}; margin-top: 0.3rem; color: ${props => props.theme.colors.accent}; `; export default ErrorMessage;
parlaylabs/botbuilder-java
libraries/bot-schema/src/main/java/com/microsoft/bot/schema/models/InnerHttpError.java
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package com.microsoft.bot.schema.models; import com.fasterxml.jackson.annotation.JsonProperty; /** * Object representing inner http error. */ public class InnerHttpError { /** * HttpStatusCode from failed request. */ @JsonProperty(value = "statusCode") private int statusCode; /** * Body from failed request. */ @JsonProperty(value = "body") private Object body; /** * Gets HttpStatusCode from failed request. * * @return the statusCode value */ public int statusCode() { return this.statusCode; } /** * Sets HttpStatusCode from failed request. * * @param activities the activities value to set * @return the InnerHttpError object itself. */ public InnerHttpError withStatusCode(int statusCode) { this.statusCode = statusCode; return this; } /** * Gets Body from failed request. */ public Object body(){ return this.body; } /** * Sets Body from failed request. * @param body The body to set */ public InnerHttpError withBody(Object body){ this.body = body; return this; } }
ryanfowler/go-domdistiller
internal/filter/heuristic/expand-title.go
// ORIGINAL: java/filters/heuristics/ExpandTitleToContentFilter.java // Copyright (c) 2020 <NAME> // // 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. // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // boilerpipe // // Copyright (c) 2009 <NAME> // // The author licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package heuristic import ( "github.com/markusmobius/go-domdistiller/internal/label" "github.com/markusmobius/go-domdistiller/internal/webdoc" ) // ExpandTitleToContent marks all TextBlocks "content" which are between the headline and the // part that has already been marked content, if they are marked with label.MightBeContent. // This filter is quite specific to the news domain. type ExpandTitleToContent struct{} func NewExpandTitleToContent() *ExpandTitleToContent { return &ExpandTitleToContent{} } func (f *ExpandTitleToContent) Process(doc *webdoc.TextDocument) bool { title := -1 contentStart := -1 for i, tb := range doc.TextBlocks { if contentStart == -1 && tb.HasLabel(label.Title) { title = i contentStart = -1 } if contentStart == -1 && tb.IsContent() { contentStart = i } } if contentStart <= title || title == -1 { return false } changes := false for _, tb := range doc.TextBlocks[title:contentStart] { if tb.HasLabel(label.MightBeContent) { changed := tb.SetIsContent(true) changes = changes || changed } } return changes }
KapilKhanal/tabletoolz
tests/test_sqlbase.py
import pytest from tabletoolz import * from pandas.testing import assert_frame_equal @pytest.fixture def response(): df = car_options >> to_statement >> to_pandas(engine) return df def test_to_statement(response): # Test to_statement expected = car_options >> to_statement >> to_pandas(engine) assert_frame_equal(response, expected, check_dtype=False) @pytest.fixture def response_2(): df = car_options >> to_statement >> pprint return str(df) def test_pprint(response_2): # Test pprint of car_options table expected = car_options >> to_statement >> pprint output = 'SELECT "Car_Options".option_set_id, "Car_Options".model_id, "Car_Options".engine_id, "Car_Options".transmission_id, "Car_Options".chassis_id, "Car_Options".premium_sound_id, "Car_Options".color, "Car_Options".option_set_price \nFROM "Car_Options"' assert response_2 == output @pytest.fixture def response_3(): df = car_options >> to_statement >> head(num=5) >> to_pandas(engine) return df def test_head(response_3): # Test first 5 rows query = car_options >> to_statement >> to_pandas(engine) expected = query.head() assert_frame_equal(response_3, expected, check_dtype=False) @pytest.fixture def response_4(): df = car_options >> to_statement >> limit(5) >> to_pandas(engine) return df def test_head(response_4): # Test first 5 rows query = car_options >> to_statement >> to_pandas(engine) expected = query.head() assert_frame_equal(response_4, expected, check_dtype=False)
fredblain/docQE-corp
systems/2014/english-russian/newstest2014.onlineA.0.en-ru/efb705e77017534ee4b72ef260187d91.newstest2014.onlineA.0.en-ru.ru
Водителя, превышение скорости на 130mph, с горячим напитком между ног оштрафован на £1000 Автомобилист оштрафован на £1000 для вождения в до 130 (210 км/ч) с горячим напитком сбалансированы между его ног. Э<NAME>, 35, Tiptree, Эссекс, был замечен в движении его <NAME> в Брэйнтри на A120 27 мая. Когда его остановили полицейские, они обнаружили takeaway пить между его ног. В Колчестер магистратский суд Howie признал за вождение без должного ухода и внимания. Семь очков добавляется его лицензии привели к его получения 6 месячный запрет вождения. Хоуи также обязали выплатить расходы £ 90 и жертвы за дополнительную плату от £100.
s3b4stian/c-adventures
CLP/memchr.c
<filename>CLP/memchr.c #include <string.h> #include <stdio.h> void print(char *b, char *p) { if (p) // value of pointer p as char, difference n string first char address and position address printf ("'%c' [%ld]\n", *p, p - b); else printf ("(null)\n"); } int main (void) { char abc['Z' - 'A' + 1]; int i; for (i = 'A'; i <= 'Z'; i++) abc[i - 'A'] = i; //search for a specific byte into memory and return the address print(abc, memchr(abc, 'C', sizeof (abc))); print(abc, memchr(abc, 'S', 10)); print(abc, memchr(abc, 's', sizeof (abc))); // memrchr start the search from the end of the memory block return 0; }
qianlong4526888/haha
src/arch/mips/dsp.hh
<gh_stars>10-100 /* * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: <NAME> */ #ifndef __ARCH_MIPS_DSP_HH__ #define __ARCH_MIPS_DSP_HH__ #include "arch/mips/isa_traits.hh" #include "arch/mips/types.hh" #include "base/misc.hh" #include "base/types.hh" class ThreadContext; namespace MipsISA { // SIMD formats enum { SIMD_FMT_L, // long word SIMD_FMT_W, // word SIMD_FMT_PH, // paired halfword SIMD_FMT_QB, // quad byte SIMD_NUM_FMTS }; // DSPControl Fields enum { DSP_POS, // insertion bitfield position DSP_SCOUNT, // insertion bitfield size DSP_C, // carry bit DSP_OUFLAG, // overflow-underflow flag DSP_CCOND, // condition code DSP_EFI, // extract fail indicator bit DSP_NUM_FIELDS }; // compare instruction operations enum { CMP_EQ, // equal CMP_LT, // less than CMP_LE // less than or equal }; // SIMD operation order modes enum { MODE_L, // left MODE_R, // right MODE_LA, // left-alternate MODE_RA, // right-alternate MODE_X // cross }; // dsp operation parameters enum { UNSIGNED, SIGNED }; enum { NOSATURATE, SATURATE }; enum { NOROUND, ROUND }; // DSPControl field positions and masks const uint32_t DSP_CTL_POS[DSP_NUM_FIELDS] = { 0, 7, 13, 16, 24, 14 }; const uint32_t DSP_CTL_MASK[DSP_NUM_FIELDS] = { 0x0000003f, 0x00001f80, 0x00002000, 0x00ff0000, 0x0f000000, 0x00004000 }; /* * SIMD format constants */ // maximum values per register const uint32_t SIMD_MAX_VALS = 4; // number of values in fmt const uint32_t SIMD_NVALS[SIMD_NUM_FMTS] = { 1, 1, 2, 4 }; // number of bits per value const uint32_t SIMD_NBITS[SIMD_NUM_FMTS] = { 64, 32, 16, 8 }; // log2(bits per value) const uint32_t SIMD_LOG2N[SIMD_NUM_FMTS] = { 6, 5, 4, 3 }; // DSP maximum values const uint64_t FIXED_L_SMAX = ULL(0x7fffffffffffffff); const uint64_t FIXED_W_SMAX = ULL(0x000000007fffffff); const uint64_t FIXED_H_SMAX = ULL(0x0000000000007fff); const uint64_t FIXED_B_SMAX = ULL(0x000000000000007f); const uint64_t FIXED_L_UMAX = ULL(0xffffffffffffffff); const uint64_t FIXED_W_UMAX = ULL(0x00000000ffffffff); const uint64_t FIXED_H_UMAX = ULL(0x000000000000ffff); const uint64_t FIXED_B_UMAX = ULL(0x00000000000000ff); const uint64_t FIXED_SMAX[SIMD_NUM_FMTS] = { FIXED_L_SMAX, FIXED_W_SMAX, FIXED_H_SMAX, FIXED_B_SMAX }; const uint64_t FIXED_UMAX[SIMD_NUM_FMTS] = { FIXED_L_UMAX, FIXED_W_UMAX, FIXED_H_UMAX, FIXED_B_UMAX }; // DSP minimum values const uint64_t FIXED_L_SMIN = ULL(0x8000000000000000); const uint64_t FIXED_W_SMIN = ULL(0xffffffff80000000); const uint64_t FIXED_H_SMIN = ULL(0xffffffffffff8000); const uint64_t FIXED_B_SMIN = ULL(0xffffffffffffff80); const uint64_t FIXED_L_UMIN = ULL(0x0000000000000000); const uint64_t FIXED_W_UMIN = ULL(0x0000000000000000); const uint64_t FIXED_H_UMIN = ULL(0x0000000000000000); const uint64_t FIXED_B_UMIN = ULL(0x0000000000000000); const uint64_t FIXED_SMIN[SIMD_NUM_FMTS] = { FIXED_L_SMIN, FIXED_W_SMIN, FIXED_H_SMIN, FIXED_B_SMIN }; const uint64_t FIXED_UMIN[SIMD_NUM_FMTS] = { FIXED_L_UMIN, FIXED_W_UMIN, FIXED_H_UMIN, FIXED_B_UMIN }; // DSP utility functions int32_t bitrev(int32_t value); uint64_t dspSaturate(uint64_t value, int32_t fmt, int32_t sign, uint32_t *overflow); uint64_t checkOverflow(uint64_t value, int32_t fmt, int32_t sign, uint32_t *overflow); uint64_t signExtend(uint64_t value, int32_t signpos); uint64_t addHalfLsb(uint64_t value, int32_t lsbpos); int32_t dspAbs(int32_t a, int32_t fmt, uint32_t *dspctl); int32_t dspAdd(int32_t a, int32_t b, int32_t fmt, int32_t saturate, int32_t sign, uint32_t *dspctl); int32_t dspAddh(int32_t a, int32_t b, int32_t fmt, int32_t round, int32_t sign); int32_t dspSub(int32_t a, int32_t b, int32_t fmt, int32_t saturate, int32_t sign, uint32_t *dspctl); int32_t dspSubh(int32_t a, int32_t b, int32_t fmt, int32_t round, int32_t sign); int32_t dspShll(int32_t a, uint32_t sa, int32_t fmt, int32_t saturate, int32_t sign, uint32_t *dspctl); int32_t dspShrl(int32_t a, uint32_t sa, int32_t fmt, int32_t sign); int32_t dspShra(int32_t a, uint32_t sa, int32_t fmt, int32_t round, int32_t sign, uint32_t *dspctl); int32_t dspMul(int32_t a, int32_t b, int32_t fmt, int32_t saturate, uint32_t *dspctl); int32_t dspMulq(int32_t a, int32_t b, int32_t fmt, int32_t saturate, int32_t round, uint32_t *dspctl); int32_t dspMuleu(int32_t a, int32_t b, int32_t mode, uint32_t *dspctl); int32_t dspMuleq(int32_t a, int32_t b, int32_t mode, uint32_t *dspctl); int64_t dspDpaq(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t infmt, int32_t outfmt, int32_t postsat, int32_t mode, uint32_t *dspctl); int64_t dspDpsq(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t infmt, int32_t outfmt, int32_t postsat, int32_t mode, uint32_t *dspctl); int64_t dspDpa(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t fmt, int32_t sign, int32_t mode); int64_t dspDps(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t fmt, int32_t sign, int32_t mode); int64_t dspMaq(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t fmt, int32_t mode, int32_t saturate, uint32_t *dspctl); int64_t dspMulsa(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t fmt); int64_t dspMulsaq(int64_t dspac, int32_t a, int32_t b, int32_t ac, int32_t fmt, uint32_t *dspctl); void dspCmp(int32_t a, int32_t b, int32_t fmt, int32_t sign, int32_t op, uint32_t *dspctl); int32_t dspCmpg(int32_t a, int32_t b, int32_t fmt, int32_t sign, int32_t op); int32_t dspCmpgd(int32_t a, int32_t b, int32_t fmt, int32_t sign, int32_t op, uint32_t *dspctl); int32_t dspPrece(int32_t a, int32_t infmt, int32_t insign, int32_t outfmt, int32_t outsign, int32_t mode); int32_t dspPrecrqu(int32_t a, int32_t b, uint32_t *dspctl); int32_t dspPrecrq(int32_t a, int32_t b, int32_t fmt, uint32_t *dspctl); int32_t dspPrecrSra(int32_t a, int32_t b, int32_t sa, int32_t fmt, int32_t round); int32_t dspPick(int32_t a, int32_t b, int32_t fmt, uint32_t *dspctl); int32_t dspPack(int32_t a, int32_t b, int32_t fmt); int32_t dspExtr(int64_t dspac, int32_t fmt, int32_t sa, int32_t round, int32_t saturate, uint32_t *dspctl); int32_t dspExtp(int64_t dspac, int32_t size, uint32_t *dspctl); int32_t dspExtpd(int64_t dspac, int32_t size, uint32_t *dspctl); // SIMD pack/unpack utility functions void simdPack(uint64_t *values_ptr, int32_t *reg, int32_t fmt); void simdUnpack(int32_t reg, uint64_t *values_ptr, int32_t fmt, int32_t sign); // DSPControl r/w utility functions void writeDSPControl(uint32_t *dspctl, uint32_t value, uint32_t mask); uint32_t readDSPControl(uint32_t *dspctl, uint32_t mask); } // namespace MipsISA #endif // __ARCH_MIPS_DSP_HH__
joshuawscott/sdops
app/models/appgen_order_lineitem.rb
# ==DEPRECATED # This was a table populated by a cronjob that pulled data from the # Appgen accounting system. We no longer use this, and it has been replaced by # the Fishbowl and Fishbowl* classes. # ===Schema: # appgen_order_id string # part_number string # description string # quantity integer # price decimal(20,5) # discount decimal(7,2) class AppgenOrderLineitem < ActiveRecord::Base belongs_to :appgen_order has_one :appgen_order_serial, :foreign_key => :id belongs_to :sugar_acct belongs_to :contract def hwchecked # if the first letter is A, then it's checked return "true" if part_number[0] == 65 || (part_number[0] >= 48 && part_number[0] <= 57) 'false' end def swchecked # if the first letter is B, then it's checked return "true" if part_number[0] == 66 'false' end #consistent interface between this and fishbowl_so def serialnum self.appgen_order_serial.serial_number end end
abhinavsri000/UAVision
WebODM-master/plugins/test/dynamic.js
<reponame>abhinavsri000/UAVision console.log('Hello ${name}');
buschmais/extended-objects
neo4j/test/src/test/java/com/buschmais/xo/neo4j/test/bootstrap/NonRegisteredTypeIT.java
<filename>neo4j/test/src/test/java/com/buschmais/xo/neo4j/test/bootstrap/NonRegisteredTypeIT.java<gh_stars>10-100 package com.buschmais.xo.neo4j.test.bootstrap; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import java.util.Collection; import com.buschmais.xo.api.XOException; import com.buschmais.xo.api.XOManager; import com.buschmais.xo.api.bootstrap.XOUnit; import com.buschmais.xo.neo4j.test.AbstractNeo4JXOManagerIT; import com.buschmais.xo.neo4j.test.bootstrap.composite.A; import com.buschmais.xo.neo4j.test.bootstrap.composite.B; import com.buschmais.xo.neo4j.test.bootstrap.composite.B2B; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @RunWith(Parameterized.class) public class NonRegisteredTypeIT extends AbstractNeo4JXOManagerIT { public NonRegisteredTypeIT(XOUnit xoUnit) { super(xoUnit); } @Parameterized.Parameters public static Collection<Object[]> getXOUnits() { return xoUnits(B.class); } @Test public void entity() { XOManager xoManager = getXOManager(); xoManager.currentTransaction().begin(); try { xoManager.create(A.class); fail("Expecting an " + XOException.class.getName()); } catch (XOException e) { assertThat("Exception message must contain name of non-registered type.", e.getMessage(), containsString(A.class.getName())); } xoManager.currentTransaction().commit(); } @Test public void relation() { XOManager xoManager = getXOManager(); xoManager.currentTransaction().begin(); B b1 = xoManager.create(B.class); B b2 = xoManager.create(B.class); try { xoManager.create(b1, B2B.class, b2); fail("Expecting an " + XOException.class.getName()); } catch (XOException e) { assertThat("Exception message must contain name of non-registered type.", e.getMessage(), containsString(B2B.class.getName())); } xoManager.currentTransaction().commit(); } }
mateuszlewko/nomad-driver-nspawn
vendor/github.com/hashicorp/consul-template/signals/nil.go
<filename>vendor/github.com/hashicorp/consul-template/signals/nil.go package signals // NilSignal is a special signal that is blank or "nil" type NilSignal int func (s *NilSignal) String() string { return "SIGNIL" } func (s *NilSignal) Signal() {}
Sunrisepeak/Linux2.6-Reading
drivers/clk/mediatek/clk-mt6779-cam.c
<gh_stars>10-100 // SPDX-License-Identifier: GPL-2.0 /* * Copyright (c) 2019 MediaTek Inc. * Author: <NAME> <<EMAIL>> */ #include <linux/module.h> #include <linux/clk-provider.h> #include <linux/platform_device.h> #include <dt-bindings/clock/mt6779-clk.h> #include "clk-mtk.h" #include "clk-gate.h" static const struct mtk_gate_regs cam_cg_regs = { .set_ofs = 0x0004, .clr_ofs = 0x0008, .sta_ofs = 0x0000, }; #define GATE_CAM(_id, _name, _parent, _shift) \ GATE_MTK(_id, _name, _parent, &cam_cg_regs, _shift, \ &mtk_clk_gate_ops_setclr) static const struct mtk_gate cam_clks[] = { GATE_CAM(CLK_CAM_LARB10, "camsys_larb10", "cam_sel", 0), GATE_CAM(CLK_CAM_DFP_VAD, "camsys_dfp_vad", "cam_sel", 1), GATE_CAM(CLK_CAM_LARB11, "camsys_larb11", "cam_sel", 2), GATE_CAM(CLK_CAM_LARB9, "camsys_larb9", "cam_sel", 3), GATE_CAM(CLK_CAM_CAM, "camsys_cam", "cam_sel", 6), GATE_CAM(CLK_CAM_CAMTG, "camsys_camtg", "cam_sel", 7), GATE_CAM(CLK_CAM_SENINF, "camsys_seninf", "cam_sel", 8), GATE_CAM(CLK_CAM_CAMSV0, "camsys_camsv0", "cam_sel", 9), GATE_CAM(CLK_CAM_CAMSV1, "camsys_camsv1", "cam_sel", 10), GATE_CAM(CLK_CAM_CAMSV2, "camsys_camsv2", "cam_sel", 11), GATE_CAM(CLK_CAM_CAMSV3, "camsys_camsv3", "cam_sel", 12), GATE_CAM(CLK_CAM_CCU, "camsys_ccu", "cam_sel", 13), GATE_CAM(CLK_CAM_FAKE_ENG, "camsys_fake_eng", "cam_sel", 14), }; static const struct of_device_id of_match_clk_mt6779_cam[] = { { .compatible = "mediatek,mt6779-camsys", }, {} }; static int clk_mt6779_cam_probe(struct platform_device *pdev) { struct clk_onecell_data *clk_data; struct device_node *node = pdev->dev.of_node; clk_data = mtk_alloc_clk_data(CLK_CAM_NR_CLK); mtk_clk_register_gates(node, cam_clks, ARRAY_SIZE(cam_clks), clk_data); return of_clk_add_provider(node, of_clk_src_onecell_get, clk_data); } static struct platform_driver clk_mt6779_cam_drv = { .probe = clk_mt6779_cam_probe, .driver = { .name = "clk-mt6779-cam", .of_match_table = of_match_clk_mt6779_cam, }, }; module_platform_driver(clk_mt6779_cam_drv); MODULE_LICENSE("GPL");
wn-upf/neko
Code/COST/sense.h
/************************************************************************ * $CVSHeader: sense/code/common/sense.h,v 1.6 2007/03/03 17:51:23 mlisee Exp $ * * @<title> SENSE Library </title>@ * * @<h1> sense.h </h1>@ * This header file provides * necessary functionalities for network simulation. All SENSE * components must include this header file. * * @<!--Copyright 2003 Gilbert (<NAME>, <NAME> and * Rensselaer Polytechnic Institute. All worldwide rights reserved. A * license to use, copy, modify and distribute this software for * non-commercial research purposes only is hereby granted, provided * that this copyright notice and accompanying disclaimer is not * modified or removed from the software. * * DISCLAIMER: The software is distributed "AS IS" without any express * or implied warranty, including but not limited to, any implied * warranties of merchantability or fitness for a particular purpose * or any warranty of non-infringement of any current or pending * patent rights. The authors of the software make no representations * about the suitability of this software for any particular * purpose. The entire risk as to the quality and performance of the * software is with the user. Should the software prove defective, the * user assumes the cost of all necessary servicing, repair or * correction. In particular, neither Rensselaer Polytechnic * Institute, nor the authors of the software are liable for any * indirect, special, consequential, or incidental damages related to * the software, to the maximum extent the law permits. -->@ * ************************************************************************/ #ifndef SENSE_H #define SENSE_H #include "config.h" const double speed_of_light=299792458.0; #include <string> using std::string; /************************************************************************ * SENSE is built on top of COST, and makes use of @CorsaAllocator@ defined * in corsa_alloc.h. ************************************************************************/ #include "cost.h" #include "corsa_alloc.h" /************************************************************************ * @<h2> Packet Management in SENSE </h2>@ * * There are two main design goals on the packet management in SENSE: to * allow components to pass packets in two forms, either as a packet * structure or as a pointer to a packet structure, and to share a * packet among all receiving components if the packet is passed by a * pointer. * * The first goal is achieved by using a modern C++ technique, * referred to as traits. According to Bjarne Stroustrup, a trait is * "a small object whose main purpose is to carry information used by * another object or algorithm to determine policy or implementation * details." In SENSE, a special trait class is declared which can be * used to tell if a certain template parameter is a packet structure * or a packet pointer. * The second goal of sharing a packet through the pointer is done by * the use of a popular programming technique, reference counting. * When a component is about to own a packet, it must increase the reference * count of the packet to indicate the newly created ownership. When a component * is about to release a packet, it needs to decrease the reference * count. Only when the reference count goes to zero will the packet be * actually deleted. * * @<h2>ether_addr_t</h2>@ ************************************************************************/ #include "ether_addr.h" /************************************************************************ * This is the packet trait class that takes one template parameter, * @T@. It serves dual purposes. First, if @T@ is a pointer, then * @nonpointer_t@ gives the corresponding structure. Second, it * defines three member functions, which are to be called when * respective operations need to be performed. * * In the general declaration, @nonpointer_t@ is just @T@, and in all * three member function no action is taken. This is for packets passed * as plain structures. ************************************************************************/ template <class T> class packet_trait { public: typedef T nonpointer_t; static void free(const T&) { } static void free(T&t) { t.~T(); } static void init(T&t) { new (&t) T; } static void init(const T&) { } static void inc_ref(const T&) { } static T& access_hdr(T&t) { return t; } static void dump(std::string& str, const T&p) { p.dump(str) ;} static void check_ref(const T&, int) { } }; /* ** nextStatsId can't be a static member since there can be different packet ** definitions for different layers. */ unsigned int nextStatsId = 0; /************************************************************************ * A smart packet is designed for layered network architecture. It has * two important fields, @hdr@ for the header and @pld@ for the * payload (which is usually the encapsulated higher layer * packet). There are two ways to access the header or payload, * working for two different cases. * * Let us use a simple example to illustrate the usage of this class * in two cases. Suppose we have a declaration @P@ @p@ (most likely * this is an argument). If we know for sure that @p@ is a pointer, * then we can simply use @p->hdr@ to access the header, @p->pld@ to * access the payload. * * However, if we don't know whether @p@ is a pointer or a structure * (which happens when @P@ is a template parameter), we cannot access * the field directly, and we have to use the function @access_hdr@. * We cannot do @P::access_hdr(p)@, because @P@ may be * a pointer. However, we can always rely on @packet_trait@, so we have * @packet_trait<P>::access_hdr(p)@. ************************************************************************/ template <class H, class P> class smart_packet_t { public: inline static smart_packet_t<H,P> *alloc(); inline void free(); inline void destroy(); inline void inc_ref(); inline smart_packet_t<H,P> *copy(); inline void inc_pld_ref() const; inline bool check_ref(int r) { return r<=refcount; } P &access_pld() { return packet_trait<P>::access_hdr(pld); } static void free_pld(P const &p) { packet_trait<P>::free(p); } H *operator ->() { return &hdr; } std::string dump() const; H hdr; P pld; private: static CorsaAllocator m_allocator; unsigned int statsId; public: int refcount; unsigned int getStatsId() const { return statsId; } void setStatsId( unsigned int id) { statsId = id; } void newStatsId() { statsId = nextStatsId++; } }; /************************************************************************ * We use our own memory allocator, @CorsaAllocator@, which is more * efficient than the default memory allocator, since for each packet * type we only need to deal with memory blocks of the same size. ************************************************************************/ template <class H, class P> CorsaAllocator smart_packet_t<H,P>::m_allocator (sizeof(smart_packet_t<H,P>)); /************************************************************************ * This function creates a new packet obtained from the allocator. It then * sets @p->pld@ to null if @p->pld@ is a pointer, and the reference count to 1. ************************************************************************/ template <class H, class P> smart_packet_t<H,P>* smart_packet_t<H,P>::alloc() { smart_packet_t<H,P>* p=static_cast<smart_packet_t<H,P>*>(m_allocator.alloc()); addToPacketList( p); packet_trait<H>::init(p->hdr); packet_trait<P>::init(p->pld); p->refcount=1; p->statsId = 0xdeadbeef; return p; } /************************************************************************ * This function creates a new copy from an existing packet. ************************************************************************/ template <class H, class P> smart_packet_t<H,P>* smart_packet_t<H,P>::copy() { smart_packet_t<H,P>* p=static_cast<smart_packet_t<H,P>*>(m_allocator.alloc()); addToPacketList( p); packet_trait<H>::init(p->hdr); packet_trait<P>::init(p->pld); p->hdr=hdr; p->pld=pld; inc_pld_ref(); p->refcount=1; p->statsId = statsId; return p; } /************************************************************************ * This function first creates a new packet obtained from the allocator. It then * sets @p->pld@ to null if @p->pld@ is a pointer, and the reference count to 1. ************************************************************************/ template <class H, class P> void smart_packet_t<H,P>::free() { #ifdef SENSE_DEBUG packet_trait<P>::check_ref(pld,refcount); #endif removeFromPacketList( this); packet_trait<P>::free(pld); refcount--; if(refcount==0) { packet_trait<H>::free(hdr); m_allocator.free(this); } } /************************************************************************ * This function destroys the packet without looking at its reference count. ************************************************************************/ template <class H, class P> void smart_packet_t<H,P>::destroy() { removeFromPacketList( this); packet_trait<H>::free(hdr); packet_trait<P>::free(pld); m_allocator.free(this); } /************************************************************************ * This function increases the reference count. * It must also increase the reference count of the payload packet. ************************************************************************/ template <class H, class P> void smart_packet_t<H,P>::inc_ref() { packet_trait<P>::inc_ref(pld); refcount++; return; } /************************************************************************ * This function is called before forwarding the * encapsulated payload packet to a higher layer. The reference count in @pld@ * is increased if @pld@ is a packet pointer, otherwise nothing * happens. ************************************************************************/ template <class H, class P> void smart_packet_t<H,P>::inc_pld_ref() const { packet_trait<P>::inc_ref(pld); } /************************************************************************ * This function is called to show the content of the packet. It calls * the @dump()@ function of the header, then, depending on the return value, * it may or may not call the @dump()@ function of the payload packet. ************************************************************************/ template <class H, class P> std::string smart_packet_t<H,P>::dump() const { std::string str="["; std::string h; char mwlString[20]; sprintf( mwlString, " rc %d", refcount); if( hdr.dump(h) ) { std::string m; packet_trait<P>::dump(m,pld); str = str + h + ", " + m + mwlString + "]"; } else { str = str + h + ", NULL "+ mwlString + "]"; } return str; } /************************************************************************ * This is the partial specialization of @packet_trait@ for smart * packets. Notice that there is no specialization for general packet * pointers. The design decision here is, the specialization for * pointers other than that of smart packets should be left to * users. When a user wants to pass a pointer of a certain packet, he * must implements required member functions, such as alloc(), free(), * as well as a partial or complete specialization of @packet_trait@ * for that pointer ************************************************************************/ template <class H, class P> class packet_trait< smart_packet_t<H,P>* > { public: typedef smart_packet_t<H,P> nonpointer_t; static void free(nonpointer_t* const &p) { if(p!=NULL) p->free(); }; static void inc_ref(nonpointer_t* const &p) { if(p!=NULL) p->inc_ref(); }; static H& access_hdr( nonpointer_t * p) { return p->hdr; } static void init(nonpointer_t* &p) { p=NULL; } static void dump(std::string& str,nonpointer_t* const &p) { if(p!=NULL) str= p->dump(); else str="NULL"; } static void check_ref(nonpointer_t* const &p, int ref) { if(p!=NULL&&!p->check_ref(ref)) printf("Packet %p: Payload refcount is smaller than the current refcount\n", p); } }; /************************************************************************ * @<h2>coordinate_t</h2>@ * * This class defines the coordination of a position in a two dimensional space. ************************************************************************/ class coordinate_t { public: coordinate_t () : x(0.0), y(0.0) { } coordinate_t ( double _x, double _y ) : x(_x), y(_y) { } double x,y; }; /************************************************************************ * In COST, timers can only pass one argument due to the * limitation of C++ template (we cannot declare two template classes * with the same name but with different numbers of template * parameters). Therefore, in case we need two arguments, we have to * use @pair@ in STL. ************************************************************************/ #include <utility> using std::make_pair; using std::pair; /************************************************************************ * @<h2>triple</h2>@ * * This class is similar to @pair@ in STL, except that it takes three * template parameters. ************************************************************************/ template <class T1, class T2, class T3> class triple { public: typedef T1 first_type; typedef T2 second_type; typedef T3 third_type; T1 first; T2 second; T3 third; triple() : first(T1()), second(T2()), third(T3()) {} triple(const T1& a, const T2& b, const T3& c) : first(a), second(b), third(c) {} template <class U1, class U2, class U3> triple(const triple<U1, U2, U3>& t) : first(t.first), second(t.second), third(t.third) {} }; template <class T1, class T2, class T3> inline bool operator == (const triple<T1, T2, T3>& x, const triple<T1, T2, T3>& y) { return x.first == y.first && x.second == y.second && x.third == y.third; } template <class T1, class T2, class T3> inline triple<T1, T2, T3> make_triple(const T1& x, const T2& y, const T3& z) { return triple<T1, T2, T3>(x, y, z); } /************************************************************************ * @<h2>Quadruple</h2>@ * We also need a template class to combine four variables, but since the * name 'quadruple' may already be defined as a long double, use the name * 'Quadruple' instead. ************************************************************************/ template <class T1, class T2, class T3, class T4> class Quadruple { public: typedef T1 first_type; typedef T2 second_type; typedef T3 third_type; typedef T4 fourth_type; T1 first; T2 second; T3 third; T4 fourth; Quadruple() : first(T1()), second(T2()), third(T3()), fourth(T4()) {} Quadruple(const T1& a, const T2& b, const T3& c, const T4& d) : first(a), second(b), third(c), fourth(d) {} template <class U1, class U2, class U3, class U4> Quadruple(const Quadruple<U1, U2, U3, U4>& t) : first(t.first), second(t.second), third(t.third), fourth(t.fourth) {} }; template <class T1, class T2, class T3, class T4> inline bool operator == (const Quadruple<T1, T2, T3, T4>& x, const Quadruple<T1, T2, T3, T4>& y) { return x.first == y.first && x.second == y.second && x.third == y.third && x.fourth == y.fourth; } template <class T1, class T2, class T3, class T4> inline Quadruple<T1, T2, T3, T4> make_Quadruple(const T1& a, const T2& b, const T3& c, const T4& d) { return Quadruple<T1, T2, T3, T4>(a, b, c, d); } #include "path.h" #endif /* SENSE_H */
crazy-max/expect-nt
blt/generic/bltSpline.c
<reponame>crazy-max/expect-nt /* * bltSpline.c -- * * This module implements curve fitting with spline interpolation. * * Copyright 1996-1997 by AT&T Bell Laboratories. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #include "bltInt.h" #ifndef NO_SPLINE #define SPLINE_VERSION "8.0" /* * Quadratic spline parameters */ #define E1 param[0] #define E2 param[1] #define V1 param[2] #define V2 param[3] #define W1 param[4] #define W2 param[5] #define Z1 param[6] #define Z2 param[7] #define Y1 param[8] #define Y2 param[9] static INLINE double Fabs(x) double x; { return ((x < 0.0) ? -x : x); } /* * ----------------------------------------------------------------------- * * Search -- * * Conducts a binary search for a value. This routine is called * only if key is between x(0) and x(len - 1). * * Results: * Returns the index of the largest value in xtab for which * x[i] < key. * * ----------------------------------------------------------------------- */ static int Search(x, len, key, foundPtr) double x[]; /* Contains the abscissas of the data * points of interpolation. */ int len; /* Dimension of x. */ double key; /* Value whose relative position in * x is to be located. */ int *foundPtr; /* (out) Returns 1 if s is found in * x and 0 otherwise. */ { int high, low, middle; low = 0; high = len - 1; while (high >= low) { middle = (high + low) / 2; if (key > x[middle]) { low = middle + 1; } else if (key < x[middle]) { high = middle - 1; } else { *foundPtr = 1; return (middle); } } *foundPtr = 0; return (low); } /* *----------------------------------------------------------------------- * * QuadChoose -- * * Determines the case needed for the computation of the parame- * ters of the quadratic spline. * * Results: * Returns a case number (1-4) which controls how the parameters * of the quadratic spline are evaluated. * *----------------------------------------------------------------------- */ static int QuadChoose(x1, y1, m1, x2, y2, m2, epsilon) double x1, y1; /* Coordinates of one of the points of * interpolation */ double m1; /* Derivative condition at point x1, y1 */ double x2, y2; /* Coordinates of one of the points of * interpolation */ double m2; /* Derivative condition at point x2, y2 */ double epsilon; /* Error tolerance used to distinguish * cases when m1 or m2 is relatively * close to the slope or twice the * slope of the line segment joining * the points x1, y1 and x2, y2. If * epsilon is not 0.0, then epsilon * should be greater than or equal to * machine epsilon. */ { double slope; /* Calculate the slope of the line joining x1,y1 and x2,y2. */ slope = (y2 - y1) / (x2 - x1); if (slope != 0.0) { double relerr; double mref, mref1, mref2, prod1, prod2; prod1 = slope * m1; prod2 = slope * m2; /* Find the absolute values of the slopes slope, m1, and m2. */ mref = Fabs(slope); mref1 = Fabs(m1); mref2 = Fabs(m2); /* * If the relative deviation of m1 or m2 from slope is less than * epsilon, then choose case 2 or case 3. */ relerr = epsilon * mref; if ((Fabs(slope - m1) > relerr) && (Fabs(slope - m2) > relerr) && (prod1 >= 0.0) && (prod2 >= 0.0)) { double prod; prod = (mref - mref1) * (mref - mref2); if (prod < 0.0) { /* * l1, the line through (x1,y1) with slope m1, and l2, * the line through (x2,y2) with slope m2, intersect * at a point whose abscissa is between x1 and x2. * The abscissa becomes a knot of the spline. */ return 1; } if (mref1 > (mref * 2.0)) { if (mref2 <= ((2.0 - epsilon) * mref)) { return 3; } } else if (mref2 <= (mref * 2.0)) { /* * Both l1 and l2 cross the line through (x1+x2)/2.0,y1 * and (x1+x2)/2.0,y2, which is the midline of the * rectangle formed by (x1,y1),(x2,y1), (x2,y2), and * (x1,y2), or both m1 and m2 have signs different * than the sign of slope, or one of m1 and m2 has * opposite sign from slope and l1 and l2 intersect to * the left of x1 or to the right of x2. The point * (x1+x2)/2. is a knot of the spline. */ return 2; } else if (mref1 <= ((2.0 - epsilon) * mref)) { /* * In cases 3 and 4, sign(m1)=sign(m2)=sign(slope). * Either l1 or l2 crosses the midline, but not both. * Choose case 4 if mref1 is greater than * (2.-epsilon)*mref; otherwise, choose case 3. */ return 3; } /* * If neither l1 nor l2 crosses the midline, the spline * requires two knots between x1 and x2. */ return 4; } else { /* * The sign of at least one of the slopes m1 or m2 does not * agree with the sign of *slope*. */ if ((prod1 < 0.0) && (prod2 < 0.0)) { return 2; } else if (prod1 < 0.0) { if (mref2 > ((epsilon + 1.0) * mref)) { return 1; } else { return 2; } } else if (mref1 > ((epsilon + 1.0) * mref)) { return 1; } else { return 2; } } } else if ((m1 * m2) >= 0.0) { return 2; } else { return 1; } } /* * ----------------------------------------------------------------------- * * QuadCases -- * * Computes the knots and other parameters of the spline on the * interval (p1,q1). * * * On input-- * * (p1,y1) and (q1,q2) are the coordinates of the points of * interpolation. * * m1 is the slope at (p1,p2). * * m2 is the slope at (q1,q2) * * ncase controls the number and location of the knots. * * * On output-- * * (v1,v2),(w1,w2),(z1,z2), and (e1,e2) are the coordinates of * the knots and other parameters of the spline on (p1,q1). * (e1,e2) and (y1,y2) are used only if ncase=4. * * ----------------------------------------------------------------------- */ static void QuadCases(p1, p2, m1, m2, q1, q2, param, which) double p1, p2, m1, m2, q1, q2; double param[]; int which; { if ((which == 3) || (which == 4)) { /* Parameters used in both 3 and 4 */ double mbar1, mbar2, mbar3, c1, d1, h1, j1, k1; c1 = p1 + (q2 - p2) / m1; d1 = q1 + (p2 - q2) / m2; h1 = c1 * 2.0 - p1; j1 = d1 * 2.0 - q1; mbar1 = (q2 - p2) / (h1 - p1); mbar2 = (p2 - q2) / (j1 - q1); if (which == 4) { /* Case 4. */ Y1 = (p1 + c1) / 2.0; V1 = (p1 + Y1) / 2.0; V2 = m1 * (V1 - p1) + p2; Z1 = (d1 + q1) / 2.0; W1 = (q1 + Z1) / 2.0; W2 = m2 * (W1 - q1) + q2; mbar3 = (W2 - V2) / (W1 - V1); Y2 = mbar3 * (Y1 - V1) + V2; Z2 = mbar3 * (Z1 - V1) + V2; E1 = (Y1 + Z1) / 2.0; E2 = mbar3 * (E1 - V1) + V2; } else { /* Case 3. */ k1 = (p2 - q2 + q1 * mbar2 - p1 * mbar1) / (mbar2 - mbar1); if (Fabs(m1) > Fabs(m2)) { Z1 = (k1 + p1) / 2.0; } else { Z1 = (k1 + q1) / 2.0; } V1 = (p1 + Z1) / 2.0; V2 = p2 + m1 * (V1 - p1); W1 = (q1 + Z1) / 2.0; W2 = q2 + m2 * (W1 - q1); Z2 = V2 + (W2 - V2) / (W1 - V1) * (Z1 - V1); } } else if (which == 2) { /* Case 2. */ Z1 = (p1 + q1) / 2.0; V1 = (p1 + Z1) / 2.0; V2 = p2 + m1 * (V1 - p1); W1 = (Z1 + q1) / 2.0; W2 = q2 + m2 * (W1 - q1); Z2 = (V2 + W2) / 2.0; } else { /* Case 1. */ double ztwo; Z1 = (p2 - q2 + m2 * q1 - m1 * p1) / (m2 - m1); ztwo = p2 + m1 * (Z1 - p1); V1 = (p1 + Z1) / 2.0; V2 = (p2 + ztwo) / 2.0; W1 = (Z1 + q1) / 2.0; W2 = (ztwo + q2) / 2.0; Z2 = V2 + (W2 - V2) / (W1 - V1) * (Z1 - V1); } } static int QuadSelect(x1, y1, x2, y2, m1, m2, epsilon, param) double x1, y1; double x2, y2; double m1, m2; double epsilon; double param[]; { int ncase; ncase = QuadChoose(x1, y1, m1, x2, y2, m2, epsilon); QuadCases(x1, y1, m1, m2, x2, y2, param, ncase); return (ncase); } /* * ----------------------------------------------------------------------- * * QuadGetImage -- * * ----------------------------------------------------------------------- */ INLINE static double QuadGetImage(p1, p2, p3, x1, x2, x3) double p1, p2, p3; double x1, x2, x3; { double A, B, C; double y; A = x1 - x2; B = x2 - x3; C = x1 - x3; y = (p1 * (A * A) + p2 * 2.0 * B * A + p3 * (B * B)) / (C * C); return (y); } /* * ----------------------------------------------------------------------- * * QuadSpline -- * * Finds the image of a point in x. * * On input * * x Contains the value at which the spline is evaluated. * leftX, leftY * Coordinates of the left-hand data point used in the * evaluation of xvals. * rightX, rightY * Coordinates of the right-hand data point used in the * evaluation of xvals. * Z1, Z2, Y1, Y2, E2, W2, V2 * Parameters of the spline. * ncase Controls the evaluation of the spline by indicating * whether one or two knots were placed in the interval * (xtabs,xtabs1). * * Results: * The image of the spline at x. * * ----------------------------------------------------------------------- */ static double QuadSpline(x, leftX, leftY, rightX, rightY, param, ncase) double x; /* Value at which spline is evaluated */ double leftX, leftY; /* Point to the left of the data point to * be evaluated */ double rightX, rightY; /* Point to the right of the data point to * be evaluated */ double param[]; /* Parameters of the spline */ int ncase; /* Controls the evaluation of the * spline by indicating whether one or * two knots were placed in the * interval (leftX,rightX) */ { if (ncase == 4) { /* * Case 4: More than one knot was placed in the interval. */ /* * Determine the location of data point relative to the 1st knot. */ if (Y1 > x) { return QuadGetImage(leftY, V2, Y2, Y1, x, leftX); } else if (Y1 < x) { /* * Determine the location of the data point relative to * the 2nd knot. */ if (Z1 > x) { return QuadGetImage(Y2, E2, Z2, Z1, x, Y1); } else if (Z1 < x) { return QuadGetImage(Z2, W2, rightY, rightX, x, Z1); } else { return (Z2); } } else { return (Y2); } } else { /* * Cases 1, 2, or 3: * * Determine the location of the data point relative to the * knot. */ if (Z1 < x) { return QuadGetImage(Z2, W2, rightY, rightX, x, Z1); } else if (Z1 > x) { return QuadGetImage(leftY, V2, Z2, Z1, x, leftX); } else { return (Z2); } } } /* * ----------------------------------------------------------------------- * * QuadSlopes -- * * Calculates the derivative at each of the data points. The * slopes computed will insure that an osculatory quadratic * spline will have one additional knot between two adjacent * points of interpolation. Convexity and monotonicity are * preserved wherever these conditions are compatible with the * data. * * Results: * The output array "m" is filled with the derivates at each * data point. * * ----------------------------------------------------------------------- */ static void QuadSlopes(x, y, m, len) double x[]; /* Abscissas of the data points. */ double y[]; /* Ordinates of the data points. */ double m[]; /* (out) To be filled with the first * derivative at each data point. */ int len; /* Number of data points (dimension of * x, y, and m). */ { double xbar, xmid, xhat, ydif1, ydif2; double yxmid; double m1, m2; double m1s, m2s; register int i, next, last; m1s = m2s = m1 = m2 = 0; for (i = 1, next = 2, last = 0; i < (len - 1); i++, next++, last++) { /* * Calculate the slopes of the two lines joining three * consecutive data points. */ ydif1 = y[i] - y[last]; ydif2 = y[next] - y[i]; m1 = ydif1 / (x[i] - x[last]); m2 = ydif2 / (x[next] - x[i]); if (i == 1) { m1s = m1, m2s = m2; /* Save slopes of starting point */ } /* * If one of the preceding slopes is zero or if they have opposite * sign, assign the value zero to the derivative at the middle * point. */ if ((m1 == 0.0) || (m2 == 0.0) || ((m1 * m2) <= 0.0)) { m[i] = 0.0; } else if (Fabs(m1) > Fabs(m2)) { /* * Calculate the slope by extending the line with slope m1. */ xbar = ydif2 / m1 + x[i]; xhat = (xbar + x[next]) / 2.0; m[i] = ydif2 / (xhat - x[i]); } else { /* * Calculate the slope by extending the line with slope m2. */ xbar = -ydif1 / m2 + x[i]; xhat = (x[last] + xbar) / 2.0; m[i] = ydif1 / (x[i] - xhat); } } /* Calculate the slope at the last point, x(n). */ i = len - 2; next = len - 1; if ((m1 * m2) < 0.0) { m[next] = m2 * 2.0; } else { xmid = (x[i] + x[next]) / 2.0; yxmid = m[i] * (xmid - x[i]) + y[i]; m[next] = (y[next] - yxmid) / (x[next] - xmid); if ((m[next] * m2) < 0.0) { m[next] = 0.0; } } /* Calculate the slope at the first point, x(0). */ if ((m1s * m2s) < 0.0) { m[0] = m1s * 2.0; } else { xmid = (x[0] + x[1]) / 2.0; yxmid = m[1] * (xmid - x[1]) + y[1]; m[0] = (yxmid - y[0]) / (xmid - x[0]); if ((m[0] * m1s) < 0.0) { m[0] = 0.0; } } } /* * ----------------------------------------------------------------------- * * QuadEval -- * * QuadEval controls the evaluation of an osculatory quadratic * spline. The user may provide his own slopes at the points of * interpolation or use the subroutine 'QuadSlopes' to calculate * slopes which are consistent with the shape of the data. * * ON INPUT-- * splX must be a nondecreasing vector of points at which the * spline will be evaluated. * x contains the abscissas of the data points to be * interpolated. xtab must be increasing. * y contains the ordinates of the data points to be * interpolated. * m contains the slope of the spline at each point of * interpolation. * len number of data points (dimension of xtab and y). * numEval is the number of points of evaluation (dimension of * xval and yval). * epsilon is a relative error tolerance used in subroutine * 'QuadChoose' to distinguish the situation m(i) or * m(i+1) is relatively close to the slope or twice * the slope of the linear segment between xtab(i) and * xtab(i+1). If this situation occurs, roundoff may * cause a change in convexity or monotonicity of the * resulting spline and a change in the case number * provided by 'QuadChoose'. If epsilon is not equal to zero, * then epsilon should be greater than or equal to machine * epsilon. * ON OUTPUT-- * splY contains the images of the points in xval. * err is one of the following error codes: * 0 - QuadEval ran normally. * 1 - xval(i) is less than xtab(1) for at least one * i or xval(i) is greater than xtab(num) for at * least one i. QuadEval will extrapolate to provide * function values for these abscissas. * 2 - xval(i+1) < xval(i) for some i. * * * QuadEval calls the following subroutines or functions: * Search * QuadCases * QuadChoose * QuadSpline * ----------------------------------------------------------------------- */ static int QuadEval(splX, splY, x, y, m, len, splLen, epsilon) double splX[]; /* Must be a nondecreasing vector of * points at which the spline will be * evaluated. */ double splY[]; /* (out) To be filled with the images * of the points in splX. */ double x[]; /* Abscissas of the data * points to * be interpolated. X must be increasing. */ double y[]; /* Ordinates of the data points to be * interpolated. */ double m[]; /* Slope of the spline at each point * of interpolation. */ int len; /* Number of data points (dimension of * X and y). */ int splLen; /* Number of points of evaluation * (length of vectors of splX and splY). */ double epsilon; /* Relative error tolerance (see choose) */ { int error; register int i; double param[10]; int ncase; int splLast; int start, last, prev; /* Initialize indices and set error result */ start = 0; splLast = splLen - 1; error = 0; last = len - 1; prev = last - 1; ncase = 1; /* * Determine if abscissas of new vector are non-decreasing. */ for (i = 1; i < splLen; i++) { if (splX[i] < splX[i - 1]) { return 2; } } /* * Determine if any of the points in splX are LESS than the * abscissa of the first data point. */ for (i = 0; i < splLen; i++) { if (splX[i] >= x[0]) { break; } start = i + 1; } /* * Determine if any of the points in splX are GREATER than the * abscissa of the last data point. */ for (i = splLen - 1; i >= 0; i--) { if (splX[i] <= x[last]) { break; } splLast = i - 1; } if (start > 0) { error = 1; /* Set error value to indicate that * extrapolation has occurred. */ /* * Calculate the images of points of evaluation whose abscissas * are less than the abscissa of the first data point. */ ncase = QuadSelect(x[0], y[0], x[1], y[1], m[0], m[1], epsilon, param); for (i = 0; i < (start - 1); i++) { splY[i] = QuadSpline(splX[i], x[0], y[0], x[1], y[1], param, ncase); } if (splLen == 1) { return (error); } } if ((splLen > 1) || (splLast == (splLen - 1))) { register int next, loc; int found; /* * Search locates the interval in which the first in-range * point of evaluation lies. */ loc = Search(x, len, splX[start], &found); next = loc + 1; /* * If the first in-range point of evaluation is equal to one * of the data points, assign the appropriate value from y. * Continue until a point of evaluation is found which is not * equal to a data point. */ if (found) { do { splY[start] = y[loc]; start++; if (start >= splLen) { return (error); } } while (splX[start - 1] == splX[start]); for (;;) { if (splX[start] < x[next]) { break; /* Break out of for-loop */ } if (splX[start] == x[next]) { do { splY[start] = y[next]; start++; if (start >= splLen) { return (error); } } while (splX[start] == splX[start - 1]); } loc++; next++; } } /* * Calculate the images of all the points which lie within * range of the data. */ if ((loc > 0) || (error != 1)) { ncase = QuadSelect(x[loc], y[loc], x[next], y[next], m[loc], m[next], epsilon, param); } for (i = start; i <= splLast; i++) { /* * If splX(i) - x(next) is negative, do not recalculate * the parameters for this section of the spline since * they are already known. */ if (splX[i] == x[next]) { splY[i] = y[next]; continue; } else if (splX[i] > x[next]) { double delta; /* Determine that the routine is in the correct part of the spline. */ do { loc++, next++; delta = splX[i] - x[next]; } while (delta > 0.0); if (delta < 0.0) { ncase = QuadSelect(x[loc], y[loc], x[next], y[next], m[loc], m[next], epsilon, param); } else if (delta == 0.0) { splY[i] = y[next]; continue; } } splY[i] = QuadSpline(splX[i], x[loc], y[loc], x[next], y[next], param, ncase); } if (splLast == (splLen - 1)) { return (error); } if ((next == last) && (splX[splLast] != x[last])) { goto noExtrapolation; } } error = 1; /* Set error value to indicate that * extrapolation has occurred. */ ncase = QuadSelect(x[prev], y[prev], x[last], y[last], m[prev], m[last], epsilon, param); noExtrapolation: /* * Calculate the images of the points of evaluation whose * abscissas are greater than the abscissa of the last data point. */ for (i = (splLast + 1); i < splLen; i++) { splY[i] = QuadSpline(splX[i], x[prev], y[prev], x[last], y[last], param, ncase); } return (error); } /* * ----------------------------------------------------------------------- * * Shape preserving quadratic splines * by D.F.Mcallister & J.A.Roulier * Coded by S.L.Dodd & M.Roulier * N.C.State University * * ----------------------------------------------------------------------- */ /* * Driver routine for quadratic spline package * On input-- * X,Y Contain n-long arrays of data (x is increasing) * XM Contains m-long array of x values (increasing) * eps Relative error tolerance * n Number of input data points * m Number of output data points * On output-- * work Contains the value of the first derivative at each data point * ym Contains the interpolated spline value at each data point */ static int QuadraticSpline(x, y, len, splX, splY, splLen, work, epsilon) double x[], y[]; int len; double splX[], splY[]; int splLen; double work[]; double epsilon; { QuadSlopes(x, y, work, len); return QuadEval(splX, splY, x, y, work, len, splLen, epsilon); } /* * ------------------------------------------------------------------------ * * Reference: * Numerical Analysis, <NAME>, <NAME> and <NAME>. * Prindle, Weber & Schmidt 1981 pp 112 * * Parameters: * x - vector of points, assumed to be sorted. * y - vector of corresponding function values. * splX - vector of new points. * splY - vector of new function values. * * ------------------------------------------------------------------------ */ static int NaturalSpline(x, y, len, splX, splY, splLen, work) double x[]; /* Vector of points in ascending order */ double y[]; /* Vector of function values f(x) */ int len; double splX[]; /* New mapping of points */ double splY[]; /* (out) Function values f(nx) */ int splLen; double work[]; /* Working storage */ { int end; int loc, found; register int i, j, n; double *h; /* vector of deltas in x */ double *alpha; double *l, *mu, *z, *a, *b, *c, *d, v; end = len - 1; a = work; b = a + len; c = b + len; d = c + len; h = d + len; l = h + len; z = l + len; mu = z + len; alpha = mu + len; for (i = 0; i < len; i++) { a[i] = y[i]; } /* Calculate vector of differences */ for (i = 0; i < end; i++) { h[i] = x[i + 1] - x[i]; if (h[i] < 0.0) { return TCL_ERROR; } } /* Calculate alpha vector */ for (n = 0, i = 1; i < end; i++, n++) { /* n = i - 1 */ alpha[i] = 3.0 * ((a[i + 1] / h[i]) - (a[i] / h[n]) - (a[i] / h[i]) + (a[n] / h[n])); } /* Vectors to solve the tridiagonal matrix */ l[0] = l[end] = 1.0; mu[0] = mu[end] = 0.0; z[0] = z[end] = 0.0; c[0] = c[end] = 0.0; /* Calculate the intermediate results */ for (n = 0, i = 1; i < end; i++, n++) { /* n = i - 1 */ l[i] = 2 * (h[i] + h[n]) - h[n] * mu[n]; mu[i] = h[i] / l[i]; z[i] = (alpha[i] - h[n] * z[n]) / l[i]; } for (n = end, j = end - 1; j >= 0; j--, n--) { /* n = j + 1 */ c[j] = z[j] - mu[j] * c[n]; b[j] = (a[n] - a[j]) / h[j] - h[j] * (c[n] + 2.0 * c[j]) / 3.0; d[j] = (c[n] - c[j]) / (3.0 * h[j]); } /* Now calculate the new values */ for (j = 0; j < splLen; j++) { v = splX[j]; splY[j] = 0.0; /* Is it outside the interval? */ if ((v < x[0]) || (v > x[end])) { continue; } /* Search for the interval containing v in the x vector */ loc = Search(x, len, v, &found); if (found) { splY[j] = y[loc]; } else { loc--; v -= x[loc]; splY[j] = a[loc] + v * (b[loc] + v * (c[loc] + v * d[loc])); } } return TCL_OK; } /*ARGSUSED*/ static int NaturalOper(tkwin, interp, xPtr, yPtr, splXPtr, splYPtr, argc, argv) Tk_Window tkwin; /* Main window of the interpreter. Used to * process options using Tk_ConfigureWidget */ Tcl_Interp *interp; Blt_Vector *xPtr, *yPtr, *splXPtr, *splYPtr; int argc; /* Not used */ char **argv; /* Not used */ { double *work; int result; /* Allocate space for vectors used in calculation */ work = (double *)ckalloc(sizeof(double) * xPtr->numValues * 9); if (work == NULL) { Tcl_SetResult(interp, "can't allocate working storage for spline", TCL_STATIC); return TCL_ERROR; } result = NaturalSpline(xPtr->valueArr, yPtr->valueArr, xPtr->numValues, splXPtr->valueArr, splYPtr->valueArr, splXPtr->numValues, work); ckfree((char *)work); if (result != TCL_OK) { Tcl_AppendResult(interp, "x vector \"", argv[2], "\" must be sorted in ascending order", (char *)NULL); return TCL_ERROR; } return TCL_OK; } typedef struct { double epsilon; /* Error setting for calculating the spline */ } QuadInfo; #define DEF_QUAD_ERROR "0.0" static Tk_ConfigSpec quadConfigSpecs[] = { {TK_CONFIG_DOUBLE, "-error", (char *)NULL, (char *)NULL, DEF_QUAD_ERROR, Tk_Offset(QuadInfo, epsilon), TK_CONFIG_DONT_SET_DEFAULT}, {TK_CONFIG_END, (char *)NULL, (char *)NULL, (char *)NULL, (char *)NULL, 0, 0} }; /* ARGSUSED */ static int QuadraticOper(tkwin, interp, xPtr, yPtr, splXPtr, splYPtr, argc, argv) Tk_Window tkwin; /* Main window of the interpreter. Used to * process options using Tk_ConfigureWidget */ Tcl_Interp *interp; Blt_Vector *xPtr, *yPtr, *splXPtr, *splYPtr; int argc; /* Not used */ char **argv; { double epsilon; double *work; int result; epsilon = 0.0; /* TBA: adjust error via command-line option */ if (argc > 6) { QuadInfo info; info.epsilon = 0.0; if (Tk_ConfigureWidget(interp, tkwin, quadConfigSpecs, argc - 6, argv + 6, (char *)&info, 0) != TCL_OK) { return TCL_ERROR; } if (info.epsilon < 0.0) { info.epsilon = 0.0; } epsilon = info.epsilon; } /* allocate space for vectors used in calculation */ work = (double *)ckalloc(xPtr->numValues * sizeof(double)); if (work == NULL) { Tcl_SetResult(interp, "can't allocate work array", TCL_STATIC); return TCL_ERROR; } result = QuadraticSpline(xPtr->valueArr, yPtr->valueArr, xPtr->numValues, splXPtr->valueArr, splYPtr->valueArr, splXPtr->numValues, work, epsilon); ckfree((char *)work); if (result != 0) { char tmpString[10]; sprintf(tmpString, "%d", result); Tcl_SetResult(interp, (char *) NULL, TCL_STATIC); Tcl_AppendResult(interp, "error #", tmpString, " in \"", argv[2], "\"", (char *) NULL); return TCL_ERROR; } return TCL_OK; } static Blt_OperSpec operSpecs[] = { {"natural", 1, (Blt_OperProc) NaturalOper, 6, 0, "x y splx sply ?option value?...",}, {"quadratic", 1, (Blt_OperProc) QuadraticOper, 6, 0, "x y splx sply ?option value?...",}, }; static int numSpecs = sizeof(operSpecs) / sizeof(Blt_OperSpec); static int SplineCmd(clientData, interp, argc, argv) ClientData clientData; Tcl_Interp *interp; int argc; char **argv; { Tk_Window tkwin = (Tk_Window)clientData; Blt_OperProc proc; Blt_Vector x, y, splX, splY; register int i; int result; proc = Blt_LookupOperation(interp, numSpecs, operSpecs, BLT_OPER_ARG1, argc, argv); if (proc == NULL) { return TCL_ERROR; } if ((Blt_GetVector(interp, argv[2], &x) != TCL_OK) || (Blt_GetVector(interp, argv[3], &y) != TCL_OK) || (Blt_GetVector(interp, argv[4], &splX) != TCL_OK)) { return TCL_ERROR; } if (x.numValues < 3) { Tcl_AppendResult(interp, "length of vector \"", argv[2], "\" is < 3", (char *)NULL); return TCL_ERROR; } for (i = 1; i < x.numValues; i++) { if (x.valueArr[i] <= x.valueArr[i - 1]) { Tcl_AppendResult(interp, "x vector \"", argv[2], "\" must be monotonically increasing", (char *)NULL); return TCL_ERROR; } } if (x.numValues != y.numValues) { Tcl_AppendResult(interp, "vectors \"", argv[2], "\" and \"", argv[3], " have different lengths", (char *)NULL); return TCL_ERROR; } if (Blt_GetVector(interp, argv[5], &splY) != TCL_OK) { /* * If the named vector to hold the ordinates of the spline * doesn't exist, create one the same size as the vector * containing the abscissas. */ if (Blt_CreateVector(interp, argv[5], splX.numValues, &splY) != TCL_OK) { return TCL_ERROR; } } else if (splX.numValues != splY.numValues) { /* * The x and y vectors differ in size. Make the number of ordinates * the same as the number of abscissas. */ if (Blt_ResizeVector(interp, argv[5], splX.numValues) != TCL_OK) { return TCL_ERROR; } /* Re-get the vector, since its size has now changed */ if (Blt_GetVector(interp, argv[5], &splY) != TCL_OK) { return TCL_ERROR; } } result = (*proc) (tkwin, interp, &x, &y, &splX, &splY, argc, argv); if (result != TCL_OK) { return TCL_ERROR; } /* * Update the vector. In this case, we're merely notifying the * vector management routines that the values have changed (the * memory is still the same). The vector does not need to be * reallocated (TCL_STATIC is ignored). */ if (Blt_ResetVector(interp, argv[5], &splY, TCL_STATIC) != TCL_OK) { return TCL_ERROR; } return TCL_OK; } int Blt_SplineInit(interp) Tcl_Interp *interp; { static Blt_CmdSpec cmdSpec = { "spline", SPLINE_VERSION, (Tcl_CmdProc*)SplineCmd, }; return (Blt_InitCmd(interp, &cmdSpec)); } #endif /* !NO_SPLINE */
secret-family-recipes-04/front-end
src/mocks/DummyData.js
const myRecipelist = [ {id: 1, name: 'Casserole', source: 'Grandma Betty', serves: '3-4 people', prepTime: 20, cookTime: 30, ingredients: ['1lb Penne Noodles', '1lb ground beef', '1 onion', '1 can of diced tomatoes', '2 garlic cloves, minced', '1 jar spaghetti sauce', '1/2 lb fresh mushrooms', '1 tsp italian seasoning', '3/4 cups of shredded mozzarella' ], instructions: ['In a large skillet, cook beef and onion over medium heat until no longer pink. Add garlic; cook 1 minute longer. Drain. Stir in spaghetti sauce, diced tomatoes, mushrooms and Italian seasoning. Bring to a boil. Reduce heat; simmer, uncovered, 20 minutes.', 'Meanwhile, preheat oven to 350°. Cook pasta according to package directions; drain. Add to beef mixture and gently stir in sliced plum tomatoes.', 'Transfer to an ungreased 13x9-in. baking dish. Sprinkle with cheeses. Bake 25-30 minutes or until bubbly and heated through.'], image: 'https://images.unsplash.com/photo-1586032340364-03f75289e661?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fGNhc3Nlcm9sZXxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=700&q=60' }, {id: 2, name: '<NAME>', source: 'Aunt Tina', serves: '3-4 people', prepTime: 5, cookTime: 8, ingredients: ['2 slices of bread', '1/2 tablespoon of butter', '3 slices of cheddar cheese' ], instructions: ['Spread 1/2 Tbsp butter on one side of each slice of bread', 'Place a skillet over low to medium/low heat. A griddle should be at 275˚F. Immediately add 2 slices of bread with the butter-side-down.', 'Stack cheeses on one of the pieces of bread, cover with the other piece of toast and flip the sandwich over.', 'Continue sauteeing, flipping once, until both sides are golden brown and cheese is melted.', 'Cut the sandwich in half on the diagonal to serve.'], image: 'https://images.unsplash.com/photo-1608039858788-667850f129f6?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80' }, {id: 3, name: '<NAME>', source: 'Uncle Tony', serves: '3-4 people', prepTime: 20, cookTime: 20, ingredients: ['salt', '10 oz linguine', '1 1/4 pounds large, peeled shrimp', '1/3 cup olive oil', '5 cloves garlic, minced', '1/4 teaspoon red pepper flakes', '1/3 cup dry white wine', '1/4 cup lemon juice', '4 tablespoons butter', '1/4 cup chopped parsley' ], instructions: ['Bring a large pot of salted water to a boil. Add the linguine and cook as the label directs. Reserve 1 cup cooking water, then drain.', 'Meanwhile, season the shrimp with salt. Heat the olive oil in a large skillet over medium-high heat. Add the garlic and red pepper flakes and cook until the garlic is just golden, 30 seconds to 1 minute. Add the shrimp and cook, stirring occasionally, until pink and just cooked through, 1 to 2 minutes per side. Remove the shrimp to a plate. Add the wine and lemon juice to the skillet and simmer until slightly reduced, 2 minutes.', 'Return the shrimp and any juices from the plate to the skillet along with the linguine, butter and 1/2 cup of the reserved cooking water. Continue to cook, tossing, until the butter is melted and the shrimp is hot, about 2 minutes, adding more of the reserved cooking water as needed. Season with salt; stir in the parsley. Serve with lemon wedges. '], image: 'https://images.unsplash.com/photo-1623345541450-9bf0cbb6faab?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340&q=80' } ]; export default myRecipelist; // recipe card has the following features: // Id: int // recipeName: string // Source: string // Serves: string (could be a range like 3-4 ppl; how many people can the recipe serve) // Prep Time: int (minutes) // Cook Time: int (minutes) // Ingredients: array (of strings) // Instructions: array (of strings) // Image: img (this is optional but preferred)
hydratk/hydratk
src/hydratk/core/message.py
# -*- coding: utf-8 -*- """HydraTK core commmunication messages definition .. module:: core.message :platform: Unix :synopsis: HydraTK core commmunication messages definition .. moduleauthor:: <NAME> <<EMAIL>> """ REQUEST = 1 # request RESPONSE = 2 # info INFO = 3 # info SERVICE_STATUS = 4 # info MONITOR = 5 # request SERVICE_IDENT = 6 # info SERVICES_MAP = 7 # info SERVICE_SHUTDOWN = 8 # info SERVICE_HELLO = 9 # info, new ident alternative PING = 10 # request PONG = 11 # response COPY = 12 # msg copy for the monitor request SERVICE_ALERT = 13 # info SERVICE_ERROR = 99 # info SERVICE_DROPPED = 100 # info SERVICE_KILLED = 101 # info DUMMY_FIRST = 300 # dummy 1st test message DUMMY = 301 # dummy test message DUMMY_LAST = 302 # dummy test message # messages with number < 500 are core reserved numbers types = { 'FN_CALLBACK': 1 } class Message(object): """Class Message """ _type = None class FnCallBackMsg(Message): """ Class FnCallBackMsg Inherited from Message """ _type = types['FN_CALLBACK'] _callback = None _args = None _kwargs = None def __init__(self, callback, *args, **kwargs): """Class constructor Called when object is initialized Args: callback (callable): callback args (args): arguments kwargs (kwargs): key value arguments """ self.set_callback(callback) self.set_args(*args, **kwargs) def set_callback(self, callback): """Method sets callback Args: callback (callable): callback Returns: void Raises: error: TypeError """ if callable(callback): self._callback = callback else: raise TypeError('Callable object required') def set_args(self, *args, **kwargs): """Method sets arguments Args: args (args): arguments kwargs (kwargs): key value arguments Returns: void """ self._args = args self._kwargs = kwargs def run(self): """Method executes callback Args: Returns: obj: callback output """ return self._callback(self, *self._args, **self._kwargs)
whatedcgveg/v2ray-core
proxy/http/config.pb.go
package http import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Config for HTTP proxy server. type ServerConfig struct { Timeout uint32 `protobuf:"varint,1,opt,name=timeout" json:"timeout,omitempty"` } func (m *ServerConfig) Reset() { *m = ServerConfig{} } func (m *ServerConfig) String() string { return proto.CompactTextString(m) } func (*ServerConfig) ProtoMessage() {} func (*ServerConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *ServerConfig) GetTimeout() uint32 { if m != nil { return m.Timeout } return 0 } // ClientConfig for HTTP proxy client. type ClientConfig struct { } func (m *ClientConfig) Reset() { *m = ClientConfig{} } func (m *ClientConfig) String() string { return proto.CompactTextString(m) } func (*ClientConfig) ProtoMessage() {} func (*ClientConfig) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func init() { proto.RegisterType((*ServerConfig)(nil), "v2ray.core.proxy.http.ServerConfig") proto.RegisterType((*ClientConfig)(nil), "v2ray.core.proxy.http.ClientConfig") } func init() { proto.RegisterFile("github.com/whatedcgveg/v2ray-core/proxy/http/config.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 161 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x2b, 0x33, 0x2a, 0x4a, 0xac, 0xd4, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, 0x2f, 0x4a, 0xd5, 0x2f, 0x28, 0xca, 0xaf, 0xa8, 0xd4, 0xcf, 0x28, 0x29, 0x29, 0xd0, 0x4f, 0xce, 0xcf, 0x4b, 0xcb, 0x4c, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x85, 0xa9, 0x2b, 0x4a, 0xd5, 0x03, 0xab, 0xd1, 0x03, 0xa9, 0x51, 0xd2, 0xe0, 0xe2, 0x09, 0x4e, 0x2d, 0x2a, 0x4b, 0x2d, 0x72, 0x06, 0x2b, 0x16, 0x92, 0xe0, 0x62, 0x2f, 0xc9, 0xcc, 0x4d, 0xcd, 0x2f, 0x2d, 0x91, 0x60, 0x54, 0x60, 0xd4, 0xe0, 0x0d, 0x82, 0x71, 0x95, 0xf8, 0xb8, 0x78, 0x9c, 0x73, 0x32, 0x53, 0xf3, 0x4a, 0x20, 0x2a, 0x9d, 0xac, 0xb9, 0x24, 0x93, 0xf3, 0x73, 0xf5, 0xb0, 0x1a, 0x1b, 0xc0, 0x18, 0xc5, 0x02, 0xa2, 0x57, 0x31, 0x89, 0x86, 0x19, 0x05, 0x25, 0x56, 0xea, 0x39, 0x83, 0xe4, 0x03, 0xc0, 0xf2, 0x1e, 0x25, 0x25, 0x05, 0x49, 0x6c, 0x60, 0x47, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xc9, 0xae, 0x86, 0xab, 0xbe, 0x00, 0x00, 0x00, }
ArriolaHarold2001/addedlamps
build/tmp/expandedArchives/forge-1.17.1-37.0.58_mapped_official_1.17.1-sources.jar_461b1baaba5fdaecf94c73039d52c00b/net/minecraft/world/level/levelgen/feature/configurations/RandomPatchConfiguration.java
package net.minecraft.world.level.levelgen.feature.configurations; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.mojang.serialization.Codec; import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import net.minecraft.util.ExtraCodecs; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.levelgen.feature.blockplacers.BlockPlacer; import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; public class RandomPatchConfiguration implements FeatureConfiguration { public static final Codec<RandomPatchConfiguration> CODEC = RecordCodecBuilder.create((p_67955_) -> { return p_67955_.group(BlockStateProvider.CODEC.fieldOf("state_provider").forGetter((p_161075_) -> { return p_161075_.stateProvider; }), BlockPlacer.CODEC.fieldOf("block_placer").forGetter((p_161073_) -> { return p_161073_.blockPlacer; }), BlockState.CODEC.listOf().fieldOf("whitelist").forGetter((p_161071_) -> { return p_161071_.whitelist.stream().map(Block::defaultBlockState).collect(Collectors.toList()); }), BlockState.CODEC.listOf().fieldOf("blacklist").forGetter((p_161069_) -> { return ImmutableList.copyOf(p_161069_.blacklist); }), ExtraCodecs.POSITIVE_INT.fieldOf("tries").orElse(128).forGetter((p_161067_) -> { return p_161067_.tries; }), ExtraCodecs.NON_NEGATIVE_INT.fieldOf("xspread").orElse(7).forGetter((p_161065_) -> { return p_161065_.xspread; }), ExtraCodecs.NON_NEGATIVE_INT.fieldOf("yspread").orElse(3).forGetter((p_161063_) -> { return p_161063_.yspread; }), ExtraCodecs.NON_NEGATIVE_INT.fieldOf("zspread").orElse(7).forGetter((p_161061_) -> { return p_161061_.zspread; }), Codec.BOOL.fieldOf("can_replace").orElse(false).forGetter((p_161059_) -> { return p_161059_.canReplace; }), Codec.BOOL.fieldOf("project").orElse(true).forGetter((p_161057_) -> { return p_161057_.project; }), Codec.BOOL.fieldOf("need_water").orElse(false).forGetter((p_161055_) -> { return p_161055_.needWater; })).apply(p_67955_, RandomPatchConfiguration::new); }); public final BlockStateProvider stateProvider; public final BlockPlacer blockPlacer; public final Set<Block> whitelist; public final Set<BlockState> blacklist; public final int tries; public final int xspread; public final int yspread; public final int zspread; public final boolean canReplace; public final boolean project; public final boolean needWater; private RandomPatchConfiguration(BlockStateProvider p_67916_, BlockPlacer p_67917_, List<BlockState> p_67918_, List<BlockState> p_67919_, int p_67920_, int p_67921_, int p_67922_, int p_67923_, boolean p_67924_, boolean p_67925_, boolean p_67926_) { this(p_67916_, p_67917_, p_67918_.stream().map(BlockBehaviour.BlockStateBase::getBlock).collect(Collectors.toSet()), ImmutableSet.copyOf(p_67919_), p_67920_, p_67921_, p_67922_, p_67923_, p_67924_, p_67925_, p_67926_); } RandomPatchConfiguration(BlockStateProvider p_67928_, BlockPlacer p_67929_, Set<Block> p_67930_, Set<BlockState> p_67931_, int p_67932_, int p_67933_, int p_67934_, int p_67935_, boolean p_67936_, boolean p_67937_, boolean p_67938_) { this.stateProvider = p_67928_; this.blockPlacer = p_67929_; this.whitelist = p_67930_; this.blacklist = p_67931_; this.tries = p_67932_; this.xspread = p_67933_; this.yspread = p_67934_; this.zspread = p_67935_; this.canReplace = p_67936_; this.project = p_67937_; this.needWater = p_67938_; } public static class GrassConfigurationBuilder { private final BlockStateProvider stateProvider; private final BlockPlacer blockPlacer; private Set<Block> whitelist = ImmutableSet.of(); private Set<BlockState> blacklist = ImmutableSet.of(); private int tries = 64; private int xspread = 7; private int yspread = 3; private int zspread = 7; private boolean canReplace; private boolean project = true; private boolean needWater; public GrassConfigurationBuilder(BlockStateProvider p_67988_, BlockPlacer p_67989_) { this.stateProvider = p_67988_; this.blockPlacer = p_67989_; } public RandomPatchConfiguration.GrassConfigurationBuilder whitelist(Set<Block> p_67994_) { this.whitelist = p_67994_; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder blacklist(Set<BlockState> p_67999_) { this.blacklist = p_67999_; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder tries(int p_67992_) { this.tries = p_67992_; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder xspread(int p_67997_) { this.xspread = p_67997_; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder yspread(int p_68002_) { this.yspread = p_68002_; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder zspread(int p_68005_) { this.zspread = p_68005_; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder canReplace() { this.canReplace = true; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder noProjection() { this.project = false; return this; } public RandomPatchConfiguration.GrassConfigurationBuilder needWater() { this.needWater = true; return this; } public RandomPatchConfiguration build() { return new RandomPatchConfiguration(this.stateProvider, this.blockPlacer, this.whitelist, this.blacklist, this.tries, this.xspread, this.yspread, this.zspread, this.canReplace, this.project, this.needWater); } } }
HulinCedric/trafalgar-simulator
src/Radar/T_Radar_N0_2_1.cpp
// // IUT de Nice / Departement informatique / Module APO-C++ // Annee 2008_2009 - Package _Trafalgar // // Classe Radar - Tests unitaires de la methode de classe privee cibleCachee (Lot 1) // (Cas nominaux / Une seule ile) // // Auteur : <NAME>, <NAME>, <NAME> // #include "Radar.h" #include "../../_Tests/Tests/Tests.h" void main () { Tests::Begin("_Trafalgar.Radar", "1.0.0"); Tests::Design("Controle de la methode de classe privee cibleCachee (Lot 1)", 3); Point O(0, 0), A(2, 0), B(0, 2); Triangle OAB(O, A, B); Tests::Case("Cas d'une seule ile / Point cible cache par l'ile"); { Point positionPorteur(1, 3), positionCible(1, -1); list <Triangle> topologie; topologie.push_back(OAB); Tests::Unit(true, Radar::cibleCachee(positionPorteur, positionCible, topologie)); } Tests::Case("Cas d'une seule ile / Point cible cache par une extremite de l'ile"); { Point positionPorteur(2, 2), positionCible(2, -1); list <Triangle> topologie; topologie.push_back(OAB); Tests::Unit(true, Radar::cibleCachee(positionPorteur, positionCible, topologie)); } Tests::Case("Cas d'une seule ile / Point cible visible"); { Point positionPorteur(2, 2), positionCible(3, -1); list <Triangle> topologie; topologie.push_back(OAB); Tests::Unit(false, Radar::cibleCachee(positionPorteur, positionCible, topologie)); } Tests::End(); }
tusharchoudhary0003/Custom-Football-Game
sources/com/paypal/android/sdk/payments/C11948l.java
package com.paypal.android.sdk.payments; import android.text.Editable; import android.text.TextWatcher; /* renamed from: com.paypal.android.sdk.payments.l */ final class C11948l implements TextWatcher { /* renamed from: a */ private /* synthetic */ LoginActivity f37574a; C11948l(LoginActivity loginActivity) { this.f37574a = loginActivity; } public final void afterTextChanged(Editable editable) { this.f37574a.m39286h(); } public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } }
86dh/bc-java
core/src/main/java/org/bouncycastle/pqc/crypto/picnic/LowmcConstants.java
<filename>core/src/main/java/org/bouncycastle/pqc/crypto/picnic/LowmcConstants.java package org.bouncycastle.pqc.crypto.picnic; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.bouncycastle.util.Pack; import org.bouncycastle.util.encoders.Hex; class LowmcConstants { // Parameters for security level L1 // Block/key size: 128 // Rounds: 20 private static final int[] linearMatrices_L1; private static final int[] roundConstants_L1; private static final int[] keyMatrices_L1; private static final KMatrices LMatrix_L1; private static final KMatrices KMatrix_L1; private static final KMatrices RConstants_L1; // Parameters for security level L1, full s-box layer // Block/key size: 129 // Rounds: 4 // Note that each 129-bit row of the matrix is zero padded to 160 bits (the next multiple of 32) private static final int[] linearMatrices_L1_full; private static final int[] keyMatrices_L1_full; private static final int[] keyMatrices_L1_inv; private static final int[] linearMatrices_L1_inv; private static final int[] roundConstants_L1_full; private static final KMatrices LMatrix_L1_full; private static final KMatrices LMatrix_L1_inv; private static final KMatrices KMatrix_L1_full; private static final KMatrices KMatrix_L1_inv; private static final KMatrices RConstants_L1_full; // Parameters for security level L3 // Block/key size: 192 // Rounds: 30 private static final int[] linearMatrices_L3; private static final int[] roundConstants_L3; private static final int[] keyMatrices_L3; private static final KMatrices LMatrix_L3; private static final KMatrices KMatrix_L3; private static final KMatrices RConstants_L3; // Parameters for security level L3, full s-box layer // Block/key size: 192 // S-boxes: 64 // Rounds: 4 private static final int[] linearMatrices_L3_full; private static final int[] linearMatrices_L3_inv; private static final int[] roundConstants_L3_full; private static final int[] keyMatrices_L3_full; private static final int[] keyMatrices_L3_inv; private static final KMatrices LMatrix_L3_full; private static final KMatrices LMatrix_L3_inv; private static final KMatrices KMatrix_L3_full; private static final KMatrices KMatrix_L3_inv; private static final KMatrices RConstants_L3_full; // Parameters for security level L5 // Block/key size: 256 // Rounds: 38 private static final int[] linearMatrices_L5; private static final int[] roundConstants_L5; private static final int[] keyMatrices_L5; private static final KMatrices LMatrix_L5; private static final KMatrices KMatrix_L5; private static final KMatrices RConstants_L5; // Parameters for security level L5, full nonlinear layer // Block/key size: 255 // S-boxes: 85 // Rounds: 4 private static final int[] linearMatrices_L5_full; private static final int[] linearMatrices_L5_inv; private static final int[] roundConstants_L5_full; private static final int[] keyMatrices_L5_full; private static final int[] keyMatrices_L5_inv; private static final KMatrices LMatrix_L5_full; private static final KMatrices LMatrix_L5_inv; private static final KMatrices KMatrix_L5_full; private static final KMatrices KMatrix_L5_inv; private static final KMatrices RConstants_L5_full; static { InputStream input = LowmcConstants.class.getResourceAsStream("lowmc.properties"); Properties props = new Properties(); // load a properties file try { props.load(input); } catch (IOException e) { throw new IllegalStateException("unable to load Picnic properties: " + e.getMessage(), e); } // Parameters for security level L1 // Block/key size: 128 // Rounds: 20 linearMatrices_L1 = ReadFromProperty(props, "linearMatrices_L1", 40960); roundConstants_L1 = ReadFromProperty(props, "roundConstants_L1", 320); keyMatrices_L1 = ReadFromProperty(props, "keyMatrices_L1", 43008); LMatrix_L1 = new KMatrices(20, 128, 4, linearMatrices_L1); KMatrix_L1 = new KMatrices(21, 128, 4, keyMatrices_L1); RConstants_L1 = new KMatrices(0, 1, 4, roundConstants_L1); // Parameters for security level L1, full s-box layer // Block/key size: 129 // Rounds: 4 // Note that each 129-bit row of the matrix is zero padded to 160 bits (the next multiple of 32) linearMatrices_L1_full = ReadFromProperty(props, "linearMatrices_L1_full", 12800); keyMatrices_L1_full = ReadFromProperty(props, "keyMatrices_L1_full", 12900); keyMatrices_L1_inv = ReadFromProperty(props, "keyMatrices_L1_inv", 2850); linearMatrices_L1_inv = ReadFromProperty(props, "linearMatrices_L1_inv", 12800); roundConstants_L1_full = ReadFromProperty(props, "roundConstants_L1_full", 80); LMatrix_L1_full = new KMatrices(4, 129, 5, linearMatrices_L1_full); LMatrix_L1_inv = new KMatrices(4, 129, 5, linearMatrices_L1_inv); KMatrix_L1_full = new KMatrices(5, 129, 5, keyMatrices_L1_full); KMatrix_L1_inv = new KMatrices(1, 129, 5, keyMatrices_L1_inv); RConstants_L1_full = new KMatrices(4, 1, 5, roundConstants_L1_full); // Parameters for security level L3 // Block/key size: 192 // Rounds: 30 linearMatrices_L3 = ReadFromProperty(props, "linearMatrices_L3", 138240); roundConstants_L3 = ReadFromProperty(props, "roundConstants_L3", 720); keyMatrices_L3 = ReadFromProperty(props, "keyMatrices_L3", 142848); LMatrix_L3 = new KMatrices(30, 192, 6, linearMatrices_L3); KMatrix_L3 = new KMatrices(31, 192, 6, keyMatrices_L3); RConstants_L3 = new KMatrices(30, 1, 6, roundConstants_L3); // Parameters for security level L3, full s-box layer // Block/key size: 192 // S-boxes: 64 // Rounds: 4 linearMatrices_L3_full = ReadFromProperty(props, "linearMatrices_L3_full", 18432); linearMatrices_L3_inv = ReadFromProperty(props, "linearMatrices_L3_inv", 18432); roundConstants_L3_full = ReadFromProperty(props, "roundConstants_L3_full", 96); keyMatrices_L3_full = ReadFromProperty(props, "keyMatrices_L3_full", 23040); keyMatrices_L3_inv = ReadFromProperty(props, "keyMatrices_L3_inv", 4608); LMatrix_L3_full = new KMatrices(4, 192, 6, linearMatrices_L3_full); LMatrix_L3_inv = new KMatrices(4, 192, 6, linearMatrices_L3_inv); KMatrix_L3_full = new KMatrices(5, 192, 6, keyMatrices_L3_full); KMatrix_L3_inv = new KMatrices(1, 192, 6, keyMatrices_L3_inv); RConstants_L3_full = new KMatrices(4, 1, 6, roundConstants_L3_full); // Parameters for security level L5 // Block/key size: 256 // Rounds: 38 linearMatrices_L5 = ReadFromProperty(props, "linearMatrices_L5", 311296); roundConstants_L5 = ReadFromProperty(props, "roundConstants_L5", 1216); keyMatrices_L5 = ReadFromProperty(props, "keyMatrices_L5", 319488); LMatrix_L5 = new KMatrices(38, 256, 8, linearMatrices_L5); KMatrix_L5 = new KMatrices(39, 256, 8, keyMatrices_L5); RConstants_L5 = new KMatrices(38, 1, 8, roundConstants_L5); // Parameters for security level L5, full nonlinear layer // Block/key size: 255 // S-boxes: 85 // Rounds: 4 linearMatrices_L5_full = ReadFromProperty(props, "linearMatrices_L5_full", 32768); linearMatrices_L5_inv = ReadFromProperty(props, "linearMatrices_L5_inv", 32768); roundConstants_L5_full = ReadFromProperty(props, "roundConstants_L5_full", 128); keyMatrices_L5_full = ReadFromProperty(props, "keyMatrices_L5_full", 40960); keyMatrices_L5_inv = ReadFromProperty(props, "keyMatrices_L5_inv", 8160); LMatrix_L5_full = new KMatrices(4, 255, 8, linearMatrices_L5_full); LMatrix_L5_inv = new KMatrices(4, 255, 8, linearMatrices_L5_inv); KMatrix_L5_full = new KMatrices(5, 255, 8, keyMatrices_L5_full); KMatrix_L5_inv = new KMatrices(1, 255, 8, keyMatrices_L5_inv); RConstants_L5_full = new KMatrices(4, 1, 8, roundConstants_L5_full); } static private int[] ReadFromProperty(Properties props, String key, int intSize) { String s = props.getProperty(key); s = s.replaceAll(",", ""); byte[] bytes = Hex.decode(s); int[] ints = new int[intSize]; for (int i = 0; i < bytes.length / 4; i++) { ints[i] = Pack.littleEndianToInt(bytes, i * 4); } return ints; } // Functions to return individual matricies and round constants /* Return a pointer to the r-th matrix. The caller must know the dimensions */ private static KMatrices GET_MAT(KMatrices m, int r) { m.setMatrixPointer(r * m.getSize()); return m; } /* Return the LowMC linear matrix for this round */ static KMatrices LMatrix(PicnicEngine engine, int round) { if (engine.stateSizeBits == 128) { return GET_MAT(LMatrix_L1, round); } else if (engine.stateSizeBits == 129) { return GET_MAT(LMatrix_L1_full, round); } else if (engine.stateSizeBits == 192) { if (engine.numRounds == 4) { return GET_MAT(LMatrix_L3_full, round); } else { return GET_MAT(LMatrix_L3, round); } } else if (engine.stateSizeBits == 255) { return GET_MAT(LMatrix_L5_full, round); } else if (engine.stateSizeBits == 256) { return GET_MAT(LMatrix_L5, round); } else { return null; } } /* Return the LowMC inverse linear layer matrix for this round */ static KMatrices LMatrixInv(PicnicEngine engine, int round) { if (engine.stateSizeBits == 129) { return GET_MAT(LMatrix_L1_inv, round); } else if (engine.stateSizeBits == 192 && engine.numRounds == 4) { return GET_MAT(LMatrix_L3_inv, round); } else if (engine.stateSizeBits == 255) { return GET_MAT(LMatrix_L5_inv, round); } else { return null; } } /* Return the LowMC key matrix for this round */ static KMatrices KMatrix(PicnicEngine engine, int round) { if (engine.stateSizeBits == 128) { return GET_MAT(KMatrix_L1, round); } else if (engine.stateSizeBits == 129) { return GET_MAT(KMatrix_L1_full, round); } else if (engine.stateSizeBits == 192) { if (engine.numRounds == 4) { return GET_MAT(KMatrix_L3_full, round); } else { return GET_MAT(KMatrix_L3, round); } } else if (engine.stateSizeBits == 255) { return GET_MAT(KMatrix_L5_full, round); } else if (engine.stateSizeBits == 256) { return GET_MAT(KMatrix_L5, round); } else { return null; } } /* Return the LowMC inverse key matrix for this round */ static KMatrices KMatrixInv(PicnicEngine engine, int round) { assert (round == 0); if (engine.stateSizeBits == 129) { return GET_MAT(KMatrix_L1_inv, round); } else if (engine.stateSizeBits == 192 && engine.numRounds == 4) { return GET_MAT(KMatrix_L3_inv, round); } else if (engine.stateSizeBits == 255) { return GET_MAT(KMatrix_L5_inv, round); } else { return null; } } /* Return the LowMC round constant for this round */ static KMatrices RConstant(PicnicEngine engine, int round) { if (engine.stateSizeBits == 128) { return GET_MAT(RConstants_L1, round); } else if (engine.stateSizeBits == 129) { return GET_MAT(RConstants_L1_full, round); } else if (engine.stateSizeBits == 192) { if (engine.numRounds == 4) { return GET_MAT(RConstants_L3_full, round); } else { return GET_MAT(RConstants_L3, round); } } else if (engine.stateSizeBits == 255) { return GET_MAT(RConstants_L5_full, round); } else if (engine.stateSizeBits == 256) { return GET_MAT(RConstants_L5, round); } else { return null; } } }
gfelbing/MicroService
microservice_core/src/main/java/de/gfelbing/microservice/core/concurrency/ExecutorServiceModule.java
<gh_stars>0 package de.gfelbing.microservice.core.concurrency; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import com.google.inject.Singleton; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; /** * Module for ExecutorServices. * <p> * With this module you are able to inject: * - A #link{ScheduledExecutorService} based on the #{ServiceConfiguration} * - A #link{ExecutorService} which is basically the ScheduledExecutorService * * @author <EMAIL> on 06.05.15. */ public final class ExecutorServiceModule extends AbstractModule { @Override protected void configure() { } @Provides @Singleton @Inject ExecutorService executorService(final ScheduledExecutorService scheduledExecutorService) { return scheduledExecutorService; } @Provides @Singleton @Inject ScheduledExecutorService scheduledExecutorService(final ExecutorServiceConfiguration serviceConfiguration) { return Executors.newScheduledThreadPool(serviceConfiguration.getThreadpoolsize()); } }
Altiscale/incubator-tez
tez-dag/src/main/java/org/apache/tez/dag/app/dag/impl/Edge.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tez.dag.app.dag.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.tez.common.RuntimeUtils; import org.apache.tez.dag.api.EdgeManager; import org.apache.tez.dag.api.EdgeManagerContext; import org.apache.tez.dag.api.EdgeManagerDescriptor; import org.apache.tez.dag.api.EdgeProperty; import org.apache.tez.dag.api.TezUncheckedException; import org.apache.tez.dag.api.EdgeProperty.DataMovementType; import org.apache.tez.dag.app.dag.Task; import org.apache.tez.dag.app.dag.Vertex; import org.apache.tez.dag.app.dag.event.TaskAttemptEventOutputFailed; import org.apache.tez.dag.app.dag.event.TaskEventAddTezEvent; import org.apache.tez.dag.records.TezTaskAttemptID; import org.apache.tez.dag.records.TezTaskID; import org.apache.tez.runtime.api.Event; import org.apache.tez.runtime.api.events.CompositeDataMovementEvent; import org.apache.tez.runtime.api.events.DataMovementEvent; import org.apache.tez.runtime.api.events.InputFailedEvent; import org.apache.tez.runtime.api.events.InputReadErrorEvent; import org.apache.tez.runtime.api.impl.EventMetaData; import org.apache.tez.runtime.api.impl.InputSpec; import org.apache.tez.runtime.api.impl.OutputSpec; import org.apache.tez.runtime.api.impl.TezEvent; import org.apache.tez.runtime.api.impl.EventMetaData.EventProducerConsumerType; import com.google.common.collect.Maps; import static com.google.common.base.Preconditions.checkNotNull; public class Edge { static class EdgeManagerContextImpl implements EdgeManagerContext { private final String srcVertexName; private final String destVertexName; private final byte[] userPayload; EdgeManagerContextImpl(String srcVertexName, String destVertexName, @Nullable byte[] userPayload) { checkNotNull(srcVertexName, "srcVertexName is null"); checkNotNull(destVertexName, "destVertexName is null"); this.srcVertexName = srcVertexName; this.destVertexName = destVertexName; this.userPayload = userPayload; } @Override public byte[] getUserPayload() { return userPayload; } @Override public String getSrcVertexName() { return srcVertexName; } @Override public String getDestVertexName() { return destVertexName; } } private EdgeProperty edgeProperty; private EdgeManagerContext edgeManagerContext; private EdgeManager edgeManager; @SuppressWarnings("rawtypes") private EventHandler eventHandler; private AtomicBoolean bufferEvents = new AtomicBoolean(false); private List<TezEvent> destinationEventBuffer = new ArrayList<TezEvent>(); private List<TezEvent> sourceEventBuffer = new ArrayList<TezEvent>(); private Vertex sourceVertex; private Vertex destinationVertex; // this may end up being a list for shared edge private EventMetaData destinationMetaInfo; @SuppressWarnings("rawtypes") public Edge(EdgeProperty edgeProperty, EventHandler eventHandler) { this.edgeProperty = edgeProperty; this.eventHandler = eventHandler; createEdgeManager(); } private void createEdgeManager() { switch (edgeProperty.getDataMovementType()) { case ONE_TO_ONE: edgeManager = new OneToOneEdgeManager(); break; case BROADCAST: edgeManager = new BroadcastEdgeManager(); break; case SCATTER_GATHER: edgeManager = new ScatterGatherEdgeManager(); break; case CUSTOM: String edgeManagerClassName = edgeProperty.getEdgeManagerDescriptor().getClassName(); edgeManager = RuntimeUtils.createClazzInstance(edgeManagerClassName); break; default: String message = "Unknown edge data movement type: " + edgeProperty.getDataMovementType(); throw new TezUncheckedException(message); } } public void initialize() { byte[] bb = null; if (edgeProperty.getDataMovementType() == DataMovementType.CUSTOM) { bb = edgeProperty.getEdgeManagerDescriptor().getUserPayload(); } edgeManagerContext = new EdgeManagerContextImpl(sourceVertex.getName(), destinationVertex.getName(), bb); edgeManager.initialize(edgeManagerContext); destinationMetaInfo = new EventMetaData(EventProducerConsumerType.INPUT, destinationVertex.getName(), sourceVertex.getName(), null); } public synchronized void setCustomEdgeManager(EdgeManagerDescriptor descriptor) { EdgeProperty modifiedEdgeProperty = new EdgeProperty(descriptor, edgeProperty.getDataSourceType(), edgeProperty.getSchedulingType(), edgeProperty.getEdgeSource(), edgeProperty.getEdgeDestination()); this.edgeProperty = modifiedEdgeProperty; createEdgeManager(); initialize(); } public EdgeProperty getEdgeProperty() { return this.edgeProperty; } public EdgeManager getEdgeManager() { return this.edgeManager; } public void setSourceVertex(Vertex sourceVertex) { if (this.sourceVertex != null && this.sourceVertex != sourceVertex) { throw new TezUncheckedException("Source vertex exists: " + sourceVertex.getName()); } this.sourceVertex = sourceVertex; } public void setDestinationVertex(Vertex destinationVertex) { if (this.destinationVertex != null && this.destinationVertex != destinationVertex) { throw new TezUncheckedException("Destination vertex exists: " + destinationVertex.getName()); } this.destinationVertex = destinationVertex; } public InputSpec getDestinationSpec(int destinationTaskIndex) { return new InputSpec(sourceVertex.getName(), edgeProperty.getEdgeDestination(), edgeManager.getNumDestinationTaskPhysicalInputs(sourceVertex.getTotalTasks(), destinationTaskIndex)); } public OutputSpec getSourceSpec(int sourceTaskIndex) { return new OutputSpec(destinationVertex.getName(), edgeProperty.getEdgeSource(), edgeManager.getNumSourceTaskPhysicalOutputs( destinationVertex.getTotalTasks(), sourceTaskIndex)); } public void startEventBuffering() { bufferEvents.set(true); } public void stopEventBuffering() { // assume only 1 entity will start and stop event buffering bufferEvents.set(false); for(TezEvent event : destinationEventBuffer) { sendTezEventToDestinationTasks(event); } destinationEventBuffer.clear(); for(TezEvent event : sourceEventBuffer) { sendTezEventToSourceTasks(event); } sourceEventBuffer.clear(); } @SuppressWarnings("unchecked") public void sendTezEventToSourceTasks(TezEvent tezEvent) { if (!bufferEvents.get()) { switch (tezEvent.getEventType()) { case INPUT_READ_ERROR_EVENT: InputReadErrorEvent event = (InputReadErrorEvent) tezEvent.getEvent(); TezTaskAttemptID destAttemptId = tezEvent.getSourceInfo() .getTaskAttemptID(); int destTaskIndex = destAttemptId.getTaskID().getId(); int srcTaskIndex = edgeManager.routeInputErrorEventToSource(event, destTaskIndex); int numConsumers = edgeManager.getNumDestinationConsumerTasks( srcTaskIndex, destinationVertex.getTotalTasks()); Task srcTask = sourceVertex.getTask(srcTaskIndex); if (srcTask == null) { throw new TezUncheckedException("Unexpected null task." + " sourceVertex=" + sourceVertex.getVertexId() + " srcIndex = " + srcTaskIndex + " destAttemptId=" + destAttemptId + " destIndex=" + destTaskIndex + " edgeManager=" + edgeManager.getClass().getName()); } TezTaskID srcTaskId = srcTask.getTaskId(); int taskAttemptIndex = event.getVersion(); TezTaskAttemptID srcTaskAttemptId = TezTaskAttemptID.getInstance(srcTaskId, taskAttemptIndex); eventHandler.handle(new TaskAttemptEventOutputFailed(srcTaskAttemptId, tezEvent, numConsumers)); break; default: throw new TezUncheckedException("Unhandled tez event type: " + tezEvent.getEventType()); } } else { sourceEventBuffer.add(tezEvent); } } private void handleCompositeDataMovementEvent(TezEvent tezEvent) { CompositeDataMovementEvent compEvent = (CompositeDataMovementEvent) tezEvent.getEvent(); EventMetaData srcInfo = tezEvent.getSourceInfo(); for (DataMovementEvent dmEvent : compEvent.getEvents()) { TezEvent newEvent = new TezEvent(dmEvent, srcInfo); sendTezEventToDestinationTasks(newEvent); } } void sendDmEventOrIfEventToTasks(TezEvent tezEvent, int srcTaskIndex, boolean isDataMovementEvent, Map<Integer, List<Integer>> ifInputIndicesToTaskIndices) { int num = 0; Event event = tezEvent.getEvent(); for (Map.Entry<Integer, List<Integer>> entry : ifInputIndicesToTaskIndices.entrySet()) { ++num; TezEvent tezEventToSend = null; if (num == ifInputIndicesToTaskIndices.size()) { if (isDataMovementEvent) { ((DataMovementEvent) event).setTargetIndex(entry.getKey().intValue()); } else { ((InputFailedEvent) event).setTargetIndex(entry.getKey().intValue()); } tezEventToSend = tezEvent; } else { Event e; if (isDataMovementEvent) { DataMovementEvent dmEvent = (DataMovementEvent) event; e = new DataMovementEvent(dmEvent.getSourceIndex(), entry.getKey().intValue(), dmEvent.getVersion(), dmEvent.getUserPayload()); } else { InputFailedEvent ifEvent = ((InputFailedEvent) event); e = new InputFailedEvent(entry.getKey().intValue(), ifEvent.getVersion()); } tezEventToSend = new TezEvent(e, tezEvent.getSourceInfo()); } tezEventToSend.setDestinationInfo(destinationMetaInfo); for(Integer destTaskIndex : entry.getValue()) { Task destTask = destinationVertex.getTask(destTaskIndex); if (destTask == null) { throw new TezUncheckedException("Unexpected null task." + " sourceVertex=" + sourceVertex.getVertexId() + " srcIndex = " + srcTaskIndex + " destAttemptId=" + destinationVertex.getVertexId() + " destIndex=" + destTaskIndex + " edgeManager=" + edgeManager.getClass().getName()); } TezTaskID destTaskId = destTask.getTaskId(); sendEventToTask(destTaskId, tezEventToSend); } } } public void sendTezEventToDestinationTasks(TezEvent tezEvent) { if (!bufferEvents.get()) { boolean isDataMovementEvent = true; switch (tezEvent.getEventType()) { case COMPOSITE_DATA_MOVEMENT_EVENT: handleCompositeDataMovementEvent(tezEvent); break; case INPUT_FAILED_EVENT: isDataMovementEvent = false; // fall through case DATA_MOVEMENT_EVENT: Map<Integer, List<Integer>> inputIndicesToTaskIndices = Maps .newHashMap(); TezTaskAttemptID srcAttemptId = tezEvent.getSourceInfo() .getTaskAttemptID(); int srcTaskIndex = srcAttemptId.getTaskID().getId(); if (isDataMovementEvent) { DataMovementEvent dmEvent = (DataMovementEvent)tezEvent.getEvent(); edgeManager.routeDataMovementEventToDestination(dmEvent, srcTaskIndex, destinationVertex.getTotalTasks(), inputIndicesToTaskIndices); } else { edgeManager.routeInputSourceTaskFailedEventToDestination(srcTaskIndex, destinationVertex.getTotalTasks(), inputIndicesToTaskIndices); } if (!inputIndicesToTaskIndices.isEmpty()) { sendDmEventOrIfEventToTasks(tezEvent, srcTaskIndex, isDataMovementEvent, inputIndicesToTaskIndices); } else { throw new TezUncheckedException("Event must be routed." + " sourceVertex=" + sourceVertex.getVertexId() + " srcIndex = " + srcTaskIndex + " destAttemptId=" + destinationVertex.getVertexId() + " edgeManager=" + edgeManager.getClass().getName() + " Event type=" + tezEvent.getEventType()); } break; default: throw new TezUncheckedException("Unhandled tez event type: " + tezEvent.getEventType()); } } else { destinationEventBuffer.add(tezEvent); } } @SuppressWarnings("unchecked") private void sendEventToTask(TezTaskID taskId, TezEvent tezEvent) { eventHandler.handle(new TaskEventAddTezEvent(taskId, tezEvent)); } public String getSourceVertexName() { return this.sourceVertex.getName(); } public String getDestinationVertexName() { return this.destinationVertex.getName(); } }
trumank/DRG-Mods
Source/FSD/Private/PendingLatentActionLibrary.cpp
<filename>Source/FSD/Private/PendingLatentActionLibrary.cpp #include "PendingLatentActionLibrary.h" class UObject; void UPendingLatentActionLibrary::WaitOneFrame(UObject* WorldContextObject, FLatentActionInfo LatentInfo) { } UPendingLatentActionLibrary::UPendingLatentActionLibrary() { }
rusucosmin/Cplusplus
Camion/main.cpp
#include <fstream> #include <vector> #define x first #define y second using namespace std; const int MAXN = 602; vector<int> G[MAXN]; int N, M, K, C; ifstream cin("camion.in"); ofstream cout("camion.out"); inline void Afisare() { cout << "\nVector:\n"; for(int i = 1 ; i <= N ; ++ i) { for(vector<int> :: iterator it = G[i].begin() ; it != G[i].end(); ++ it) cout << *it << " "; cout << "\n"; } } int main() { cin >> N >> M >> K >> C; for(int i = 1 ; i <= N ; ++ i) for(int j = 1 ; j <= M ; ++ j) G[i].push_back(j); for(int i = 1 ; i <= K ; ++ i) { pair<int, int> st, fn; // Afisare(); cin >> st.x >> st.y >> fn.x >> fn.y; for(int x = st.x ; x <= fn.x ; ++ x) for(int y = st.y ; y <= fn.y ; ++ y) if(G[x].size() >= st.y) G[x].erase(G[x].begin() + st.y - 1); } for(int i = 1 ; i <= N ; ++ i) if(G[i].size() >= C) cout << G[i][C-1] << '\n'; else cout << "0\n"; return 0; }
malord/prime
XMLNodeWriter.h
<gh_stars>0 // Copyright 2000-2021 <NAME> #ifndef PRIME_XMLNODEWRITER_H #define PRIME_XMLNODEWRITER_H #include "XMLNode.h" #include "XMLWriter.h" namespace Prime { /// Writes a hierarchy of XML nodes to a file. class PRIME_PUBLIC XMLNodeWriter { public: XMLNodeWriter(); enum { defaultBufferSize = PRIME_FILE_BUFFER_SIZE }; class PRIME_PUBLIC Options { public: Options() : _xmlProcessingInstruction(true) , _encoding("UTF-8") , _assumeText(true) , _ignoreNameCase(false) , _html(false) { } Options& setXMLProcessingInstruction(bool value) { _xmlProcessingInstruction = value; return *this; } bool getXMLProcessingInstruction() const { return _xmlProcessingInstruction; } Options& setEncoding(std::string value) { _encoding.swap(value); return *this; } const std::string& getEncoding() const { return _encoding; } /// By default true, so all nodes are assumed to contain text and therefore cannot be indented etc. as /// that would insert extra whitespace. Works alongside the text node filters set by addTextNodeFilters(). Options& setAssumeText(bool value) { _assumeText = value; return *this; } bool getAssumeText() const { return _assumeText; } // In HTML mode, self-closing tags are only used for tags which are supposed to be empty in HTML // (as returned by GetHTMLEmptyElements()). Options& setHTML(bool value) { _html = value; return *this; } bool getHTML() const { return _html; } Options& setIgnoreNameCase(bool value) { _ignoreNameCase = value; return *this; } bool getIgnoreNameCase() const { return _ignoreNameCase; } private: bool _xmlProcessingInstruction; std::string _encoding; bool _assumeText; bool _ignoreNameCase; bool _html; }; /// Assign the Stream and Log to write to. If buffer π null, allocate a buffer of the specified size, /// otherwise use the supplied memory for the buffer. XMLNodeWriter(const Options& options, Stream* stream, Log* log, size_t bufferSize = defaultBufferSize, void* buffer = NULL); ~XMLNodeWriter(); void init(const Options& options, Stream* stream, Log* log, size_t bufferSize = defaultBufferSize, void* buffer = NULL); Log* getLog() const { return _writer.getLog(); } /// Add a bunch of names (all in the same namespace) to the list of nodes to filter from the text/non-text /// lists. So if you call setAssumeText(false), these will be the text nodes, if you call /// setAssumeText(true) (the default) then these will be the non-text nodes. void addTextNodeFilters(const char* const* names, size_t count, const char* namespaceForAll); bool isTextNode(StringView name, StringView nspace) const; /// In HTML mode, returns true for all element names returned by GetHTMLEmptyElements() and false for all /// others. When not in HTML mode, returns true. bool allowSelfClosing(StringView name) const; bool writeDocument(const XMLNode* node, bool childrenOnly); XMLWriter& getWriter() { return _writer; } private: static bool equalNamespaces(StringView a, StringView b); bool equalNames(StringView a, StringView b) const; bool write(const XMLNode* node); bool writeChildren(const XMLNode* node, bool includingAttributes); XMLWriter _writer; Options _options; struct NameAndNamespace { const char* name; const char* nspace; }; std::vector<NameAndNamespace> _names; }; } #endif
Lando-L/ocd-detection
ocddetection/learning/federated/simulation/training/__init__.py
<gh_stars>1-10 from collections import namedtuple from functools import partial, reduce import os from typing import Callable, Dict, List, Text, Tuple import matplotlib.pylab as plt import mlflow import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf import tensorflow_federated as tff from ocddetection import metrics from ocddetection.data import preprocessing from ocddetection.types import Metrics, ServerState, ClientState, FederatedDataset from ocddetection.learning.federated.simulation import common Config = namedtuple( 'Config', ['path', 'output', 'rounds', 'clients_per_round', 'checkpoint_rate', 'learning_rate', 'epochs', 'batch_size', 'window_size', 'pos_weights', 'hidden_size', 'dropout'] ) def __load_data(path, epochs, window_size, batch_size) -> Tuple[FederatedDataset, FederatedDataset, FederatedDataset]: files = pd.Series( [os.path.join(path, f'S{subject}-ADL{run}-AUGMENTED.csv') for subject in range(1, 5) for run in range(1, 6)], index=pd.MultiIndex.from_product([list(range(1, 5)), list(range(1, 6))]), name='path' ) train_files, val_files, test_files = preprocessing.split( files, validation=[], test=[(subject, 5) for subject in range(1, 5)] ) train = preprocessing.to_federated(train_files, epochs, window_size, batch_size) val = preprocessing.to_federated(val_files, 1, window_size, batch_size) test = preprocessing.to_federated(test_files, 1, window_size, batch_size) return train, val, test def __training_metrics_fn() -> List[tf.keras.metrics.Metric]: return [ metrics.SigmoidDecorator(tf.keras.metrics.AUC(curve='PR'), name='auc') ] def __validation_metrics_fn() -> List[tf.keras.metrics.Metric]: thresholds = list(np.linspace(0, 1, 200, endpoint=False)) return [ metrics.SigmoidDecorator(tf.keras.metrics.AUC(curve='PR'), name='auc'), metrics.SigmoidDecorator(tf.keras.metrics.Precision(thresholds=thresholds), name='precision'), metrics.SigmoidDecorator(tf.keras.metrics.Recall(thresholds=thresholds), name='recall'), metrics.SigmoidDecorator(tf.keras.metrics.BinaryAccuracy(), name='accuracy'), ] def __client_optimizer_fn(learning_rate: float) -> tf.keras.optimizers.Optimizer: return tf.keras.optimizers.SGD(learning_rate) def __server_optimizer_fn() -> tf.keras.optimizers.Optimizer: return tf.keras.optimizers.SGD(1.0, momentum=0.9) def __train_step( server_state: ServerState, client_states: Dict[int, ClientState], dataset: FederatedDataset, clients_per_round: int, client_idx2id: Dict[int, int], training_fn: Callable[[ServerState, List[tf.data.Dataset], List[ClientState]], Tuple[ServerState, Metrics, List[ClientState]]] ) -> Tuple[ServerState, Metrics, Dict[int, ClientState]]: sampled_clients = common.sample_clients(dataset, clients_per_round) sampled_data = [dataset.data[client] for client in sampled_clients] sampled_client_states = [client_states[client] for client in sampled_clients] next_state, metrics, updated_client_states = training_fn(server_state, sampled_data, sampled_client_states) next_client_states = { **client_states, **{ client_idx2id[client.client_index.numpy()]: client for client in updated_client_states } } return next_state, metrics, next_client_states def __validation_step( weights: tff.learning.ModelWeights, client_states: Dict[int, ClientState], dataset: FederatedDataset, validation_fn: Callable[[tff.learning.ModelWeights, List[tf.data.Dataset], List[ClientState]], Metrics] ) -> Metrics: return common.update_test_metrics( validation_fn( weights, [dataset.data[client] for client in dataset.clients], [client_states[client] for client in dataset.clients] ) ) def __fit( state: Tuple[ServerState, Dict[int, ClientState]], round_num: int, checkpoint_rate: int, checkpoint_manager: tff.simulation.FileCheckpointManager, train_step_fn: Callable[[ServerState, Dict[int, ClientState]], Tuple[ServerState, Metrics, Dict[int, ClientState]]], validation_step_fn: Callable[[tff.learning.ModelWeights, Dict[int, ClientState]], Metrics] ) -> Tuple[ServerState, Dict[int, ClientState]]: next_state, metrics, next_client_states = train_step_fn(state[0], state[1]) mlflow.log_metrics(metrics, step=round_num) test_metrics = validation_step_fn(next_state.model, next_client_states) mlflow.log_metrics(test_metrics, step=round_num) if round_num % checkpoint_rate == 0: checkpoint_manager.save_checkpoint([next_state, next_client_states], round_num) return next_state, next_client_states def __evaluate( weights: tff.learning.ModelWeights, client_states: Dict[int, ClientState], dataset: FederatedDataset, evaluation_fn: Callable[[tff.learning.ModelWeights, List[tf.data.Dataset], List[ClientState]], Tuple[tf.Tensor, Dict[Text, tf.Tensor], Dict[Text, tf.Tensor]]] ) -> None: confusion_matrix, aggregated_metrics, client_metrics = evaluation_fn( weights, [dataset.data[client] for client in dataset.clients], [client_states[client] for client in dataset.clients] ) # Confusion Matrix fig, ax = plt.subplots(figsize=(16, 8)) sns.heatmap(confusion_matrix, annot=True, fmt='d', cmap=sns.color_palette("Blues"), ax=ax) ax.set_xlabel('Predicted') ax.set_ylabel('Ground Truth') mlflow.log_figure(fig, f'confusion_matrix.png') plt.close(fig) # Precision Recall fig, ax = plt.subplots(figsize=(16, 8)) sns.lineplot(x=aggregated_metrics['recall'], y=aggregated_metrics['precision'], ax=ax) ax.set_xlabel('Recall') ax.set_xlim(0., 1.) ax.set_ylabel('Precision') ax.set_ylim(0., 1.) mlflow.log_figure(fig, f'precision_recall.png') plt.close(fig) # Client Metrics auc = metrics.SigmoidDecorator(tf.keras.metrics.AUC(curve='PR'), name='auc') accuracy = metrics.SigmoidDecorator(tf.keras.metrics.BinaryAccuracy(), name='accuracy') for client, metric in zip(client_states.keys(), iter(client_metrics)): tf.nest.map_structure(lambda v, t: v.assign(t), auc.variables, list(metric['auc'])) tf.nest.map_structure(lambda v, t: v.assign(t), accuracy.variables, list(metric['accuracy'])) mlflow.log_metric(f'client_{client}_val_auc', auc.result().numpy()) mlflow.log_metric(f'client_{client}_val_acc', accuracy.result().numpy()) def run( experiment_name: str, run_name: str, setup_fn: Callable[[int, int, float, Dict[int, int], Callable, Callable, Callable, Callable], Tuple[Dict[int, ClientState], Callable, Callable, Callable]], config: Config ) -> None: mlflow.set_experiment(experiment_name) client_state_fn, iterator, validator, evaluator = setup_fn( config.window_size, config.hidden_size, config.dropout, __training_metrics_fn, __validation_metrics_fn, partial(__client_optimizer_fn, learning_rate=config.learning_rate), __server_optimizer_fn ) train, _, test = __load_data(config.path, config.epochs, config.window_size, config.batch_size) checkpoint_manager = tff.simulation.FileCheckpointManager(config.output) client_idx2id = list(sorted(train.clients.union(test.clients))) client_states = { i: client_state_fn(idx, pos_weight) for idx, (i, pos_weight) in enumerate(zip(client_idx2id, config.pos_weights)) } train_step = partial( __train_step, dataset=train, clients_per_round=config.clients_per_round, client_idx2id=client_idx2id, training_fn=iterator.next ) validation_step = partial( __validation_step, dataset=test, validation_fn=validator ) fitting_fn = partial( __fit, checkpoint_rate=config.checkpoint_rate, checkpoint_manager=checkpoint_manager, train_step_fn=train_step, validation_step_fn=validation_step ) evaluation_fn = partial( __evaluate, dataset=test, evaluation_fn=evaluator ) with mlflow.start_run(run_name=run_name): mlflow.log_params(config._asdict()) server_state, client_states = reduce( fitting_fn, range(1, config.rounds + 1), (iterator.initialize(), client_states) ) evaluation_fn(server_state.model, client_states)
dolittle/Legacy_Studio
Source/Master/Web/doLittle/client/views/LoadAndRenderView.js
/*--------------------------------------------------------------------------------------------- * Copyright (c) 2008-2017 doLittle. All rights reserved. * Licensed under the MIT License. See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Task } from "doLittle/tasks/Task"; import { ViewLoader } from "./ViewLoader"; import { ViewPath } from "./ViewPath"; const _viewLoader = new WeakMap(); const _viewPath = new WeakMap(); /** * Represents a {Task} that is capable of loading views */ export class LoadAndRenderView extends Task { /** * Initializes a new instance of {LoadAndRenderView} * @param {ViewLoader} viewLoader The loader for loading views * @param {ViewPath} viewPath The path of the view to load */ constructor(viewLoader, viewPath) { super(); _viewLoader.set(this, viewLoader); _viewPath.set(this, viewPath); } /** @inheritdoc */ execute(taskContext) { _viewLoader.get(this).load(_viewPath.get(this)).then(viewDefinition => { taskContext.values.viewDefinition = viewDefinition; }); } }
rongrongrr/main
src/main/java/seedu/guilttrip/logic/parser/GuiltTripParser.java
package seedu.guilttrip.logic.parser; import static seedu.guilttrip.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.guilttrip.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import static seedu.guilttrip.logic.parser.ParserUtil.mapOfMessageUsages; import static seedu.guilttrip.logic.parser.ParserUtil.mapOfOneLinerDescs; import static seedu.guilttrip.logic.parser.ParserUtil.setOfCommandWords; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.guilttrip.logic.commands.ClearCommand; import seedu.guilttrip.logic.commands.Command; import seedu.guilttrip.logic.commands.ExitCommand; import seedu.guilttrip.logic.commands.HelpCommand; import seedu.guilttrip.logic.commands.HistoryCommand; import seedu.guilttrip.logic.commands.ListBudgetCommand; import seedu.guilttrip.logic.commands.ListCategoriesCommand; import seedu.guilttrip.logic.commands.ListCommand; import seedu.guilttrip.logic.commands.ListWishCommand; import seedu.guilttrip.logic.commands.RedoCommand; import seedu.guilttrip.logic.commands.SetCurrDateCommand; import seedu.guilttrip.logic.commands.UndoCommand; import seedu.guilttrip.logic.commands.addcommands.AddAutoExpenseCommand; import seedu.guilttrip.logic.commands.addcommands.AddBudgetCommand; import seedu.guilttrip.logic.commands.addcommands.AddCategoryCommand; import seedu.guilttrip.logic.commands.addcommands.AddExpenseCommand; import seedu.guilttrip.logic.commands.addcommands.AddIncomeCommand; import seedu.guilttrip.logic.commands.addcommands.AddWishCommand; import seedu.guilttrip.logic.commands.deletecommands.DeleteAutoExpenseCommand; import seedu.guilttrip.logic.commands.deletecommands.DeleteBudgetCommand; import seedu.guilttrip.logic.commands.deletecommands.DeleteCategoryCommand; import seedu.guilttrip.logic.commands.deletecommands.DeleteExpenseCommand; import seedu.guilttrip.logic.commands.deletecommands.DeleteIncomeCommand; import seedu.guilttrip.logic.commands.deletecommands.DeleteWishCommand; import seedu.guilttrip.logic.commands.editcommands.EditAutoExpenseCommand; import seedu.guilttrip.logic.commands.editcommands.EditBudgetCommand; import seedu.guilttrip.logic.commands.editcommands.EditCategoryCommand; import seedu.guilttrip.logic.commands.editcommands.EditExpenseCommand; import seedu.guilttrip.logic.commands.editcommands.EditIncomeCommand; import seedu.guilttrip.logic.commands.editcommands.EditWishCommand; import seedu.guilttrip.logic.commands.findcommands.FindAutoExpenseCommand; import seedu.guilttrip.logic.commands.findcommands.FindBudgetCommand; import seedu.guilttrip.logic.commands.findcommands.FindExpenseCommand; import seedu.guilttrip.logic.commands.findcommands.FindIncomeCommand; import seedu.guilttrip.logic.commands.findcommands.FindWishCommand; import seedu.guilttrip.logic.commands.remindercommands.AddGeneralReminderCommand; import seedu.guilttrip.logic.commands.remindercommands.DeleteReminderCommand; import seedu.guilttrip.logic.commands.remindercommands.EditReminderCommand; import seedu.guilttrip.logic.commands.remindercommands.ListRemindersCommand; import seedu.guilttrip.logic.commands.remindercommands.RemoveConditionFromReminderCommand; import seedu.guilttrip.logic.commands.remindercommands.SelectReminderCommand; import seedu.guilttrip.logic.commands.remindercommands.SetReminderCommand; import seedu.guilttrip.logic.commands.sortcommands.SortAutoExpenseCommand; import seedu.guilttrip.logic.commands.sortcommands.SortBudgetCommand; import seedu.guilttrip.logic.commands.sortcommands.SortExpenseCommand; import seedu.guilttrip.logic.commands.sortcommands.SortIncomeCommand; import seedu.guilttrip.logic.commands.sortcommands.SortWishCommand; import seedu.guilttrip.logic.commands.statisticscommands.ViewBarChartCommand; import seedu.guilttrip.logic.commands.statisticscommands.ViewEntryCommand; import seedu.guilttrip.logic.commands.statisticscommands.ViewPieChartCommand; import seedu.guilttrip.logic.commands.statisticscommands.ViewTableCommand; import seedu.guilttrip.logic.commands.uicommands.ChangeFontCommand; import seedu.guilttrip.logic.commands.uicommands.SetDarkThemeCommand; import seedu.guilttrip.logic.commands.uicommands.SetLightThemeCommand; import seedu.guilttrip.logic.commands.uicommands.TogglePanelCommand; import seedu.guilttrip.logic.parser.addcommandparsers.AddAutoExpenseCommandParser; import seedu.guilttrip.logic.parser.addcommandparsers.AddBudgetCommandParser; import seedu.guilttrip.logic.parser.addcommandparsers.AddCategoryCommandParser; import seedu.guilttrip.logic.parser.addcommandparsers.AddExpenseCommandParser; import seedu.guilttrip.logic.parser.addcommandparsers.AddIncomeCommandParser; import seedu.guilttrip.logic.parser.addcommandparsers.AddWishCommandParser; import seedu.guilttrip.logic.parser.deletecommandparsers.DeleteAutoExpenseCommandParser; import seedu.guilttrip.logic.parser.deletecommandparsers.DeleteBudgetCommandParser; import seedu.guilttrip.logic.parser.deletecommandparsers.DeleteCategoryCommandParser; import seedu.guilttrip.logic.parser.deletecommandparsers.DeleteExpenseCommandParser; import seedu.guilttrip.logic.parser.deletecommandparsers.DeleteIncomeCommandParser; import seedu.guilttrip.logic.parser.deletecommandparsers.DeleteWishCommandParser; import seedu.guilttrip.logic.parser.editcommandparsers.EditAutoExpenseCommandParser; import seedu.guilttrip.logic.parser.editcommandparsers.EditBudgetCommandParser; import seedu.guilttrip.logic.parser.editcommandparsers.EditCategoryCommandParser; import seedu.guilttrip.logic.parser.editcommandparsers.EditExpenseCommandParser; import seedu.guilttrip.logic.parser.editcommandparsers.EditIncomeCommandParser; import seedu.guilttrip.logic.parser.editcommandparsers.EditWishCommandParser; import seedu.guilttrip.logic.parser.exceptions.ParseException; import seedu.guilttrip.logic.parser.findcommandparsers.FindAutoExpenseCommandParser; import seedu.guilttrip.logic.parser.findcommandparsers.FindBudgetCommandParser; import seedu.guilttrip.logic.parser.findcommandparsers.FindExpenseCommandParser; import seedu.guilttrip.logic.parser.findcommandparsers.FindIncomeCommandParser; import seedu.guilttrip.logic.parser.findcommandparsers.FindWishCommandParser; import seedu.guilttrip.logic.parser.remindercommandparsers.AddGeneralReminderCommandParser; import seedu.guilttrip.logic.parser.remindercommandparsers.EditReminderCommandParser; import seedu.guilttrip.logic.parser.remindercommandparsers.RemoveConditionFromReminderCommandParser; import seedu.guilttrip.logic.parser.remindercommandparsers.SelectReminderCommandParser; import seedu.guilttrip.logic.parser.remindercommandparsers.SetReminderCommandParser; import seedu.guilttrip.logic.parser.sortcommandparsers.SortAutoExpenseCommandParser; import seedu.guilttrip.logic.parser.sortcommandparsers.SortBudgetCommandParser; import seedu.guilttrip.logic.parser.sortcommandparsers.SortExpenseCommandParser; import seedu.guilttrip.logic.parser.sortcommandparsers.SortIncomeCommandParser; import seedu.guilttrip.logic.parser.sortcommandparsers.SortWishCommandParser; import seedu.guilttrip.logic.parser.statscommandparsers.ViewBarChartCommandParser; import seedu.guilttrip.logic.parser.statscommandparsers.ViewPieChartCommandParser; import seedu.guilttrip.logic.parser.statscommandparsers.ViewTableCommandParser; import seedu.guilttrip.logic.parser.uicommandparsers.ChangeFontCommandParser; import seedu.guilttrip.logic.parser.uicommandparsers.TogglePanelCommandParser; /** * Parses user input. */ public class GuiltTripParser { public static final Set<String> COMMANDS_SET = setOfCommandWords(); public static final Map<String, String> ONE_LINER_DESC_MAP = mapOfOneLinerDescs(); public static final Map<String, String> MESSAGE_USAGE_MAP = mapOfMessageUsages(); /** * Used for initial separation of command word and args. */ public static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input * @throws ParseException if the user input does not conform the expected format */ public Command parseCommand(String userInput) throws ParseException, IllegalArgumentException { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord) { case AddExpenseCommand.COMMAND_WORD: // Fallthrough case AddExpenseCommand.COMMAND_WORD_SHORT: return new AddExpenseCommandParser().parse(arguments); case SetCurrDateCommand.COMMAND_WORD: return new SetCurrDateCommandParser().parse(arguments); case AddIncomeCommand.COMMAND_WORD: return new AddIncomeCommandParser().parse(arguments); case AddBudgetCommand.COMMAND_WORD: return new AddBudgetCommandParser().parse(arguments); case AddCategoryCommand.COMMAND_WORD: return new AddCategoryCommandParser().parse(arguments); case AddWishCommand.COMMAND_WORD: return new AddWishCommandParser().parse(arguments); case EditExpenseCommand.COMMAND_WORD: // Fallthrough case EditExpenseCommand.COMMAND_WORD_SHORT: return new EditExpenseCommandParser().parse(arguments); case EditIncomeCommand.COMMAND_WORD: return new EditIncomeCommandParser().parse(arguments); case EditCategoryCommand.COMMAND_WORD: return new EditCategoryCommandParser().parse(arguments); case EditWishCommand.COMMAND_WORD: return new EditWishCommandParser().parse(arguments); case EditBudgetCommand.COMMAND_WORD: return new EditBudgetCommandParser().parse(arguments); case DeleteExpenseCommand.COMMAND_WORD: // Fallthrough case DeleteExpenseCommand.COMMAND_WORD_SHORT: return new DeleteExpenseCommandParser().parse(arguments); case DeleteIncomeCommand.COMMAND_WORD: return new DeleteIncomeCommandParser().parse(arguments); case DeleteCategoryCommand.COMMAND_WORD: return new DeleteCategoryCommandParser().parse(arguments); case DeleteWishCommand.COMMAND_WORD: return new DeleteWishCommandParser().parse(arguments); case DeleteBudgetCommand.COMMAND_WORD: return new DeleteBudgetCommandParser().parse(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case FindExpenseCommand.COMMAND_WORD: return new FindExpenseCommandParser().parse(arguments); case FindAutoExpenseCommand.COMMAND_WORD: return new FindAutoExpenseCommandParser().parse(arguments); case FindIncomeCommand.COMMAND_WORD: return new FindIncomeCommandParser().parse(arguments); case FindWishCommand.COMMAND_WORD: return new FindWishCommandParser().parse(arguments); case FindBudgetCommand.COMMAND_WORD: return new FindBudgetCommandParser().parse(arguments); case ListCommand.COMMAND_WORD: return new ListCommand(); case ListCategoriesCommand.COMMAND_WORD: return new ListCategoriesCommand(); case ListWishCommand.COMMAND_WORD: return new ListWishCommand(); case ListBudgetCommand.COMMAND_WORD: return new ListBudgetCommand(); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case SortExpenseCommand.COMMAND_WORD: return new SortExpenseCommandParser().parse(arguments); case SortIncomeCommand.COMMAND_WORD: return new SortIncomeCommandParser().parse(arguments); case SortBudgetCommand.COMMAND_WORD: return new SortBudgetCommandParser().parse(arguments); case SortAutoExpenseCommand.COMMAND_WORD: return new SortAutoExpenseCommandParser().parse(arguments); case SortWishCommand.COMMAND_WORD: return new SortWishCommandParser().parse(arguments); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case SelectReminderCommand.COMMAND_WORD: return new SelectReminderCommandParser().parse(arguments); case AddGeneralReminderCommand.COMMAND_WORD: return new AddGeneralReminderCommandParser().parse(arguments); case SetReminderCommand.COMMAND_WORD: return new SetReminderCommandParser().parse(arguments); case EditReminderCommand.COMMAND_WORD: return new EditReminderCommandParser().parse(arguments); case DeleteReminderCommand.COMMAND_WORD: return new DeleteReminderCommand(); case ListRemindersCommand.COMMAND_WORD: return new ListRemindersCommand(); case RemoveConditionFromReminderCommand.COMMAND_WORD: return new RemoveConditionFromReminderCommandParser().parse(arguments); case AddAutoExpenseCommand.COMMAND_WORD: return new AddAutoExpenseCommandParser().parse(arguments); case EditAutoExpenseCommand.COMMAND_WORD: return new EditAutoExpenseCommandParser().parse(arguments); case DeleteAutoExpenseCommand.COMMAND_WORD: return new DeleteAutoExpenseCommandParser().parse(arguments); case ViewBarChartCommand.COMMAND_WORD: return new ViewBarChartCommandParser().parse(arguments); case ViewTableCommand.COMMAND_WORD: return new ViewTableCommandParser().parse(arguments); case ViewPieChartCommand.COMMAND_WORD: return new ViewPieChartCommandParser().parse(arguments); case ViewEntryCommand.COMMAND_WORD: return new ViewEntryCommand(); case TogglePanelCommand.COMMAND_WORD: return new TogglePanelCommandParser().parse(arguments); case UndoCommand.COMMAND_WORD: return new UndoCommandParser().parse(arguments); case RedoCommand.COMMAND_WORD: return new RedoCommandParser().parse(arguments); case HistoryCommand.COMMAND_WORD: return new HistoryCommand(); case ChangeFontCommand.COMMAND_WORD: return new ChangeFontCommandParser().parse(arguments); case SetLightThemeCommand.COMMAND_WORD: return new SetLightThemeCommand(); case SetDarkThemeCommand.COMMAND_WORD: return new SetDarkThemeCommand(); default: throw new ParseException(MESSAGE_UNKNOWN_COMMAND); } } }
saimonmoore/xorodia
web/src/policies/PersistSingerPolicy/PersistSingerPolicy.js
<filename>web/src/policies/PersistSingerPolicy/PersistSingerPolicy.js import React, { useContext } from 'react' import { useQuery, useMutation } from '@redwoodjs/web' import { Link, routes, navigate } from '@redwoodjs/router' import { AuthContext } from 'src/contexts/AuthContext' import Loading from 'src/components/Loading' const QUERY = gql` query FIND_USER_SINGER($id: Int!) { singer: userSinger(id: $id) { id } } ` const CREATE_SINGER_MUTATION = gql` mutation CreateSingerMutation($input: SingerInput!) { createSinger(input: $input) { id } } ` const PersistSinger = ({ singer, currentUser }) => { const [ createSinger, { loading: isCreatingSinger, error: singerCreationError }, ] = useMutation(CREATE_SINGER_MUTATION, { onCompleted: (data) => { // TODO: Dispatch notification console.log('[PersistSinger] associated this user to singer: ', data) }, }) if (isCreatingSinger) return <Loading /> if (singerCreationError) { console.log('[PersistedSingerPolicy] error: ', singerCreationError) } console.log('[PersistedSingerPolicy] got user: ', currentUser) if (!singer) { const singerInput = { user: currentUser.id, defaultPart: 'FUU', } createSinger({ variables: { input: singerInput } }) } } const PersistSingerPolicy = ({ children }) => { const { currentUser } = useContext(AuthContext) const { data, loading, error } = useQuery(QUERY, { variables: { id: currentUser.id }, }) if (loading) return <Loading /> if (error) { console.log('[PersistSingerPolicy] BOOM: ', error) } const { singer } = data return ( <PersistSinger singer={singer} currentUser={currentUser}> {children} </PersistSinger> ) } export default PersistSingerPolicy
ibaned/seacas
docs/apr_html/search/variables_7.js
var searchData= [ ['hashsize',['HASHSIZE',['../namespaceanonymous__namespace_02apr__aprepro_8cc_03.html#a3ccb605d7abf7abff225f663dc92d0e3',1,'anonymous_namespace{apr_aprepro.cc}']]], ['hist_5fstart',['hist_start',['../apr__scanner_8cc.html#a252fb105ec4adf6ab62197f9e7c30d52',1,'apr_scanner.cc']]], ['history',['history',['../classSEAMS_1_1Aprepro.html#a337c8c2410d7ad5ddef1eb6593a19132',1,'SEAMS::Aprepro']]], ['history_5fstring',['history_string',['../apr__scanner_8cc.html#a748e6be0ac0614a20c58899ed02aaf8a',1,'apr_scanner.cc']]] ];
valachedi/otus_java_2020_03
hw04-gc/src/main/java/hw04/components/BenchmarkOverfillMemoryMBean.java
package hw04.components; public interface BenchmarkOverfillMemoryMBean { public int getNumberOfElementsToAdd(); public void setNumberOfElementsToAdd(int number); }
zhangkn/iOS14Header
System/Library/Frameworks/PhotosUI.framework/PUMutableReviewScreenBarsModel.h
/* * This header is generated by classdump-dyld 1.0 * on Monday, September 28, 2020 at 5:54:54 PM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/Frameworks/PhotosUI.framework/PhotosUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @class NSDictionary, UIView; @protocol PUMutableReviewScreenBarsModel @property (nonatomic,copy) NSDictionary * availableItemsByIdentifier; @property (nonatomic,retain) UIView * accessoryView; @property (assign,nonatomic) BOOL shouldPlaceScrubberInScrubberBar; @property (assign,getter=isTransitioningWithCamera,nonatomic) BOOL transitioningWithCamera; @property (assign,nonatomic) BOOL useVerticalControlLayout; @property (assign,nonatomic) CGPoint controlCenterAlignmentPoint; @required -(BOOL)isTransitioningWithCamera; -(UIView *)accessoryView; -(BOOL)shouldPlaceScrubberInScrubberBar; -(void)setAccessoryView:(id)arg1; -(void)setAvailableItemsByIdentifier:(id)arg1; -(void)setShouldPlaceScrubberInScrubberBar:(BOOL)arg1; -(void)setUseVerticalControlLayout:(BOOL)arg1; -(void)setControlCenterAlignmentPoint:(CGPoint)arg1 forceLayout:(BOOL)arg2; -(NSDictionary *)availableItemsByIdentifier; -(void)setTransitioningWithCamera:(BOOL)arg1; -(void)setControlCenterAlignmentPoint:(CGPoint)arg1; -(BOOL)useVerticalControlLayout; -(CGPoint)controlCenterAlignmentPoint; @end
aidtechnology/composer
packages/composer-runtime/lib/loggingservice.js
<filename>packages/composer-runtime/lib/loggingservice.js /* * 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. */ 'use strict'; const Service = require('./service'); /** * Base class representing the logging service provided by a {@link Container}. * @protected * @abstract * @memberof module:composer-runtime */ class LoggingService extends Service { /** Get the config (if possible) for the standard winston logger * @abstract */ getLoggerCfg() { throw new Error('abstract function called'); } /** * @abstract */ setLoggerCfg() { throw new Error('abstract function called'); } /** * @abstract */ initLogging(){ throw new Error('abstract function called'); } /** * @abstract */ callback(){ throw new Error('abstract function called'); } /** * @abstract * */ mapCfg(){ throw new Error('abstract function called'); } } module.exports = LoggingService;
ghost0224/jauth
jauth-soap/src/main/java/com/hp/security/jauth/soap/wss/WSSInterceptor.java
<reponame>ghost0224/jauth package com.hp.security.jauth.soap.wss; import java.util.Map; import java.util.Vector; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.stream.XMLStreamException; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.interceptor.Fault; import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor; import org.apache.ws.security.handler.RequestData; import com.hp.security.jauth.core.util.ContextHolder; public class WSSInterceptor extends WSS4JInInterceptor { public WSSInterceptor() { super(); } public WSSInterceptor(boolean ignore) { super(ignore); } public WSSInterceptor(Map<String, Object> properties) { super(properties); } @Override public void setIgnoreActions(boolean i) { super.setIgnoreActions(i); } @Override public Object getProperty(Object msgContext, String key) { return super.getProperty(msgContext, key); } @Override protected void computeAction(SoapMessage msg, RequestData reqData) { super.computeAction(msg, reqData); } @Override protected void doResults(SoapMessage msg, String actor, SOAPMessage doc, Vector wsResult) throws SOAPException, XMLStreamException { super.doResults(msg, actor, doc, wsResult); } @Override public void handleMessage(SoapMessage msg) throws Fault { if(ContextHolder.isPassed() == null || !ContextHolder.isPassed()) { super.handleMessage(msg); } } }
Snowgem/bitfrost-ts
ts_build/transaction/spenddescription.js
<reponame>Snowgem/bitfrost-ts "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SpendDescription = void 0; const _ = __importStar(require("lodash")); const preconditions_1 = __importDefault(require("../util/preconditions")); const bufferwriter_1 = require("../encoding/bufferwriter"); class SpendDescription { constructor(params) { this._fromObject = function (params) { return this; }; this.toObject = function toObject() { var obj = {}; return obj; }; this.toJSON = this.toObject; this.toBufferWriter = function (writer) { var i; if (!writer) { writer = new bufferwriter_1.BufferWriter(); } writer.write(this.cv); writer.write(this.anchor); writer.write(this.nullifier); writer.write(this.rk); writer.write(this.proof); writer.write(this.spendAuthSig); return writer; }; if (!(this instanceof SpendDescription)) { return new SpendDescription(params); } if (params) { return this._fromObject(params); } } } exports.SpendDescription = SpendDescription; SpendDescription.fromObject = function (obj) { preconditions_1.default.checkArgument(_.isObject(obj)); var spenddesc = new SpendDescription(); return spenddesc._fromObject(obj); }; SpendDescription.fromBufferReader = function (br) { var obj = new SpendDescription(); obj.cv = br.read(32); obj.anchor = br.read(32); obj.nullifier = br.read(32); obj.rk = br.read(32); obj.proof = br.read(48 + 96 + 48); obj.spendAuthSig = br.read(64); return obj; }; //# sourceMappingURL=spenddescription.js.map
SylvesterAbreu/sling
contrib/extensions/cache/api/src/main/java/org/apache/sling/commons/cache/api/CacheScope.java
<filename>contrib/extensions/cache/api/src/main/java/org/apache/sling/commons/cache/api/CacheScope.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.sling.commons.cache.api; /** * Defines the scope of the cache */ public enum CacheScope { /** * Bind the Cache to the request scope. */ REQUEST(), /** * Bind a cache to the Thread, forever. WARNING: use with extreme caution, * as any classes referenced in this type of cache will keep classloaders * open and result in memory leaks */ THREAD(), /** * Bind the cache to the instance, one per instance. */ INSTANCE(), /** * Make the cache bound to the instance, but accept cluster wide * invalidations. */ CLUSTERINVALIDATED(), /** * Replicate the cache over the whole cluster. */ CLUSTERREPLICATED(); }
BastianBlokland/volo
libs/rend/src/rvk/desc.c
<filename>libs/rend/src/rvk/desc.c #include "core_array.h" #include "core_bits.h" #include "core_diag.h" #include "core_search.h" #include "core_thread.h" #include "log_logger.h" #include "buffer_internal.h" #include "desc_internal.h" #include "image_internal.h" #include "mem_internal.h" #include "sampler_internal.h" // #define VOLO_RVK_DESC_LOGGING #define rvk_desc_sets_per_chunk 8 typedef struct { u32 metaHash; RvkDescMeta meta; VkDescriptorSetLayout vkLayout; } RvkDescLayout; struct sRvkDescChunk { RvkDescPool* pool; RvkDescChunk* next; VkDescriptorPool vkPool; VkDescriptorSet vkSets[rvk_desc_sets_per_chunk]; u8 freeSets[bits_to_bytes(rvk_desc_sets_per_chunk) + 1]; u32 metaHash; }; struct sRvkDescPool { VkDevice vkDev; VkAllocationCallbacks vkAlloc; ThreadMutex layoutLock; DynArray layouts; // RvkDescLayout[], kept sorted on the metaHash. ThreadMutex chunkLock; RvkDescChunk* chunkHead; RvkDescChunk* chunkTail; }; static u32 rvk_desc_meta_hash(const RvkDescMeta* meta) { return bits_hash_32(array_mem(meta->bindings)); } static i8 rvk_desc_compare_layout(const void* a, const void* b) { return compare_u32(field_ptr(a, RvkDescLayout, metaHash), field_ptr(b, RvkDescLayout, metaHash)); } static BitSet rvk_desc_chunk_mask(const RvkDescChunk* chunk) { return bitset_from_array(chunk->freeSets); } static VkDescriptorType rvk_desc_vktype(const RvkDescKind kind) { switch (kind) { case RvkDescKind_None: break; case RvkDescKind_CombinedImageSampler: return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; case RvkDescKind_UniformBuffer: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; case RvkDescKind_UniformBufferDynamic: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; case RvkDescKind_StorageBuffer: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; case RvkDescKind_Count: break; } diag_crash_msg("Unsupported binding kind"); } MAYBE_UNUSED static usize rvk_desc_binding_count(const RvkDescMeta* meta) { usize res = 0; array_for_t(meta->bindings, RvkDescKind, kind) { if (*kind) { ++res; } } return res; } static VkDescriptorSetLayout rvk_desc_vklayout_create(RvkDescPool* pool, const RvkDescMeta* meta) { VkDescriptorSetLayoutBinding bindings[rvk_desc_bindings_max]; u32 bindingCount = 0; for (u32 id = 0; id != rvk_desc_bindings_max; ++id) { if (meta->bindings[id]) { bindings[bindingCount++] = (VkDescriptorSetLayoutBinding){ .binding = id, .descriptorType = rvk_desc_vktype(meta->bindings[id]), .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_ALL_GRAPHICS, }; } } const VkDescriptorSetLayoutCreateInfo layoutInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = bindingCount, .pBindings = bindings, }; VkDescriptorSetLayout result; rvk_call(vkCreateDescriptorSetLayout, pool->vkDev, &layoutInfo, &pool->vkAlloc, &result); return result; } static VkDescriptorPool rvk_desc_vkpool_create(RvkDescPool* pool, const RvkDescMeta* meta) { VkDescriptorPoolSize sizes[rvk_desc_bindings_max]; u32 sizeCount = 0; for (u32 id = 0; id != rvk_desc_bindings_max; ++id) { if (meta->bindings[id]) { const VkDescriptorType type = rvk_desc_vktype(meta->bindings[id]); for (u32 sizeIdx = 0; sizeIdx != sizeCount; ++sizeIdx) { if (sizes[sizeIdx].type == type) { sizes[sizeIdx].descriptorCount += rvk_desc_sets_per_chunk; goto NextBinding; } } sizes[sizeCount++] = (VkDescriptorPoolSize){type, .descriptorCount = rvk_desc_sets_per_chunk}; } NextBinding: continue; } if (!sizeCount) { /** * NOTE: Vulkan spec does not allow for empty descriptor pools, however supporting empty * bindings simplifies the api quite a bit. Needs investigation into alternatives. */ sizes[sizeCount++] = (VkDescriptorPoolSize){VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .descriptorCount = 1}; } const VkDescriptorPoolCreateInfo poolInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .poolSizeCount = sizeCount, .pPoolSizes = sizes, .maxSets = rvk_desc_sets_per_chunk, }; VkDescriptorPool result; rvk_call(vkCreateDescriptorPool, pool->vkDev, &poolInfo, &pool->vkAlloc, &result); return result; } static RvkDescChunk* rvk_desc_chunk_create(RvkDescPool* pool, const RvkDescMeta* meta) { RvkDescChunk* chunk = alloc_alloc_t(g_alloc_heap, RvkDescChunk); *chunk = (RvkDescChunk){ .pool = pool, .vkPool = rvk_desc_vkpool_create(pool, meta), .metaHash = rvk_desc_meta_hash(meta), }; const BitSet freeMask = rvk_desc_chunk_mask(chunk); const VkDescriptorSetLayout vkLayout = rvk_desc_vklayout(pool, meta); VkDescriptorSetLayout layouts[rvk_desc_sets_per_chunk]; for (usize i = 0; i != rvk_desc_sets_per_chunk; ++i) { layouts[i] = vkLayout; // Use the same layout for all sets in the chunk. bitset_set(freeMask, i); // Mark the set as available. } // Preallocate all the descriptor sets. const VkDescriptorSetAllocateInfo allocInfo = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = chunk->vkPool, .descriptorSetCount = rvk_desc_sets_per_chunk, .pSetLayouts = layouts, }; rvk_call(vkAllocateDescriptorSets, pool->vkDev, &allocInfo, chunk->vkSets); #if defined(VOLO_RVK_DESC_LOGGING) log_d( "Vulkan descriptor chunk created", log_param("bindings", fmt_int(rvk_desc_binding_count(meta))), log_param("sets", fmt_int(rvk_desc_sets_per_chunk)), log_param("meta-hash", fmt_int(chunk->metaHash))); #endif return chunk; } static void rvk_desc_chunk_destroy(RvkDescChunk* chunk) { diag_assert_msg( bitset_count(rvk_desc_chunk_mask(chunk)) == rvk_desc_sets_per_chunk, "Not all descriptor sets have been freed"); vkDestroyDescriptorPool(chunk->pool->vkDev, chunk->vkPool, &chunk->pool->vkAlloc); alloc_free_t(g_alloc_heap, chunk); #if defined(VOLO_RVK_DESC_LOGGING) log_d("Vulkan descriptor chunk destroyed", log_param("meta-hash", fmt_int(chunk->metaHash))); #endif } static RvkDescSet rvk_desc_chunk_alloc(RvkDescChunk* chunk) { const BitSet freeMask = rvk_desc_chunk_mask(chunk); const usize next = bitset_next(freeMask, 0); if (sentinel_check(next)) { return (RvkDescSet){0}; // No set available. } bitset_clear(freeMask, next); // Mark the set as used. return (RvkDescSet){.chunk = chunk, .idx = next}; } static void rvk_desc_chunk_free(RvkDescChunk* chunk, const RvkDescSet set) { diag_assert(set.chunk == chunk); const BitSet freeMask = rvk_desc_chunk_mask(chunk); diag_assert(!bitset_test(freeMask, set.idx)); // Check if its not freed before. bitset_set(freeMask, set.idx); // Mark the set as available. } RvkDescPool* rvk_desc_pool_create(const VkDevice vkDev) { RvkDescPool* pool = alloc_alloc_t(g_alloc_heap, RvkDescPool); *pool = (RvkDescPool){ .vkDev = vkDev, .vkAlloc = rvk_mem_allocator(g_alloc_heap), .layoutLock = thread_mutex_create(g_alloc_heap), .layouts = dynarray_create_t(g_alloc_heap, RvkDescLayout, 64), .chunkLock = thread_mutex_create(g_alloc_heap), }; return pool; } void rvk_desc_pool_destroy(RvkDescPool* pool) { // Destroy all chunks. thread_mutex_destroy(pool->chunkLock); for (RvkDescChunk* chunk = pool->chunkHead; chunk;) { RvkDescChunk* toDestroy = chunk; chunk = chunk->next; rvk_desc_chunk_destroy(toDestroy); } // Destroy all layouts. thread_mutex_destroy(pool->layoutLock); dynarray_for_t(&pool->layouts, RvkDescLayout, layout) { vkDestroyDescriptorSetLayout(pool->vkDev, layout->vkLayout, &pool->vkAlloc); } dynarray_destroy(&pool->layouts); alloc_free_t(g_alloc_heap, pool); } VkDescriptorSetLayout rvk_desc_vklayout(RvkDescPool* pool, const RvkDescMeta* meta) { const u32 hash = rvk_desc_meta_hash(meta); thread_mutex_lock(pool->layoutLock); // Find an existing layout that matches the given descriptor meta or create a new one. RvkDescLayout* tgt = mem_struct(RvkDescLayout, .metaHash = hash).ptr; RvkDescLayout* layout = dynarray_search_binary(&pool->layouts, rvk_desc_compare_layout, tgt); if (!layout) { layout = dynarray_insert_sorted_t(&pool->layouts, RvkDescLayout, rvk_desc_compare_layout, tgt); *layout = (RvkDescLayout){ .metaHash = hash, .meta = *meta, .vkLayout = rvk_desc_vklayout_create(pool, meta), }; #if defined(VOLO_RVK_DESC_LOGGING) log_d( "Vulkan descriptor layout created", log_param("bindings", fmt_int(rvk_desc_binding_count(meta))), log_param("meta-hash", fmt_int(hash))); #endif } const VkDescriptorSetLayout result = layout->vkLayout; thread_mutex_unlock(pool->layoutLock); return result; } RvkDescSet rvk_desc_alloc(RvkDescPool* pool, const RvkDescMeta* meta) { RvkDescSet result = {0}; const u32 hash = rvk_desc_meta_hash(meta); thread_mutex_lock(pool->chunkLock); // Attempt to allocate from an existing chunk. for (RvkDescChunk* chunk = pool->chunkHead; chunk; chunk = chunk->next) { if (chunk->metaHash == hash) { result = rvk_desc_chunk_alloc(chunk); if (rvk_desc_valid(result)) { goto Done; } } } // No existing chunk has a set available; create a new chunk. RvkDescChunk* chunk = rvk_desc_chunk_create(pool, meta); result = rvk_desc_chunk_alloc(chunk); if (!pool->chunkHead) { pool->chunkHead = chunk; } if (pool->chunkTail) { pool->chunkTail->next = chunk; } pool->chunkTail = chunk; Done: diag_assert(rvk_desc_valid(result)); thread_mutex_unlock(pool->chunkLock); return result; } void rvk_desc_free(RvkDescSet set) { diag_assert(rvk_desc_valid(set)); thread_mutex_lock(set.chunk->pool->chunkLock); rvk_desc_chunk_free(set.chunk, set); thread_mutex_unlock(set.chunk->pool->chunkLock); } String rvk_desc_kind_str(const RvkDescKind kind) { static const String names[] = { string_static("None"), string_static("CombinedImageSampler"), string_static("UniformBuffer"), string_static("UniformBufferDynamic"), string_static("StorageBuffer"), }; ASSERT(array_elems(names) == RvkDescKind_Count, "Incorrect number of names"); return names[kind]; } VkDescriptorSet rvk_desc_set_vkset(const RvkDescSet set) { diag_assert(rvk_desc_valid(set)); return set.chunk->vkSets[set.idx]; } VkDescriptorSetLayout rvk_desc_set_vklayout(const RvkDescSet set) { diag_assert(rvk_desc_valid(set)); thread_mutex_lock(set.chunk->pool->layoutLock); const RvkDescLayout* layout = dynarray_search_binary( &set.chunk->pool->layouts, rvk_desc_compare_layout, mem_struct(RvkDescLayout, .metaHash = set.chunk->metaHash).ptr); const VkDescriptorSetLayout result = layout->vkLayout; thread_mutex_unlock(set.chunk->pool->layoutLock); return result; } RvkDescKind rvk_desc_set_kind(const RvkDescSet set, const u32 binding) { diag_assert(rvk_desc_valid(set)); thread_mutex_lock(set.chunk->pool->layoutLock); const RvkDescLayout* layout = dynarray_search_binary( &set.chunk->pool->layouts, rvk_desc_compare_layout, mem_struct(RvkDescLayout, .metaHash = set.chunk->metaHash).ptr); const RvkDescKind result = layout->meta.bindings[binding]; thread_mutex_unlock(set.chunk->pool->layoutLock); return result; } void rvk_desc_set_attach_buffer( const RvkDescSet set, const u32 binding, const RvkBuffer* buffer, const u32 size) { const RvkDescKind kind = rvk_desc_set_kind(set, binding); diag_assert(kind); const VkDescriptorBufferInfo bufferInfo = { .buffer = buffer->vkBuffer, .offset = 0, .range = size ? size : buffer->size, }; const VkWriteDescriptorSet descriptorWrite = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = rvk_desc_set_vkset(set), .dstBinding = binding, .dstArrayElement = 0, .descriptorType = rvk_desc_vktype(kind), .descriptorCount = 1, .pBufferInfo = &bufferInfo, }; vkUpdateDescriptorSets(set.chunk->pool->vkDev, 1, &descriptorWrite, 0, null); } void rvk_desc_set_attach_sampler( const RvkDescSet set, const u32 binding, const RvkImage* image, const RvkSampler* sampler) { MAYBE_UNUSED const RvkDescKind kind = rvk_desc_set_kind(set, binding); diag_assert(kind == RvkDescKind_CombinedImageSampler); VkDescriptorImageInfo imgInfo = { .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, .imageView = image->vkImageView, .sampler = sampler->vkSampler, }; VkWriteDescriptorSet descriptorWrite = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = rvk_desc_set_vkset(set), .dstBinding = binding, .dstArrayElement = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .descriptorCount = 1, .pImageInfo = &imgInfo, }; vkUpdateDescriptorSets(set.chunk->pool->vkDev, 1, &descriptorWrite, 0, null); }
sensiblegame/WebMail-Interface-with-Angular2
test/e2e.utils/dropFile.js
const fs = require('fs'); const path = require('path'); /** * Inspiration: * @link {http://labs.criteo.com/2016/06/1315/} */ module.exports = () => { const makeMediaMap = (filePaths) => { return filePaths.reduce((acc, { file, type }) => { acc[path.basename(file)] = { content: fs.readFileSync(file).toString('base64'), type }; return acc; }, Object.create(null)); }; function dropMedia(filePaths = [], selector) { const MAP_FILES = makeMediaMap(filePaths); // select drop zone with the selectors element(selector).getWebElement() .then((selectedElement) => { // use executeAsyncScript to execute Javascript code in the browser context return browser.executeAsyncScript((MAP_FILES, domElement, callback) => { // here we are in the browser context // decode the media content with window.atob and create Blob objects function b64toBlob(b64Data, contentType = '', sliceSize = 512) { const byteCharacters = window.atob(b64Data); const max = byteCharacters.length; const byteArrays = []; for (let offset = 0; offset < max; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, { type: contentType }); } // create the array of file objects to attach to the mouse drop event const files = Object .keys(MAP_FILES) .map((fileName) => { const { content, type = 'image/jpeg' } = MAP_FILES[fileName]; const blob = b64toBlob(content, type); return new File([blob], fileName, { lastModified: blob.lastModifiedDate, type }); }); const e = new MouseEvent('dragenter'); e.dataTransfer = { dataTransfer: { types: ['image/jpeg'] } }; domElement.dispatchEvent(e); setTimeout(() => { // create the mouse drop event const event = new MouseEvent('drop'); event.dataTransfer = { types: ['File'], files, item(i) { return this.files[i]; }, length: files.length }; // dispatch the event $('.composer-dropzone')[0].dispatchEvent(event); // call the callback function callback(); }, 100); }, MAP_FILES, selectedElement); }) .then(() => console.log('Drop:success')); } return { dropMedia }; };
Matthew-Han/leetcode
dream/No1480.java
<gh_stars>0 /** * @ClassName RunningSumOf1dArray * @Description #1480 一维数组的动态和 * @Author MatthewHan * @Date 2020/7/15 11:23 * @Version 1.0 **/ public class No1480 { /** * 执行用时: 0 ms , 在所有 Java 提交中击败了 100.00% 的用户 * 内存消耗: 39.8 MB , 在所有 Java 提交中击败了 100.00% 的用户 * * @param nums * @return */ public int[] runningSum(int[] nums) { int sum = 0; for (int num : nums) { sum += num; } for (int i = nums.length - 1; i >= 0; i--) { int temp = nums[i]; nums[i] = sum; sum -= temp; } return nums; } /** * 执行用时: 0 ms , 在所有 Java 提交中击败了 100.00% 的用户 * 内存消耗: 39.7 MB , 在所有 Java 提交中击败了 100.00% 的用户 * * @param nums * @return */ public int[] runningSumPro(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { nums[i + 1] = nums[i] + nums[i + 1]; } return nums; } }
16Bitt/virtix
libc/include/syscall.h
#ifndef __SYSCALL_H #define __SYSCALL_H #include "sys/cdefs.h" __HEADER_START #define SYS_FORK 0 #define SYS_GETPID 1 #define SYS_GETENV 2 #define SYS_WRITE 3 #define SYS_READ 4 #define SYS_CLOSE 5 #define SYS_EXIT 6 #define SYS_OPEN 7 #define SYS_MALLOC 8 #define SYS_FREE 9 #define SYS_GET_ARGS 10 #define SYS_LSEEK 11 #define SYS_GETSTDIN 12 #define SYS_GETSTDOUT 13 #define SYS_GETSTDERR 14 #define SYS_EXEC 15 #define SYS_SBRK 16 #define SYS_RAISE 17 #define SYS_SIGNAL 18 #define SYS_SIGEXIT 19 #define SYS_WAIT 20 #define SYS_GETGID 21 #define SYS_GETCWD 22 #define SYS_CHDIR 23 #define SYS_EXECVE 24 #define SYS_STAT 25 #define SYS_FSTAT 26 #define SYS_SYNC 27 int syscall_0arg(uint call_no); int syscall_1arg(uint call_no, uint arg1); int syscall_2arg(uint call_no, uint arg1, uint arg2); int syscall_3arg(uint call_no, uint arg1, uint arg2, uint arg3); int syscall_4arg(uint call_no, uint arg1, uint arg2, uint arg3, uint arg4); __HEADER_END #endif
mohneesh9797-puresoftware/cat2
cat-core-config/src/main/java/org/unidal/cat/core/config/spi/ConfigChangeListener.java
<reponame>mohneesh9797-puresoftware/cat2 package org.unidal.cat.core.config.spi; public interface ConfigChangeListener { /** * Applies the config change, throws excepiton if any error. * * @param config * to be applied * @exception ConfigException * should be thrown if the config is NOT changeable */ public void onChanged(String config) throws ConfigException; }
bigginlab/chap
include/io/pdb_io.hpp
<filename>include/io/pdb_io.hpp // CHAP - The Channel Annotation Package // // Copyright (c) 2016 - 2018 <NAME>, <NAME>, <NAME>, and // <NAME> // // 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. #ifndef PDB_IO_HPP #define PDB_IO_HPP #include <fstream> #include <string> #include <vector> #include <gromacs/trajectoryanalysis/analysissettings.h> #include <gromacs/topology/topology.h> #include <gromacs/utility/real.h> #include "statistics/summary_statistics.hpp" /*! * \brief Container class for a PDB structure. */ class PdbStructure { friend class PdbIo; public: // create PDB file from topology: void fromTopology(const gmx::TopologyInformation &top); // void setPoreFacing( const std::vector<SummaryStatistics> &poreLining, const std::vector<SummaryStatistics> &poreFacing); private: // data required for writing PDB file: t_atoms atoms_; rvec *coords_; int ePBC_; matrix box_; }; /*! * \brief Exports structures to PDB file format. * * This wraps around the PDB export utilities of Gromacs. */ class PdbIo { public: // public interface for PDB export: static void write( std::string fileName, PdbStructure structure); private: }; #endif
rSantucci/PonySDK
ponysdk/src/main/java/com/ponysdk/core/ui/basic/PSimplePanel.java
/* * Copyright (c) 2011 PonySDK * Owners: * <NAME> <luciano.broussal AT gmail.com> * <NAME> <mathieu.barbier AT gmail.com> * <NAME> <nicolas.ciaravola.pro AT gmail.com> * * WebSite: * http://code.google.com/p/pony-sdk/ * * 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.ponysdk.core.ui.basic; import com.ponysdk.core.model.WidgetType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.NoSuchElementException; /** * Base class for panels that contain only one widget. */ public class PSimplePanel extends PPanel implements PAcceptsOneWidget { private static final Logger log = LoggerFactory.getLogger(PSimplePanel.class); private PWidget widget; protected PSimplePanel() { } @Override protected WidgetType getWidgetType() { return WidgetType.SIMPLE_PANEL; } @Override public void add(final PWidget w) { if (widget == null) setWidget(w); else log.error("Can only contain one widget to a PSimplePanel, remove the previous one or use a PComplexPanel"); } public PWidget getWidget() { return widget; } @Override public void setWidget(final IsPWidget w) { setWidget(w.asWidget()); } @Override public boolean remove(final PWidget w) { // Validate. if (widget == null || widget != w) { return false; } // Orphan. try { orphan(w); } finally { // Physical detach. w.saveRemove(w.getID(), ID); // Logical detach. widget = null; } return true; } public void setWidget(final PWidget w) { if (w == this) throw new UnsupportedOperationException("You cannot call setWidget with 'this' in parameter"); // Validate if (w == widget) return; // Detach new child. w.removeFromParent(); // Remove old child. if (widget != null) { remove(widget); } // Logical attach. widget = w; adopt(w); if (isInitialized()) w.attach(window, frame); w.saveAdd(w.getID(), ID); } @Override public Iterator<PWidget> iterator() { return new Iterator<>() { boolean hasElement = widget != null; PWidget returned = null; @Override public boolean hasNext() { return hasElement; } @Override public PWidget next() { if (!hasElement || widget == null) { throw new NoSuchElementException(); } hasElement = false; return returned = widget; } @Override public void remove() { if (returned != null) { PSimplePanel.this.remove(returned); } } }; } @Override public String dumpDOM() { return "<div pid=\"" + ID + "\">" + widget.dumpDOM() + "</div>"; } }
stewnorriss/letsencrypt
letsencrypt-apache/letsencrypt_apache/tests/configurator_test.py
"""Test for letsencrypt_apache.configurator.""" import os import re import shutil import unittest import mock from acme import challenges from letsencrypt import achallenges from letsencrypt import errors from letsencrypt import le_util from letsencrypt.plugins import common from letsencrypt.tests import acme_util from letsencrypt_apache import configurator from letsencrypt_apache import parser from letsencrypt_apache.tests import util class TwoVhost80Test(util.ApacheTest): """Test two standard well configured HTTP vhosts.""" def setUp(self): super(TwoVhost80Test, self).setUp() with mock.patch("letsencrypt_apache.configurator.ApacheConfigurator." "mod_loaded") as mock_load: mock_load.return_value = True self.config = util.get_apache_configurator( self.config_path, self.config_dir, self.work_dir) self.vh_truth = util.get_vh_truth( self.temp_dir, "debian_apache_2_4/two_vhost_80") def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) def test_get_all_names(self): names = self.config.get_all_names() self.assertEqual(names, set( ["letsencrypt.demo", "encryption-example.demo", "ip-172-30-0-17"])) def test_get_virtual_hosts(self): """Make sure all vhosts are being properly found. .. note:: If test fails, only finding 1 Vhost... it is likely that it is a problem with is_enabled. """ vhs = self.config.get_virtual_hosts() self.assertEqual(len(vhs), 4) found = 0 for vhost in vhs: for truth in self.vh_truth: if vhost == truth: found += 1 break self.assertEqual(found, 4) def test_is_site_enabled(self): """Test if site is enabled. .. note:: This test currently fails for hard links (which may happen if you move dirs incorrectly) .. warning:: This test does not work when running using the unittest.main() function. It incorrectly copies symlinks. """ self.assertTrue(self.config.is_site_enabled(self.vh_truth[0].filep)) self.assertFalse(self.config.is_site_enabled(self.vh_truth[1].filep)) self.assertTrue(self.config.is_site_enabled(self.vh_truth[2].filep)) self.assertTrue(self.config.is_site_enabled(self.vh_truth[3].filep)) def test_deploy_cert(self): # Get the default 443 vhost self.config.assoc["random.demo"] = self.vh_truth[1] self.config.deploy_cert( "random.demo", "example/cert.pem", "example/key.pem", "example/cert_chain.pem") self.config.save() loc_cert = self.config.parser.find_dir( parser.case_i("sslcertificatefile"), re.escape("example/cert.pem"), self.vh_truth[1].path) loc_key = self.config.parser.find_dir( parser.case_i("sslcertificateKeyfile"), re.escape("example/key.pem"), self.vh_truth[1].path) loc_chain = self.config.parser.find_dir( parser.case_i("SSLCertificateChainFile"), re.escape("example/cert_chain.pem"), self.vh_truth[1].path) # Verify one directive was found in the correct file self.assertEqual(len(loc_cert), 1) self.assertEqual(configurator.get_file_path(loc_cert[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_key), 1) self.assertEqual(configurator.get_file_path(loc_key[0]), self.vh_truth[1].filep) self.assertEqual(len(loc_chain), 1) self.assertEqual(configurator.get_file_path(loc_chain[0]), self.vh_truth[1].filep) def test_is_name_vhost(self): addr = common.Addr.fromstring("*:80") self.assertTrue(self.config.is_name_vhost(addr)) self.config.version = (2, 2) self.assertFalse(self.config.is_name_vhost(addr)) def test_add_name_vhost(self): self.config.add_name_vhost("*:443") self.assertTrue(self.config.parser.find_dir( "NameVirtualHost", re.escape("*:443"))) def test_make_vhost_ssl(self): ssl_vhost = self.config.make_vhost_ssl(self.vh_truth[0]) self.assertEqual( ssl_vhost.filep, os.path.join(self.config_path, "sites-available", "encryption-example-le-ssl.conf")) self.assertEqual(ssl_vhost.path, "/files" + ssl_vhost.filep + "/IfModule/VirtualHost") self.assertEqual(len(ssl_vhost.addrs), 1) self.assertEqual(set([common.Addr.fromstring("*:443")]), ssl_vhost.addrs) self.assertEqual(ssl_vhost.names, set(["encryption-example.demo"])) self.assertTrue(ssl_vhost.ssl) self.assertFalse(ssl_vhost.enabled) self.assertTrue(self.config.parser.find_dir( "SSLCertificateFile", None, ssl_vhost.path)) self.assertTrue(self.config.parser.find_dir( "SSLCertificateKeyFile", None, ssl_vhost.path)) self.assertTrue(self.config.parser.find_dir( "Include", self.ssl_options, ssl_vhost.path)) self.assertEqual(self.config.is_name_vhost(self.vh_truth[0]), self.config.is_name_vhost(ssl_vhost)) self.assertEqual(len(self.config.vhosts), 5) @mock.patch("letsencrypt_apache.configurator.dvsni.ApacheDvsni.perform") @mock.patch("letsencrypt_apache.configurator.ApacheConfigurator.restart") def test_perform(self, mock_restart, mock_dvsni_perform): # Only tests functionality specific to configurator.perform # Note: As more challenges are offered this will have to be expanded auth_key = le_util.Key(self.rsa256_file, self.rsa256_pem) achall1 = achallenges.DVSNI( challb=acme_util.chall_to_challb( challenges.DVSNI( r="jIq_Xy1mXGN37tb4L6Xj_es58fW571ZNyXekdZzhh7Q", nonce="37bc5eb75d3e00a19b4f6355845e5a18"), "pending"), domain="encryption-example.demo", key=auth_key) achall2 = achallenges.DVSNI( challb=acme_util.chall_to_challb( challenges.DVSNI( r="uqnaPzxtrndteOqtrXb0Asl5gOJfWAnnx6QJyvcmlDU", nonce="59ed014cac95f77057b1d7a1b2c596ba"), "pending"), domain="letsencrypt.demo", key=auth_key) dvsni_ret_val = [ challenges.DVSNIResponse(s="randomS1"), challenges.DVSNIResponse(s="randomS2"), ] mock_dvsni_perform.return_value = dvsni_ret_val responses = self.config.perform([achall1, achall2]) self.assertEqual(mock_dvsni_perform.call_count, 1) self.assertEqual(responses, dvsni_ret_val) self.assertEqual(mock_restart.call_count, 1) @mock.patch("letsencrypt_apache.configurator.subprocess.Popen") def test_get_version(self, mock_popen): mock_popen().communicate.return_value = ( "Server Version: Apache/2.4.2 (Debian)", "") self.assertEqual(self.config.get_version(), (2, 4, 2)) mock_popen().communicate.return_value = ( "Server Version: Apache/2 (Linux)", "") self.assertEqual(self.config.get_version(), (2,)) mock_popen().communicate.return_value = ( "Server Version: Apache (Debian)", "") self.assertRaises(errors.PluginError, self.config.get_version) mock_popen().communicate.return_value = ( "Server Version: Apache/2.3{0} Apache/2.4.7".format(os.linesep), "") self.assertRaises(errors.PluginError, self.config.get_version) mock_popen.side_effect = OSError("Can't find program") self.assertRaises(errors.PluginError, self.config.get_version) if __name__ == "__main__": unittest.main() # pragma: no cover
chvonrohr/ember-gantt
addon/components/gantt-line-barcontent.js
<gh_stars>0 import Component from '@ember/component'; import layout from '../templates/components/gantt-line-barcontent'; export default Component.extend({ layout, classNames: ['gantt-line-bar-content'] });
etanshaul/travis-cobertura-test
google-cloud-tools-plugin/src/com/google/gct/idea/debugger/ProjectRepositoryState.java
/* * Copyright (C) 2015 The Android Open Source Project * * 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.google.gct.idea.debugger; import com.intellij.openapi.util.Key; import com.intellij.util.xmlb.annotations.Transient; import git4idea.repo.GitRepository; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Holds state and performs operations related to source control contexts. */ public class ProjectRepositoryState { private static final Key<ProjectRepositoryState> REPO_KEY = Key.create("com.google.gct.idea.debugger.ProjectRepositoryState"); private String myOriginalBranchName; private GitRepository mySourceRepository; private String myStashMessage; private ProjectRepositoryState() { } @NotNull public static ProjectRepositoryState fromProcessState(@NotNull CloudDebugProcessState processState) { ProjectRepositoryState repoState = processState.getUserData(REPO_KEY); if (repoState == null) { repoState = new ProjectRepositoryState(); processState.putUserData(REPO_KEY, repoState); } return repoState; } public void clearForNextSession() { setStashMessage(null); } /** * This is the branch the user was on before they started a debug session and we moved them to the target SHA. */ @Transient @Nullable protected String getOriginalBranchName() { return myOriginalBranchName; } @Transient public void setOriginalBranchName(@Nullable String originalBranchName) { myOriginalBranchName = originalBranchName; } /** * The source repository is used during stash/unstash and sync to perform Git operations. Right now we only support * Git. If we added citc or other clients, this would need to be factored out. */ @Transient @Nullable protected GitRepository getSourceRepository() { return mySourceRepository; } @Transient public void setSourceRepository(@Nullable GitRepository sourceRepository) { mySourceRepository = sourceRepository; } /** * The stash message is how we identify which item to unstash when the session ends. Stashes are ordered and may not * necessarily have the same ordinal value because new stashes are inserted at the top. */ @Transient @Nullable protected String getStashMessage() { return myStashMessage; } @Transient public void setStashMessage(@Nullable String stashMessage) { myStashMessage = stashMessage; } /** * @return True if we have a valid git repo */ protected boolean hasSourceRepository() { return getSourceRepository() != null; } }
bm16ton/yoga-c630-linux-kernel
drivers/gpu/drm/i915/gem/i915_gem_shmem.c
/* * SPDX-License-Identifier: MIT * * Copyright © 2014-2016 Intel Corporation */ #include <linux/pagevec.h> #include <linux/swap.h> #include "gem/i915_gem_region.h" #include "i915_drv.h" #include "i915_gemfs.h" #include "i915_gem_object.h" #include "i915_scatterlist.h" #include "i915_trace.h" /* * Move pages to appropriate lru and release the pagevec, decrementing the * ref count of those pages. */ static void check_release_pagevec(struct pagevec *pvec) { check_move_unevictable_pages(pvec); __pagevec_release(pvec); cond_resched(); } static int shmem_get_pages(struct drm_i915_gem_object *obj) { struct drm_i915_private *i915 = to_i915(obj->base.dev); struct intel_memory_region *mem = obj->mm.region; const unsigned long page_count = obj->base.size / PAGE_SIZE; unsigned long i; struct address_space *mapping; struct sg_table *st; struct scatterlist *sg; struct sgt_iter sgt_iter; struct page *page; unsigned long last_pfn = 0; /* suppress gcc warning */ unsigned int max_segment = i915_sg_segment_size(); unsigned int sg_page_sizes; gfp_t noreclaim; int ret; /* * Assert that the object is not currently in any GPU domain. As it * wasn't in the GTT, there shouldn't be any way it could have been in * a GPU cache */ GEM_BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS); GEM_BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS); /* * If there's no chance of allocating enough pages for the whole * object, bail early. */ if (obj->base.size > resource_size(&mem->region)) return -ENOMEM; st = kmalloc(sizeof(*st), GFP_KERNEL); if (!st) return -ENOMEM; rebuild_st: if (sg_alloc_table(st, page_count, GFP_KERNEL)) { kfree(st); return -ENOMEM; } /* * Get the list of pages out of our struct file. They'll be pinned * at this point until we release them. * * Fail silently without starting the shrinker */ mapping = obj->base.filp->f_mapping; mapping_set_unevictable(mapping); noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM); noreclaim |= __GFP_NORETRY | __GFP_NOWARN; sg = st->sgl; st->nents = 0; sg_page_sizes = 0; for (i = 0; i < page_count; i++) { const unsigned int shrink[] = { I915_SHRINK_BOUND | I915_SHRINK_UNBOUND, 0, }, *s = shrink; gfp_t gfp = noreclaim; do { cond_resched(); page = shmem_read_mapping_page_gfp(mapping, i, gfp); if (!IS_ERR(page)) break; if (!*s) { ret = PTR_ERR(page); goto err_sg; } i915_gem_shrink(i915, 2 * page_count, NULL, *s++); /* * We've tried hard to allocate the memory by reaping * our own buffer, now let the real VM do its job and * go down in flames if truly OOM. * * However, since graphics tend to be disposable, * defer the oom here by reporting the ENOMEM back * to userspace. */ if (!*s) { /* reclaim and warn, but no oom */ gfp = mapping_gfp_mask(mapping); /* * Our bo are always dirty and so we require * kswapd to reclaim our pages (direct reclaim * does not effectively begin pageout of our * buffers on its own). However, direct reclaim * only waits for kswapd when under allocation * congestion. So as a result __GFP_RECLAIM is * unreliable and fails to actually reclaim our * dirty pages -- unless you try over and over * again with !__GFP_NORETRY. However, we still * want to fail this allocation rather than * trigger the out-of-memory killer and for * this we want __GFP_RETRY_MAYFAIL. */ gfp |= __GFP_RETRY_MAYFAIL; } } while (1); if (!i || sg->length >= max_segment || page_to_pfn(page) != last_pfn + 1) { if (i) { sg_page_sizes |= sg->length; sg = sg_next(sg); } st->nents++; sg_set_page(sg, page, PAGE_SIZE, 0); } else { sg->length += PAGE_SIZE; } last_pfn = page_to_pfn(page); /* Check that the i965g/gm workaround works. */ GEM_BUG_ON(gfp & __GFP_DMA32 && last_pfn >= 0x00100000UL); } if (sg) { /* loop terminated early; short sg table */ sg_page_sizes |= sg->length; sg_mark_end(sg); } /* Trim unused sg entries to avoid wasting memory. */ i915_sg_trim(st); ret = i915_gem_gtt_prepare_pages(obj, st); if (ret) { /* * DMA remapping failed? One possible cause is that * it could not reserve enough large entries, asking * for PAGE_SIZE chunks instead may be helpful. */ if (max_segment > PAGE_SIZE) { for_each_sgt_page(page, sgt_iter, st) put_page(page); sg_free_table(st); max_segment = PAGE_SIZE; goto rebuild_st; } else { dev_warn(&i915->drm.pdev->dev, "Failed to DMA remap %lu pages\n", page_count); goto err_pages; } } if (i915_gem_object_needs_bit17_swizzle(obj)) i915_gem_object_do_bit_17_swizzle(obj, st); __i915_gem_object_set_pages(obj, st, sg_page_sizes); return 0; err_sg: sg_mark_end(sg); err_pages: mapping_clear_unevictable(mapping); if (sg != st->sgl) { struct pagevec pvec; pagevec_init(&pvec); for_each_sgt_page(page, sgt_iter, st) { if (!pagevec_add(&pvec, page)) check_release_pagevec(&pvec); } if (pagevec_count(&pvec)) check_release_pagevec(&pvec); } sg_free_table(st); kfree(st); /* * shmemfs first checks if there is enough memory to allocate the page * and reports ENOSPC should there be insufficient, along with the usual * ENOMEM for a genuine allocation failure. * * We use ENOSPC in our driver to mean that we have run out of aperture * space and so want to translate the error from shmemfs back to our * usual understanding of ENOMEM. */ if (ret == -ENOSPC) ret = -ENOMEM; return ret; } static void shmem_truncate(struct drm_i915_gem_object *obj) { /* * Our goal here is to return as much of the memory as * is possible back to the system as we are called from OOM. * To do this we must instruct the shmfs to drop all of its * backing pages, *now*. */ shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1); obj->mm.madv = __I915_MADV_PURGED; obj->mm.pages = ERR_PTR(-EFAULT); } static void shmem_writeback(struct drm_i915_gem_object *obj) { struct address_space *mapping; struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = SWAP_CLUSTER_MAX, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1, }; unsigned long i; /* * Leave mmapings intact (GTT will have been revoked on unbinding, * leaving only CPU mmapings around) and add those pages to the LRU * instead of invoking writeback so they are aged and paged out * as normal. */ mapping = obj->base.filp->f_mapping; /* Begin writeback on each dirty page */ for (i = 0; i < obj->base.size >> PAGE_SHIFT; i++) { struct page *page; page = find_lock_page(mapping, i); if (!page) continue; if (!page_mapped(page) && clear_page_dirty_for_io(page)) { int ret; SetPageReclaim(page); ret = mapping->a_ops->writepage(page, &wbc); if (!PageWriteback(page)) ClearPageReclaim(page); if (!ret) goto put; } unlock_page(page); put: put_page(page); } } void __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj, struct sg_table *pages, bool needs_clflush) { GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED); if (obj->mm.madv == I915_MADV_DONTNEED) obj->mm.dirty = false; if (needs_clflush && (obj->read_domains & I915_GEM_DOMAIN_CPU) == 0 && !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ)) drm_clflush_sg(pages); __start_cpu_write(obj); } static void shmem_put_pages(struct drm_i915_gem_object *obj, struct sg_table *pages) { struct sgt_iter sgt_iter; struct pagevec pvec; struct page *page; __i915_gem_object_release_shmem(obj, pages, true); i915_gem_gtt_finish_pages(obj, pages); if (i915_gem_object_needs_bit17_swizzle(obj)) i915_gem_object_save_bit_17_swizzle(obj, pages); mapping_clear_unevictable(file_inode(obj->base.filp)->i_mapping); pagevec_init(&pvec); for_each_sgt_page(page, sgt_iter, pages) { if (obj->mm.dirty) set_page_dirty(page); if (obj->mm.madv == I915_MADV_WILLNEED) mark_page_accessed(page); if (!pagevec_add(&pvec, page)) check_release_pagevec(&pvec); } if (pagevec_count(&pvec)) check_release_pagevec(&pvec); obj->mm.dirty = false; sg_free_table(pages); kfree(pages); } static int shmem_pwrite(struct drm_i915_gem_object *obj, const struct drm_i915_gem_pwrite *arg) { struct address_space *mapping = obj->base.filp->f_mapping; char __user *user_data = u64_to_user_ptr(arg->data_ptr); u64 remain, offset; unsigned int pg; /* Caller already validated user args */ GEM_BUG_ON(!access_ok(user_data, arg->size)); /* * Before we instantiate/pin the backing store for our use, we * can prepopulate the shmemfs filp efficiently using a write into * the pagecache. We avoid the penalty of instantiating all the * pages, important if the user is just writing to a few and never * uses the object on the GPU, and using a direct write into shmemfs * allows it to avoid the cost of retrieving a page (either swapin * or clearing-before-use) before it is overwritten. */ if (i915_gem_object_has_pages(obj)) return -ENODEV; if (obj->mm.madv != I915_MADV_WILLNEED) return -EFAULT; /* * Before the pages are instantiated the object is treated as being * in the CPU domain. The pages will be clflushed as required before * use, and we can freely write into the pages directly. If userspace * races pwrite with any other operation; corruption will ensue - * that is userspace's prerogative! */ remain = arg->size; offset = arg->offset; pg = offset_in_page(offset); do { unsigned int len, unwritten; struct page *page; void *data, *vaddr; int err; char c; len = PAGE_SIZE - pg; if (len > remain) len = remain; /* Prefault the user page to reduce potential recursion */ err = __get_user(c, user_data); if (err) return err; err = __get_user(c, user_data + len - 1); if (err) return err; err = pagecache_write_begin(obj->base.filp, mapping, offset, len, 0, &page, &data); if (err < 0) return err; vaddr = kmap_atomic(page); unwritten = __copy_from_user_inatomic(vaddr + pg, user_data, len); kunmap_atomic(vaddr); err = pagecache_write_end(obj->base.filp, mapping, offset, len, len - unwritten, page, data); if (err < 0) return err; /* We don't handle -EFAULT, leave it to the caller to check */ if (unwritten) return -ENODEV; remain -= len; user_data += len; offset += len; pg = 0; } while (remain); return 0; } static void shmem_release(struct drm_i915_gem_object *obj) { i915_gem_object_release_memory_region(obj); fput(obj->base.filp); } const struct drm_i915_gem_object_ops i915_gem_shmem_ops = { .name = "i915_gem_object_shmem", .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE | I915_GEM_OBJECT_IS_SHRINKABLE, .get_pages = shmem_get_pages, .put_pages = shmem_put_pages, .truncate = shmem_truncate, .writeback = shmem_writeback, .pwrite = shmem_pwrite, .release = shmem_release, }; static int __create_shmem(struct drm_i915_private *i915, struct drm_gem_object *obj, resource_size_t size) { unsigned long flags = VM_NORESERVE; struct file *filp; drm_gem_private_object_init(&i915->drm, obj, size); if (i915->mm.gemfs) filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size, flags); else filp = shmem_file_setup("i915", size, flags); if (IS_ERR(filp)) return PTR_ERR(filp); obj->filp = filp; return 0; } static int shmem_object_init(struct intel_memory_region *mem, struct drm_i915_gem_object *obj, resource_size_t size, unsigned int flags) { static struct lock_class_key lock_class; struct drm_i915_private *i915 = mem->i915; struct address_space *mapping; unsigned int cache_level; gfp_t mask; int ret; ret = __create_shmem(i915, &obj->base, size); if (ret) return ret; mask = GFP_HIGHUSER | __GFP_RECLAIMABLE; if (IS_I965GM(i915) || IS_I965G(i915)) { /* 965gm cannot relocate objects above 4GiB. */ mask &= ~__GFP_HIGHMEM; mask |= __GFP_DMA32; } mapping = obj->base.filp->f_mapping; mapping_set_gfp_mask(mapping, mask); GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM)); i915_gem_object_init(obj, &i915_gem_shmem_ops, &lock_class); obj->write_domain = I915_GEM_DOMAIN_CPU; obj->read_domains = I915_GEM_DOMAIN_CPU; if (HAS_LLC(i915)) /* On some devices, we can have the GPU use the LLC (the CPU * cache) for about a 10% performance improvement * compared to uncached. Graphics requests other than * display scanout are coherent with the CPU in * accessing this cache. This means in this mode we * don't need to clflush on the CPU side, and on the * GPU side we only need to flush internal caches to * get data visible to the CPU. * * However, we maintain the display planes as UC, and so * need to rebind when first used as such. */ cache_level = I915_CACHE_LLC; else cache_level = I915_CACHE_NONE; i915_gem_object_set_cache_coherency(obj, cache_level); i915_gem_object_init_memory_region(obj, mem, 0); return 0; } struct drm_i915_gem_object * i915_gem_object_create_shmem(struct drm_i915_private *i915, resource_size_t size) { return i915_gem_object_create_region(i915->mm.regions[INTEL_REGION_SMEM], size, 0); } /* Allocate a new GEM object and fill it with the supplied data */ struct drm_i915_gem_object * i915_gem_object_create_shmem_from_data(struct drm_i915_private *dev_priv, const void *data, resource_size_t size) { struct drm_i915_gem_object *obj; struct file *file; resource_size_t offset; int err; obj = i915_gem_object_create_shmem(dev_priv, round_up(size, PAGE_SIZE)); if (IS_ERR(obj)) return obj; GEM_BUG_ON(obj->write_domain != I915_GEM_DOMAIN_CPU); file = obj->base.filp; offset = 0; do { unsigned int len = min_t(typeof(size), size, PAGE_SIZE); struct page *page; void *pgdata, *vaddr; err = pagecache_write_begin(file, file->f_mapping, offset, len, 0, &page, &pgdata); if (err < 0) goto fail; vaddr = kmap(page); memcpy(vaddr, data, len); kunmap(page); err = pagecache_write_end(file, file->f_mapping, offset, len, len, page, pgdata); if (err < 0) goto fail; size -= len; data += len; offset += len; } while (size); return obj; fail: i915_gem_object_put(obj); return ERR_PTR(err); } static int init_shmem(struct intel_memory_region *mem) { int err; err = i915_gemfs_init(mem->i915); if (err) { DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err); } intel_memory_region_set_name(mem, "system"); return 0; /* Don't error, we can simply fallback to the kernel mnt */ } static void release_shmem(struct intel_memory_region *mem) { i915_gemfs_fini(mem->i915); } static const struct intel_memory_region_ops shmem_region_ops = { .init = init_shmem, .release = release_shmem, .init_object = shmem_object_init, }; struct intel_memory_region *i915_gem_shmem_setup(struct drm_i915_private *i915) { return intel_memory_region_create(i915, 0, totalram_pages() << PAGE_SHIFT, PAGE_SIZE, 0, &shmem_region_ops); } bool i915_gem_object_is_shmem(const struct drm_i915_gem_object *obj) { return obj->ops == &i915_gem_shmem_ops; }