max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,253
<gh_stars>1000+ #include <iostream> #include <fstream> #include <string> #include <map> #include <vector> using namespace std; map <char, char> subs_table_enc; map <char, char> subs_table_dec; map <char, string> options; void help () { cout << "Instructions:" << endl; cout << "This is an implementation of substitution cipher that at the end gives you a file called <my_file>_encrypted.txt or <my_file>_decryted.txt" << endl; cout << endl; cout << "The program has 3 options:" << endl; cout << "--encrypt, -e: encrypt a file passed as an argument" << endl; cout << "--decript, -d: decrypt a file passed as an argument" << endl; cout << "--subs_table, -s: use a substitution table passed as an argument" << endl; cout << endl; cout << "Example:" << endl; cout << "./substitution_cipher -e my_file_decrypted.txt -s my_table.txt" << endl; cout << "./substitution_cipher -d my_file_encrypted.txt -s my_table.txt" << endl; } int load_options (int argc, char* argv[]) { for (int i = 1; i < argc; i += 2) { string option = argv[i]; if (i + 1 >= argc) { return -1; } if (option == "-e" || option == "encrypt") { options['e'] = argv[i + 1]; } else if (option == "-d" || option == "decrypt") { options['d'] = argv[i + 1]; } else if (option == "-s" || option == "subs_table") { options['s'] = argv[i + 1]; } else { return -1; } } return 0; } int load_table () { ifstream table_file (options['s']); if (!table_file.is_open ()) { return -1; } string line1; string line2; getline (table_file, line1); getline (table_file, line2); if (line1.size() != line2.size()) { return -1; } for (int i = 0; i < line1.size(); ++i) { subs_table_enc[line1[i]] = line2[i]; subs_table_dec[line2[i]] = line1[i]; } table_file.close (); return 0; } string remove_ext (const string &file_name) { int pos = file_name.size () - 1; for (; pos >= 0; --pos) { if (file_name[pos] == '.') { break; } } return file_name.substr (0, pos); } int base_function (const string &file_name, map<char, char> &subs, const string &cypher_name) { ifstream file (file_name); if (!file.is_open()) { return -1; } ofstream o_file; o_file.open (remove_ext (file_name) + "_" + cypher_name); string line; string nline; while (getline (file, line)) { nline = ""; for (char c : line) { if (!subs.count(c)) { nline += c; continue; } nline += subs[c]; } o_file << nline << endl; } o_file.close (); return 0; } int encrypt (const string &file_name) { return base_function (file_name, subs_table_enc, "encrypted.txt"); } int decrypt (const string &file_name) { return base_function (file_name, subs_table_dec, "decrypted.txt"); } int main (int argc, char* argv[]) { if (argc != 5) { help (); return 0; } if (load_options (argc, argv) == -1) { cout << "The command is not valid" << endl; help (); return 0; } if (load_table() == -1) { cout << "Table file not found" << endl; help (); return 0; } if (options.count ('e')) { if (encrypt (options['e']) == -1) { cout << "Error encrypting the file" << endl; help (); } } else if (options.count ('d')) { if (decrypt (options['d']) == -1) { cout << "Error decrypting the file" << endl; help (); } } else { cout << "The command is not valid" << endl; help (); } return 0; }
1,887
420
<filename>sample/src/main/java/com/kevin/delegationadapter/sample/util/ViewBindingAdapter.java package com.kevin.delegationadapter.sample.util; import android.view.View; import android.view.ViewGroup; import androidx.databinding.BindingAdapter; /** * ViewBindingAdapter * * @author <EMAIL>, Created on 2018-06-11 17:47:23 * Major Function:<b></b> * <p/> * 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!! * @author mender,Modified Date Modify Content: */ public class ViewBindingAdapter { @BindingAdapter("android:layout_height") public static void setLayoutHeight(View view, float dipValue) { ViewGroup.LayoutParams lp = view.getLayoutParams(); if (lp != null) { final float scale = view.getResources().getDisplayMetrics().density; lp.height = (int) (dipValue * scale + 0.5f); view.setLayoutParams(lp); } } }
444
1,290
#!/usr/bin/env python # Script to extract "hashes" from password protected Apple Notes databases. # # All credit goes to hashcat folks for doing the original hard work. # # ~/Library/Group Containers/group.com.apple.notes/NoteStore.sqlite <- typical # database location. # # This software is Copyright (c) 2017, <NAME> <kholia at kth.se> and it is # hereby released to the general public under the following terms: # # Redistribution and use in source and binary forms, with or without # modification, are permitted. import os import sys import sqlite3 import binascii PY3 = sys.version_info[0] == 3 if not PY3: reload(sys) sys.setdefaultencoding('utf8') def process_file(filename): db = sqlite3.connect(filename) cursor = db.cursor() rows = cursor.execute("SELECT Z_PK, ZCRYPTOITERATIONCOUNT, ZCRYPTOSALT, ZCRYPTOWRAPPEDKEY, ZPASSWORDHINT, ZCRYPTOVERIFIER, ZISPASSWORDPROTECTED FROM ZICCLOUDSYNCINGOBJECT") for row in rows: iden, iterations, salt, fhash, hint, shash, is_protected = row if fhash is None: phash = shash else: phash = fhash if hint is None: hint = "None" # NOTE: is_protected can be zero even if iterations value is non-zero! # This was tested on macOS 10.13.2 with cloud syncing turned off. if iterations == 0: # is this a safer check than checking is_protected? continue phash = binascii.hexlify(phash) salt = binascii.hexlify(salt) if PY3: phash = str(phash, 'ascii') salt = str(salt, 'ascii') fname = os.path.basename(filename) sys.stdout.write("%s:$ASN$*%d*%d*%s*%s:::::%s\n" % (fname, iden, iterations, salt, phash, hint)) if __name__ == "__main__": if len(sys.argv) < 2: sys.stderr.write("Usage: %s [Apple Notes .sqlite files]\n" % sys.argv[0]) sys.exit(-1) for i in range(1, len(sys.argv)): process_file(sys.argv[i])
884
643
public class CharLiterals { public static boolean redundantSurrogateRange(char c) { if(c >= '\uda00') { if(c >= '\ud900') { return true; } } return false; } public static boolean goodSurrogateRange(char c) { if(c >= '\ud900') { if(c >= '\uda00') { return true; } } return false; } public static boolean redundantNonSurrogateRange(char c) { if(c >= 'b') { if(c >= 'a') { return true; } } return false; } public static boolean goodNonSurrogateRange(char c) { if(c >= 'a') { if(c >= 'b') { return true; } } return false; } public static boolean redundantSurrogateEquality(char c) { if(c == '\uda00') { return true; } else if(c == '\uda00') { return true; } return false; } public static boolean goodSurrogateEquality(char c) { if(c == '\uda00') { return true; } else if(c == '\ud900') { return true; } return false; } public static boolean redundantNonSurrogateEquality(char c) { if(c == 'a') { return true; } else if(c == 'a') { return true; } return false; } public static boolean goodNonSurrogateEquality(char c) { if(c == 'a') { return true; } else if(c == 'b') { return true; } return false; } }
641
2,151
// Copyright 2017 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. #include "third_party/blink/renderer/core/paint/compositing/compositing_layer_property_updater.h" #include "third_party/blink/renderer/core/layout/layout_box_model_object.h" #include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h" #include "third_party/blink/renderer/core/paint/fragment_data.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { void CompositingLayerPropertyUpdater::Update(const LayoutObject& object) { if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() || RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) return; if (!object.HasLayer()) return; const auto* paint_layer = ToLayoutBoxModelObject(object).Layer(); const auto* mapping = paint_layer->GetCompositedLayerMapping(); if (!mapping) return; const FragmentData& fragment_data = object.FirstFragment(); DCHECK(fragment_data.HasLocalBorderBoxProperties()); // SPv1 compositing forces single fragment for composited elements. DCHECK(!fragment_data.NextFragment()); LayoutPoint layout_snapped_paint_offset = fragment_data.PaintOffset() - mapping->SubpixelAccumulation(); IntPoint snapped_paint_offset = RoundedIntPoint(layout_snapped_paint_offset); // A layer without visible contents can be composited due to animation. // Since the layer itself has no visible subtree, there is no guarantee // that all of its ancestors have a visible subtree. An ancestor with no // visible subtree can be non-composited despite we expected it to, this // resulted in the paint offset used by CompositedLayerMapping to mismatch. bool subpixel_accumulation_may_be_bogus = paint_layer->SubtreeIsInvisible(); DCHECK(layout_snapped_paint_offset == snapped_paint_offset || subpixel_accumulation_may_be_bogus); base::Optional<PropertyTreeState> container_layer_state; auto SetContainerLayerState = [&fragment_data, &snapped_paint_offset, &container_layer_state](GraphicsLayer* graphics_layer) { if (graphics_layer) { if (!container_layer_state) { container_layer_state = fragment_data.LocalBorderBoxProperties(); if (const auto* properties = fragment_data.PaintProperties()) { // CSS clip should be applied within the layer. if (const auto* css_clip = properties->CssClip()) container_layer_state->SetClip(css_clip->Parent()); } } graphics_layer->SetLayerState( *container_layer_state, snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); } }; SetContainerLayerState(mapping->MainGraphicsLayer()); SetContainerLayerState(mapping->DecorationOutlineLayer()); SetContainerLayerState(mapping->ChildClippingMaskLayer()); base::Optional<PropertyTreeState> scrollbar_layer_state; auto SetContainerLayerStateForScrollbars = [&fragment_data, &snapped_paint_offset, &container_layer_state, &scrollbar_layer_state](GraphicsLayer* graphics_layer) { if (graphics_layer) { if (!scrollbar_layer_state) { // OverflowControlsClip should be applied within the scrollbar // layers. if (container_layer_state) { scrollbar_layer_state = container_layer_state; } else { scrollbar_layer_state = fragment_data.LocalBorderBoxProperties(); } if (const auto* properties = fragment_data.PaintProperties()) { if (const auto* clip = properties->OverflowControlsClip()) { scrollbar_layer_state->SetClip(clip); } else if (const auto* css_clip = properties->CssClip()) { scrollbar_layer_state->SetClip(css_clip->Parent()); } } } graphics_layer->SetLayerState( *scrollbar_layer_state, snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); } }; SetContainerLayerStateForScrollbars(mapping->LayerForHorizontalScrollbar()); SetContainerLayerStateForScrollbars(mapping->LayerForVerticalScrollbar()); SetContainerLayerStateForScrollbars(mapping->LayerForScrollCorner()); if (mapping->ScrollingContentsLayer()) { auto paint_offset = snapped_paint_offset; // In flipped blocks writing mode, if there is scrollbar on the right, // we move the contents to the left with extra amount of ScrollTranslation // (-VerticalScrollbarWidth, 0). However, ScrollTranslation doesn't apply // on ScrollingContentsLayer so we shift paint offset instead. if (object.IsBox() && object.HasFlippedBlocksWritingMode()) paint_offset.Move(ToLayoutBox(object).VerticalScrollbarWidth(), 0); auto SetContentsLayerState = [&fragment_data, &paint_offset](GraphicsLayer* graphics_layer) { if (graphics_layer) { graphics_layer->SetLayerState( fragment_data.ContentsProperties(), paint_offset + graphics_layer->OffsetFromLayoutObject()); } }; SetContentsLayerState(mapping->ScrollingContentsLayer()); SetContentsLayerState(mapping->ForegroundLayer()); } else { SetContainerLayerState(mapping->ForegroundLayer()); } if (auto* squashing_layer = mapping->SquashingLayer()) { auto state = fragment_data.PreEffectProperties(); // The squashing layer's ClippingContainer is the common ancestor of clip // state of all squashed layers, so we should use its clip state. This skips // any control clips on the squashing layer's object which should not apply // on squashed layers. const auto* clipping_container = paint_layer->ClippingContainer(); state.SetClip( clipping_container ? clipping_container->FirstFragment().ContentsProperties().Clip() : ClipPaintPropertyNode::Root()); squashing_layer->SetLayerState( state, snapped_paint_offset + mapping->SquashingLayerOffsetFromLayoutObject()); } if (auto* mask_layer = mapping->MaskLayer()) { auto state = fragment_data.LocalBorderBoxProperties(); const auto* properties = fragment_data.PaintProperties(); DCHECK(properties && properties->Mask()); state.SetEffect(properties->Mask()); state.SetClip(properties->MaskClip()); mask_layer->SetLayerState( state, snapped_paint_offset + mask_layer->OffsetFromLayoutObject()); } if (auto* ancestor_clipping_mask_layer = mapping->AncestorClippingMaskLayer()) { PropertyTreeState state( fragment_data.PreTransform(), mapping->ClipInheritanceAncestor() ->GetLayoutObject() .FirstFragment() .PostOverflowClip(), // This is a hack to incorporate mask-based clip-path. Really should be // nullptr or some dummy. fragment_data.PreFilter()); ancestor_clipping_mask_layer->SetLayerState( state, snapped_paint_offset + ancestor_clipping_mask_layer->OffsetFromLayoutObject()); } if (auto* child_clipping_mask_layer = mapping->ChildClippingMaskLayer()) { PropertyTreeState state = fragment_data.LocalBorderBoxProperties(); // Same hack as for ancestor_clipping_mask_layer. state.SetEffect(fragment_data.PreFilter()); child_clipping_mask_layer->SetLayerState( state, snapped_paint_offset + child_clipping_mask_layer->OffsetFromLayoutObject()); } } } // namespace blink
2,780
4,054
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.node.admin.configserver.noderepository; import java.time.Instant; import java.util.Objects; /** * @author mortent */ public class TrustStoreItem { private final String fingerprint; private final Instant expiry; public TrustStoreItem(String fingerprint, Instant expiry) { this.fingerprint = fingerprint; this.expiry = expiry; } public String fingerprint() { return fingerprint; } public Instant expiry() { return expiry; } @Override public String toString() { return "TrustStoreItem{" + "fingerprint='" + fingerprint + '\'' + ", expiry=" + expiry + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TrustStoreItem that = (TrustStoreItem) o; return Objects.equals(fingerprint, that.fingerprint) && Objects.equals(expiry, that.expiry); } @Override public int hashCode() { return Objects.hash(fingerprint, expiry); } }
482
562
#include <stdlib.h> #include <stdio.h> #include "glib.h" #include "gmodule.h" #include "gio/gio.h" void test_gmodule() { if (g_module_supported()) printf("gmodule supported\n"); else printf("gmodule not supported\n"); } void test_glib() { GQueue *queue = g_queue_new(); if (!g_queue_is_empty(queue)) { return; } g_queue_push_tail(queue, "Alice"); g_queue_push_tail(queue, "Bob"); g_queue_push_tail(queue, "Fred"); printf("head: %s\n", (const char *)g_queue_peek_head(queue)); printf("tail: %s\n", (const char *)g_queue_peek_tail(queue)); printf("length: %d\n", g_queue_get_length(queue)); printf("pop: %s\n", (const char *)g_queue_pop_head(queue)); printf("length: %d\n", g_queue_get_length(queue)); printf("head: %s\n", (const char *)g_queue_peek_head(queue)); g_queue_push_head(queue, "<NAME>"); printf("length: %d\n", g_queue_get_length(queue)); printf("head: %s\n", (const char *)g_queue_peek_head(queue)); g_queue_free(queue); } void test_gio() { GInetAddress *add = g_inet_address_new_any(G_SOCKET_FAMILY_IPV4); printf("Any ipv4 address: %s\n", g_inet_address_to_string(add)); g_object_unref(add); } void test_gthread() { GMutex m; g_mutex_init(&m); g_mutex_lock(&m); g_mutex_unlock(&m); g_mutex_clear(&m); } void test_gobject() { printf("type name for char: %s\n", g_type_name(G_TYPE_CHAR)); } int main(int argc, char **argv) { printf("glib %d.%d.%d\n", glib_major_version, glib_minor_version, glib_micro_version); printf("glib interface age: %d\n", glib_interface_age); printf("glib binary age: %d\n", glib_binary_age); test_glib(); test_gmodule(); test_gio(); test_gthread(); test_gobject(); return EXIT_SUCCESS; }
824
634
from datetime import datetime from functools import reduce import operator from django.contrib.auth.models import Group, Permission from django.db.models import Q from django.urls import reverse from django.utils.crypto import get_random_string from django.utils.http import urlencode from django.test import TestCase, override_settings from zentral.contrib.inventory.models import MachineSnapshotCommit from accounts.models import User @override_settings(STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage') class MacOSAppsViewsTestCase(TestCase): @classmethod def setUpTestData(cls): # user cls.user = User.objects.create_user("godzilla", "<EMAIL>", get_random_string()) cls.group = Group.objects.create(name=get_random_string()) cls.user.groups.set([cls.group]) # machine snapshot cls.computer_name = "yolozulu" source = {"module": "tests.zentral.io", "name": "Zentral Tests"} tree = { "source": source, "business_unit": {"name": "yo bu", "reference": "bu1", "source": source, "links": [{"anchor_text": "bu link", "url": "http://bu-link.de"}]}, "groups": [{"name": "yo grp", "reference": "grp1", "source": source, "links": [{"anchor_text": "group link", "url": "http://group-link.de"}]}], "serial_number": "0123456789", "system_info": {"computer_name": cls.computer_name}, "os_version": {'name': 'OS X', 'major': 10, 'minor': 11, 'patch': 1}, "osx_app_instances": [ {'app': {'bundle_id': 'io.zentral.baller', 'bundle_name': 'Baller.app', 'bundle_version': '123', 'bundle_version_str': '1.2.3'}, 'bundle_path': "/Applications/Baller.app", 'signed_by': { "common_name": "Developer ID Application: GODZILLA", "organization": "GOZILLA INC", "organizational_unit": "ATOM", "sha_1": 40 * "a", "sha_256": 64 * "a", "valid_from": datetime(2015, 1, 1), "valid_until": datetime(2026, 1, 1), "signed_by": { "common_name": "Developer ID Certification Authority", "organization": "Apple Inc.", "organizational_unit": "Apple Certification Authority", "sha_1": "3b166c3b7dc4b751c9fe2afab9135641e388e186", "sha_256": "7afc9d01a62f03a2de9637936d4afe68090d2de18d03f29c88cfb0b1ba63587f", "valid_from": datetime(2012, 12, 1), "valid_until": datetime(2027, 12, 1), "signed_by": { "common_name": "<NAME>", "organization": "Apple Inc.", "organizational_unit": "Apple Certification Authority", "sha_1": "611e5b662c593a08ff58d14ae22452d198df6c60", "sha_256": "b0b1730ecbc7ff4505142c49f1295e6eda6bcaed7e2c68c5be91b5a11001f024", "valid_from": datetime(2006, 4, 25), "valid_until": datetime(2035, 2, 9) } } }} ] } _, cls.ms = MachineSnapshotCommit.objects.commit_machine_snapshot_tree(tree) cls.osx_app_instance = cls.ms.osx_app_instances.all()[0] cls.osx_app = cls.osx_app_instance.app # utility methods def _login_redirect(self, url): response = self.client.get(url) self.assertRedirects(response, "{u}?next={n}".format(u=reverse("login"), n=url)) def _login(self, *permissions): if permissions: permission_filter = reduce(operator.or_, ( Q(content_type__app_label=app_label, codename=codename) for app_label, codename in ( permission.split(".") for permission in permissions ) )) self.group.permissions.set(list(Permission.objects.filter(permission_filter))) else: self.group.permissions.clear() self.client.force_login(self.user) # macos pass def test_macos_apps_redirect(self): self._login_redirect(reverse("inventory:macos_apps")) def test_macos_apps_permission_denied(self): self._login() response = self.client.get(reverse("inventory:macos_apps")) self.assertEqual(response.status_code, 403) def test_macos_apps(self): self._login("inventory.view_osxapp", "inventory.view_osxappinstance") response = self.client.get(reverse("inventory:macos_apps")) self.assertContains(response, "Search macOS applications", status_code=200) def test_macos_apps_bundle_name(self): self._login("inventory.view_osxapp", "inventory.view_osxappinstance") response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"bundle_name": "baller"}) )) self.assertContains(response, "1 result") response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"bundle_name": "yolo"}) )) self.assertContains(response, "0 results") def test_macos_apps_bundle_name_and_source_search(self): self._login("inventory.view_osxapp", "inventory.view_osxappinstance") response = self.client.get("{}?{}".format( reverse("inventory:macos_apps"), urlencode({"bundle_name": "baller", "source": self.ms.source.id}) )) self.assertContains(response, "1 result") def test_macos_app(self): self._login("inventory.view_osxapp", "inventory.view_osxappinstance") response = self.client.get(reverse("inventory:macos_app", args=(self.osx_app.id,))) self.assertContains(response, "Baller.app 1.2.3") self.assertContains(response, "1 application instance") self.assertContains(response, self.osx_app_instance.signed_by.sha_256) def test_macos_app_instance_machines(self): self._login("inventory.view_osxapp", "inventory.view_osxappinstance", "inventory.view_machinesnapshot") response = self.client.get(reverse("inventory:macos_app_instance_machines", args=(self.osx_app.id, self.osx_app_instance.id)), follow=True) self.assertContains(response, "Baller.app 1.2.3") self.assertContains(response, "1 Machine") self.assertContains(response, self.osx_app_instance.signed_by.sha_256) self.assertContains(response, self.computer_name)
3,655
421
#ifndef FOOLGO_SRC_DEEP_LEARNING #define FOOLGO_SRC_DEEP_LEARNING #include "board/full_board.h" namespace foolgo { template<BoardLen BOARD_LEN> struct Sample { FullBoard<BOARD_LEN> full_board; PositionIndex position_index; Sample() = default; Sample(const Sample &sample) : position_index(sample.position_index) { full_board.Copy(sample.full_board); } }; } #endif
149
1,253
// // FILE: FastShiftOut.cpp // AUTHOR: <NAME> // VERSION: 0.2.4 // PURPOSE: ShiftOut that implements the Print interface // DATE: 2013-08-22 // URL: https://github.com/RobTillaart/FastShiftOut #include "FastShiftOut.h" FastShiftOut::FastShiftOut(const uint8_t datapin, const uint8_t clockpin, const uint8_t bitOrder) { _bitorder = bitOrder; pinMode(datapin, OUTPUT); pinMode(clockpin, OUTPUT); // https://www.arduino.cc/reference/en/language/functions/advanced-io/shiftout/ digitalWrite(clockpin, LOW); // assume rising pulses from clock #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_MEGAAVR) // uint8_t _datatimer = digitalPinToTimer(datapin); // if (_datatimer != NOT_ON_TIMER) turnOffPWM(_datatimer); TODO uint8_t _dataport = digitalPinToPort(datapin); _dataout = portOutputRegister(_dataport); _databit = digitalPinToBitMask(datapin); // uint8_t _clocktimer = digitalPinToTimer(clockpin); // if (_clocktimer != NOT_ON_TIMER) turnOffPWM(_clocktimer); uint8_t _clockport = digitalPinToPort(clockpin); _clockout = portOutputRegister(_clockport); _clockbit = digitalPinToBitMask(clockpin); #else // reference implementation // reuse these vars as pin to save some space _databit = datapin; _clockbit = clockpin; #endif } size_t FastShiftOut::write(const uint8_t data) { _value = data; if (_bitorder == LSBFIRST) { return writeLSBFIRST(data); } return writeMSBFIRST(data); } size_t FastShiftOut::writeLSBFIRST(const uint8_t data) { #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_MEGAAVR) uint8_t cbmask1 = _clockbit; uint8_t cbmask2 = ~_clockbit; uint8_t dbmask1 = _databit; uint8_t dbmask2 = ~_databit; for (uint8_t i = 0, m = 1; i < 8; i++) { uint8_t oldSREG = SREG; noInterrupts(); if ((data & m) == 0) *_dataout &= dbmask2; else *_dataout |= dbmask1; *_clockout |= cbmask1; *_clockout &= cbmask2; SREG = oldSREG; m <<= 1; } return 1; #else shiftOut(_databit, _clockbit, LSBFIRST, data); return 1; #endif } size_t FastShiftOut::writeMSBFIRST(const uint8_t data) { #if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_MEGAAVR) uint8_t cbmask1 = _clockbit; uint8_t cbmask2 = ~_clockbit; uint8_t dbmask1 = _databit; uint8_t dbmask2 = ~_databit; for (uint8_t i = 0, n = 128; i < 8; i++) { uint8_t oldSREG = SREG; noInterrupts(); if ((data & n) == 0) *_dataout &= dbmask2; else *_dataout |= dbmask1; *_clockout |= cbmask1; *_clockout &= cbmask2; SREG = oldSREG; n >>= 1; } return 1; #else // reference implementation // note this has no cli() shiftOut(_databit, _clockbit, MSBFIRST, data); return 1; #endif } bool FastShiftOut::setBitOrder(const uint8_t bitOrder) { if ((bitOrder == LSBFIRST) || (bitOrder == MSBFIRST)) { _bitorder = bitOrder; return true; }; return false; } // -- END OF FILE --
1,260
1,755
<filename>Common/DataModel/Testing/Cxx/TestVectorOperators.cxx<gh_stars>1000+ /*========================================================================= Program: Visualization Toolkit Module: TestVector.cxx Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSetGet.h" #include "vtkVector.h" #include "vtkVectorOperators.h" //------------------------------------------------------------------------------ int TestVectorOperators(int, char*[]) { vtkVector3i vec3i(0, 6, 9); // Store up any errors, return non-zero if something fails. int retVal = 0; // Test out vtkVector3i and ensure the ostream operator is working. cout << "vec3i -> " << vec3i << endl; // Test the equality operator. vtkVector3i vec3ia(0, 6, 9); vtkVector3i vec3ib(0, 6, 8); vtkVector<int, 3> vector3f(vec3i.GetData()); vector3f[0] = vector3f[2] = 6; if (!(vec3i == vec3ia)) { cerr << "vec3i == vec3ia failed (are equal, but reported not)." << endl << "vec3i = " << vec3i << ", vec3ia = " << vec3ia << endl; ++retVal; } if (vec3ia == vec3ib) { cerr << "vec3ia == vec3ib failed (are not equal, but reported equal)." << endl << "vec3i = " << vec3i << ", vec3ia = " << vec3ia << endl; ++retVal; } if (vector3f == vec3i) { cerr << "vector3f == vec3ib failed (are not equal, but reported equal)." << endl << "vec3i = " << vector3f << ", vec3ia = " << vec3ia << endl; ++retVal; } // Test the inequality operator. if (vec3i != vec3ia) { cerr << "vec3i != vec3ia (reported as not equal, but are equal)." << endl << "vec3i = " << vec3i << ", vec3ia = " << vec3ia << endl; ++retVal; } // Does the + operator work as expected??? vtkVector3i result = vec3ia + vec3ib; if (result != vtkVector3i(0, 12, 17)) { cerr << "Vector addition operator failed." << endl; cerr << vec3ia << " + " << vec3ib << " = " << result << endl; ++retVal; } // Test the - operator. result = vec3ia - vec3ib; if (result != vtkVector3i(0, 0, 1)) { cerr << "Vector subtraction operator failed." << endl; cerr << vec3ia << " - " << vec3ib << " = " << result << endl; ++retVal; } // Test the * operator. result = vec3ia * vec3ib; if (result != vtkVector3i(0, 36, 72)) { cerr << "Vector multiplication operator failed." << endl; cerr << vec3ia << " * " << vec3ib << " = " << result << endl; ++retVal; } // Test the / operator. vec3i.SetX(1); result = vec3ia / vec3i; if (result != vtkVector3i(0, 1, 1)) { cerr << "Vector division operator failed." << endl; cerr << vec3ia << " / " << vec3i << " = " << result << endl; ++retVal; } // Test the * operator with a scalar. result = vec3ia * 2; if (result != vtkVector3i(0, 12, 18)) { cerr << "Vector multiplication by scalar operator failed." << endl; cerr << vec3ia << " * 2 = " << result << endl; ++retVal; } result = 2 * vec3ia; if (result != vtkVector3i(0, 12, 18)) { cerr << "Vector multiplication by scalar operator failed." << endl; cerr << "2 * " << vec3ia << " = " << result << endl; ++retVal; } // Test the += operator result = vec3ia; result += vec3ib; if (result != vtkVector3i(0, 12, 17)) { cerr << "Vector += operator failed." << endl; cerr << vec3ia << " + " << vec3ib << " = " << result << endl; ++retVal; } // Test the -= operator result = vec3ia; result -= vec3ib; if (result != vtkVector3i(0, 0, 1)) { cerr << "Vector -= operator failed." << endl; cerr << vec3ia << " - " << vec3ib << " = " << result << endl; ++retVal; } return retVal; }
1,536
1,374
package def.dom; public class Text extends CharacterData { public java.lang.String wholeText; native public Text replaceWholeText(java.lang.String content); native public Text splitText(double offset); public static Text prototype; public Text(){} }
79
2,338
// RUN: %check_clang_tidy %s misc-non-copyable-objects %t namespace std { typedef struct FILE {} FILE; } using namespace std; // CHECK-MESSAGES: :[[@LINE+1]]:18: warning: 'f' declared as type 'FILE', which is unsafe to copy; did you mean 'FILE *'? [misc-non-copyable-objects] void g(std::FILE f); struct S { // CHECK-MESSAGES: :[[@LINE+1]]:10: warning: 'f' declared as type 'FILE', which is unsafe to copy; did you mean 'FILE *'? ::FILE f; }; void func(FILE *f) { // CHECK-MESSAGES: :[[@LINE+1]]:13: warning: 'f1' declared as type 'FILE', which is unsafe to copy; did you mean 'FILE *'? std::FILE f1; // match // CHECK-MESSAGES: :[[@LINE+2]]:10: warning: 'f2' declared as type 'FILE', which is unsafe to copy; did you mean 'FILE *'? // CHECK-MESSAGES: :[[@LINE+1]]:15: warning: expression has opaque data structure type 'FILE'; type should only be used as a pointer and not dereferenced ::FILE f2 = *f; // match, match // CHECK-MESSAGES: :[[@LINE+1]]:15: warning: 'f3' declared as type 'FILE', which is unsafe to copy; did you mean 'FILE *'? struct FILE f3; // match // CHECK-MESSAGES: :[[@LINE+1]]:16: warning: expression has opaque data structure type 'FILE'; type should only be used as a pointer and not dereferenced (void)sizeof(*f); // match }
455
2,086
/* * 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.dolphinscheduler.alert; import junit.framework.TestCase; import org.apache.dolphinscheduler.dao.PluginDao; import org.apache.dolphinscheduler.remote.NettyRemotingServer; import org.apache.dolphinscheduler.remote.config.NettyServerConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.powermock.reflect.Whitebox; @RunWith(MockitoJUnitRunner.class) public class AlertServerTest extends TestCase { @InjectMocks private AlertServer alertServer; @Mock private PluginDao pluginDao; @Mock private AlertConfig alertConfig; @Test public void testStart() { Mockito.when(pluginDao.checkPluginDefineTableExist()).thenReturn(true); Mockito.when(alertConfig.getPort()).thenReturn(50053); alertServer.start(); NettyRemotingServer nettyRemotingServer = Whitebox.getInternalState(alertServer, "server"); NettyServerConfig nettyServerConfig = Whitebox.getInternalState(nettyRemotingServer, "serverConfig"); Assert.assertEquals(50053, nettyServerConfig.getListenPort()); } }
694
601
<gh_stars>100-1000 package io.lacuna.artifex.utils.regions; import io.lacuna.artifex.*; import io.lacuna.artifex.Ring2.Result; import io.lacuna.artifex.utils.Combinatorics; import io.lacuna.bifurcan.*; import java.util.Comparator; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Predicate; import static java.lang.Math.abs; public class Clip { public static final BinaryOperator<Arc> SHORTEST_ARC = (x, y) -> x.length() < y.length() ? x : y; // for debug purposes private static final ISet<Vec2> VERTICES = new LinearSet<>(); private static void describe(String prefix, IList<Vec2>... arcs) { for (IList<Vec2> arc : arcs) { arc.forEach(VERTICES::add); System.out.print(prefix + " "); arc.forEach(v -> System.out.print(VERTICES.indexOf(v) + " ")); System.out.println(); } } /** * an Arc is a list of curves, either describing a loop or an edge between two points of intersection */ private final static class Arc extends LinearList<Curve2> { private double length = Double.NaN, area = Double.NaN; double length() { if (Double.isNaN(length)) { length = stream().mapToDouble(c -> c.end().sub(c.start()).length()).sum(); } return length; } double signedArea() { if (Double.isNaN(area)) { area = stream().mapToDouble(Curve2::signedArea).sum(); } return area; } Vec2 head() { return first().start(); } Vec2 tail() { return last().end(); } Vec2 position(double t) { double length = length(), offset = 0, threshold = length * t; for (Curve2 c : this) { double l = c.end().sub(c.start()).length(); Interval i = new Interval(offset, offset + l); if (i.contains(threshold)) { return c.position(i.normalize(threshold)); } offset = i.hi; } throw new IllegalStateException(); } Arc reverse() { Arc result = new Arc(); forEach(c -> result.addFirst(c.reverse())); return result; } IList<Vec2> vertices() { IList<Vec2> result = new LinearList<Vec2>().addLast(head()); forEach(c -> result.addLast(c.end())); return result; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object obj) { return this == obj; } } private static double area(IList<Arc> arcs) { return abs(arcs.stream().mapToDouble(Arc::signedArea).sum()); } private static double length(IList<Arc> arcs) { return abs(arcs.stream().mapToDouble(Arc::length).sum()); } private static Ring2 ring(IList<Arc> arcs) { IList<Curve2> acc = new LinearList<>(); arcs.forEach(arc -> arc.forEach(acc::addLast)); return new Ring2(acc); } private static Arc arc(Curve2... cs) { Arc result = new Arc(); for (Curve2 c : cs) { result.addLast(c); } return result; } private static <U, V> IList<V> edges(IList<U> vertices, BiFunction<U, U, V> edge) { IList<V> result = new LinearList<>(); for (int i = 0; i < vertices.size() - 1; i++) { result.addLast(edge.apply(vertices.nth(i), vertices.nth(i + 1))); } return result; } // The approach used here is described at https://ideolalia.com/2018/08/28/artifex.html. The "simplest" approach would // be to represent the unused segments as a multi-graph (since there can be multiple segments connecting any pair of vertices), // but the graph data structure used here is *not* a multi-graph, so instead we model it as a graph which only includes // the shortest edge between the vertices, and we just iterate over it multiple times. Empirically 2-3 times should // always suffice, but we give ourselves a bit of breathing room because mostly we just want to preclude an infinite loop. private static final int MAX_REPAIR_ATTEMPTS = 10; private enum Operation { UNION, INTERSECTION, DIFFERENCE } private enum Type { OUTSIDE, INSIDE, SAME_EDGE, DIFF_EDGE } private static boolean isTop(Curve2 c) { if (c == null) { return false; } double delta = c.end().x - c.start().x; if (delta == 0) { return c.end().y > c.start().y; } return delta < 0; } private static Type classify(Region2 region, Arc arc) { // we want some point near the middle of the arc which is unlikely to coincide with a vertex, because those // sometimes sit ambiguously on the edge of the other region Result result = region.test(arc.position(1.0 / Math.E)); if (!result.inside) { return Type.OUTSIDE; } else if (result.curve == null) { return Type.INSIDE; } else { return isTop(arc.first()) == isTop(result.curve) ? Type.SAME_EDGE : Type.DIFF_EDGE; } } /** * Cuts the rings of a region at the specified vertices, yielding a list of arcs that will serve as the edges of our * graph. */ private static IList<Arc> partition(Region2 region, ISet<Vec2> vertices) { IList<Arc> result = new LinearList<>(); for (Ring2 r : region.rings) { Curve2[] cs = r.curves; int offset = 0; for (; offset < cs.length; offset++) { if (vertices.contains(cs[offset].start())) { break; } } if (offset == cs.length) { result.addLast(arc(cs)); } else { Arc acc = new Arc(); for (int i = offset; i < cs.length; i++) { Curve2 c = cs[i]; if (vertices.contains(c.start())) { if (acc.size() > 0) { result.addLast(acc); } acc = arc(c); } else { acc.addLast(c); } } for (int i = 0; i < offset; i++) { acc.addLast(cs[i]); } if (acc.size() > 0) { result.addLast(acc); } } } return result; } private static IList<IList<Arc>> greedyPairing(IGraph<Vec2, Arc> graph, IList<Vec2> out, ISet<Vec2> in) { IList<IList<Arc>> result = new LinearList<>(); ISet<Vec2> currIn = in.clone(); for (Vec2 v : out) { // this will only happen if a vertex needs to have multiple edges added/removed, but we'll just get it on the // next time around if (currIn.size() == 0) { break; } IList<Vec2> path = Graphs.shortestPath(graph, v, currIn::contains, e -> e.value().length()).orElse(null); if (path == null) { return null; } currIn.remove(path.last()); result.addLast(edges(path, graph::edge)); } return result; } private static IList<IList<Arc>> repairGraph(IGraph<Vec2, ISet<Arc>> graph, Iterable<Arc> unused) { // create a graph of all the unused arcs IGraph<Vec2, Arc> search = new DirectedGraph<Vec2, Arc>().linear(); for (Arc arc : unused) { search.link(arc.head(), arc.tail(), arc, SHORTEST_ARC); } // add in the existing arcs as reversed edges, so we can potentially retract them for (IEdge<Vec2, ISet<Arc>> e : graph.edges()) { Arc arc = e.value().stream().min(Comparator.comparingDouble(Arc::length)).get(); search.link(arc.tail(), arc.head(), arc, SHORTEST_ARC); } //search.vertices().forEach(v -> System.out.println(VERTICES.indexOf(v) + " " + search.out(v).stream().map(VERTICES::indexOf).collect(Lists.linearCollector()))); //graph.vertices().forEach(v -> System.out.println(VERTICES.indexOf(v) + " " + graph.out(v).stream().map(VERTICES::indexOf).collect(Lists.linearCollector()))); ISet<Vec2> in = graph.vertices().stream().filter(v -> graph.in(v).size() == 0).collect(Sets.linearCollector()), out = graph.vertices().stream().filter(v -> graph.out(v).size() == 0).collect(Sets.linearCollector()), currIn = in.clone(), currOut = out.clone(); // attempt to greedily pair our outs and ins ISet<IList<Arc>> result = new LinearSet<>(); while (currIn.size() > 0 && currOut.size() > 0) { IList<Vec2> path = Graphs.shortestPath(search, currOut, in::contains, e -> e.value().length()).orElse(null); // if our search found a vertex that was previously claimed, we need something better than a greedy search if (path == null || !currIn.contains(path.last())) { break; } else { currOut.remove(path.first()); currIn.remove(path.last()); result.add(edges(path, search::edge)); } } if (currIn.size() == 0 || currOut.size() == 0) { return result.elements(); } // Do greedy pairings with every possible vertex ordering, and choose the one that results in the shortest aggregate // paths. If `out` is sufficiently large, `permutations` will just return a subset of random shufflings, and it's // possible we won't find a single workable solution this time around. return Combinatorics.permutations(out.elements()) .stream() .map(vs -> greedyPairing(search, vs, in)) .filter(Objects::nonNull) .min(Comparator.comparingDouble(path -> path.stream().mapToDouble(Clip::length).sum())) .orElseGet(LinearList::new); } public static Region2 operation(Region2 ra, Region2 rb, Operation operation, Predicate<Type> aPredicate, Predicate<Type> bPredicate) { Split.Result split = Split.split(ra, rb); Region2 a = split.a; Region2 b = split.b; // Partition rings into arcs separated at intersection points IList<Arc> pa = partition(a, split.splits), pb = partition(b, split.splits); if (operation == Operation.DIFFERENCE) { pb = pb.stream().map(Arc::reverse).collect(Lists.linearCollector()); } // Filter out arcs which are to be ignored, per our operation ISet<Arc> arcs = new LinearSet<>(); pa.stream() .filter(arc -> aPredicate.test(classify(b, arc))) .forEach(arcs::add); pb.stream() .filter(arc -> bPredicate.test(classify(a, arc))) .forEach(arcs::add); /* describe("split", split.splits.elements()); describe("arcs", arcs.elements().stream().map(Arc::vertices).toArray(IList[]::new)); VERTICES.forEach(v -> System.out.println(VERTICES.indexOf(v) + " " + v)); //*/ IList<Ring2> result = new LinearList<>(); ISet<Arc> consumed = new LinearSet<>(); // First we're going to extract complete cycles, and then try to iteratively repair the graph for (int i = 0; i < MAX_REPAIR_ATTEMPTS; i++) { // Construct a graph where the edges are the set of all arcs connecting the vertices IGraph<Vec2, ISet<Arc>> graph = new DirectedGraph<Vec2, ISet<Arc>>().linear(); arcs.forEach(arc -> graph.link(arc.head(), arc.tail(), LinearSet.of(arc), ISet::union)); //graph.vertices().forEach(v -> System.out.println(VERTICES.indexOf(v) + " " + graph.out(v).stream().map(VERTICES::indexOf).collect(Lists.linearCollector()))); if (i > 0) { for (IList<Arc> path : repairGraph(graph, LinearSet.from(pa.concat(pb)).difference(arcs).difference(consumed))) { for (Arc arc : path) { // if the graph currently contains the arc, remove it if (arcs.contains(arc)) { //describe("remove", arc.vertices()); graph.unlink(arc.head(), arc.tail()); arcs.remove(arc); // if the graph doesn't contain the arc, add it } else { //describe("add", arc.vertices()); graph.link(arc.head(), arc.tail(), LinearSet.of(arc)); arcs.add(arc); } } } } // find every cycle in the graph, and then expand those cycles into every possible arc combination, yielding a bunch // of rings ordered from largest to smallest IList<IList<Arc>> cycles = Graphs.cycles(graph) .stream() .map(cycle -> edges(cycle, (x, y) -> graph.edge(x, y).elements())) .map(Combinatorics::combinations) .flatMap(IList::stream) .sorted(Comparator.comparingDouble(Clip::area).reversed()) .collect(Lists.linearCollector()); // extract as many cycles as possible without using the same arc twice for (IList<Arc> cycle : cycles) { //describe("cycle", cycle.stream().map(Arc::vertices).toArray(IList[]::new)); if (cycle.stream().anyMatch(consumed::contains)) { continue; } cycle.forEach(consumed::add); result.addLast(ring(cycle)); } arcs = arcs.difference(consumed); if (arcs.size() == 0) { break; } } assert arcs.size() == 0; return new Region2(result); } /// public static Region2 union(Region2 a, Region2 b) { return operation(a, b, Operation.UNION, t -> t == Type.OUTSIDE || t == Type.SAME_EDGE, t -> t == Type.OUTSIDE); } public static Region2 intersection(Region2 a, Region2 b) { return operation(a, b, Operation.INTERSECTION, t -> t == Type.INSIDE || t == Type.SAME_EDGE, t -> t == Type.INSIDE); } public static Region2 difference(Region2 a, Region2 b) { return operation(a, b, Operation.DIFFERENCE, t -> t == Type.OUTSIDE || t == Type.DIFF_EDGE, t -> t == Type.INSIDE); } }
5,434
2,494
<reponame>ktrzeciaknubisa/jxcore-binary-packaging // Copyright & License details are available under JXCORE_LICENSE file #include "wrappers/fs_event_wrap.h" #include <stdlib.h> #include "jx/commons.h" namespace node { FSEventWrap::FSEventWrap(JS_HANDLE_OBJECT_REF object) : HandleWrap(object, (uv_handle_t*)&handle_) { handle_.data = static_cast<void*>(this); initialized_ = false; } FSEventWrap::~FSEventWrap() { assert(initialized_ == false); } JS_METHOD(FSEventWrap, New) { JS_CLASS_NEW_INSTANCE(obj, FSEvent); new FSEventWrap(obj); RETURN_POINTER(obj); } JS_METHOD_END JS_METHOD_NO_COM(FSEventWrap, Start) { ENGINE_UNWRAP(FSEventWrap); if (args.Length() < 1 || !args.IsString(0)) { THROW_EXCEPTION("FSEventWrap - Start : Bad arguments"); } uv_loop_t* loop = com->loop; jxcore::JXString jxs; args.GetString(0, &jxs); int r = uv_fs_event_init(loop, &wrap->handle_, *jxs, OnEvent, 0); if (r == 0) { // Check for persistent argument if (!args.GetBoolean(1)) { uv_unref(reinterpret_cast<uv_handle_t*>(&wrap->handle_)); } wrap->initialized_ = true; } else { SetErrno(uv_last_error(loop)); } RETURN_PARAM(STD_TO_INTEGER(r)); } JS_METHOD_END void FSEventWrap::OnEvent(uv_fs_event_t* handle, const char* filename, int events, int status) { FSEventWrap* wrap = static_cast<FSEventWrap*>(handle->data); commons* com = wrap->com; JS_ENTER_SCOPE_WITH(com->node_isolate); JS_LOCAL_STRING eventStr; JS_DEFINE_STATE_MARKER(com); assert(JS_IS_EMPTY((wrap->object_)) == false); // We're in a bind here. libuv can set both UV_RENAME and UV_CHANGE but // the Node API only lets us pass a single event to JS land. // // The obvious solution is to run the callback twice, once for each event. // However, since the second event is not allowed to fire if the handle is // closed after the first event, and since there is no good way to detect // closed handles, that option is out. // // For now, ignore the UV_CHANGE event if UV_RENAME is also set. Make the // assumption that a rename implicitly means an attribute change. Not too // unreasonable, right? Still, we should revisit this before v1.0. if (status) { SetErrno(uv_last_error(com->loop)); eventStr = STD_TO_STRING(""); } else if (events & UV_RENAME) { eventStr = STD_TO_STRING("rename"); } else if (events & UV_CHANGE) { eventStr = STD_TO_STRING("change"); } else { assert(0 && "bad fs events flag"); abort(); } JS_LOCAL_VALUE fn_value; if (filename) fn_value = static_cast<JS_LOCAL_VALUE>(STD_TO_STRING(filename)); else fn_value = JS_NULL(); #ifdef JS_ENGINE_V8 __JS_LOCAL_VALUE argv[3] = {STD_TO_INTEGER(status), eventStr, fn_value}; #elif defined(JS_ENGINE_MOZJS) __JS_LOCAL_VALUE argv[3] = {JS::Int32Value(status), eventStr.GetRawValue(), fn_value.GetRawValue()}; #endif JS_LOCAL_OBJECT lobj = JS_OBJECT_FROM_PERSISTENT(wrap->object_); MakeCallback(com, lobj, JS_PREDEFINED_STRING(onchange), ARRAY_SIZE(argv), argv); } JS_METHOD_NO_COM(FSEventWrap, Close) { ENGINE_UNWRAP(FSEventWrap); if (wrap == NULL || wrap->initialized_ == false) { RETURN(); } wrap->initialized_ = false; #ifdef JS_ENGINE_V8 #ifdef V8_IS_3_28 HandleWrap::Close(p___args); #else RETURN_PARAM(HandleWrap::Close(p___args)); #endif #elif defined(JS_ENGINE_MOZJS) return HandleWrap::Close(JS_GET_STATE_MARKER(), __argc, __jsval); #endif } JS_METHOD_END } // namespace node NODE_MODULE(node_fs_event_wrap, node::FSEventWrap::Initialize)
1,478
324
<filename>providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualMachineScaleSetApiLiveTest.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.jclouds.azurecompute.arm.features; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jclouds.azurecompute.arm.domain.Extension; import org.jclouds.azurecompute.arm.domain.ExtensionProfile; import org.jclouds.azurecompute.arm.domain.ExtensionProfileSettings; import org.jclouds.azurecompute.arm.domain.ExtensionProperties; import org.jclouds.azurecompute.arm.domain.IdReference; import org.jclouds.azurecompute.arm.domain.ImageReference; import org.jclouds.azurecompute.arm.domain.IpConfiguration; import org.jclouds.azurecompute.arm.domain.IpConfigurationProperties; import org.jclouds.azurecompute.arm.domain.ManagedDiskParameters; import org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard; import org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties; import org.jclouds.azurecompute.arm.domain.NetworkInterfaceConfiguration; import org.jclouds.azurecompute.arm.domain.NetworkInterfaceConfigurationProperties; import org.jclouds.azurecompute.arm.domain.NetworkProfile; import org.jclouds.azurecompute.arm.domain.OSDisk; import org.jclouds.azurecompute.arm.domain.StorageProfile; import org.jclouds.azurecompute.arm.domain.Subnet; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSet; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetDNSSettings; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetIpConfiguration; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetIpConfigurationProperties; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetNetworkProfile; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetNetworkSecurityGroup; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetOSProfile; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetProperties; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetPublicIPAddressConfiguration; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetPublicIPAddressProperties; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetSKU; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetUpgradePolicy; import org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetVirtualMachineProfile; import org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; @Test(groups = "live", testName = "VirtualMachineScaleSetApiLiveTest") public class VirtualMachineScaleSetApiLiveTest extends BaseAzureComputeApiLiveTest { private String subscriptionid; private String vmssName; private String virtualNetworkName; private String subnetId; private Subnet subnet; @BeforeClass @Override public void setup() { super.setup(); subscriptionid = getSubscriptionId(); createTestResourceGroup(); //BASE: Creates a random resource group using the properties location virtualNetworkName = String.format("vn-%s-%s", this.getClass().getSimpleName().toLowerCase(), System.getProperty("user.name")); // Subnets belong to a virtual network so that needs to be created first assertNotNull(createDefaultVirtualNetwork(resourceGroupName, virtualNetworkName, "10.2.0.0/16", LOCATION)); //Subnet needs to be up & running before NIC can be created String subnetName = String.format("s-%s-%s", this.getClass().getSimpleName().toLowerCase(), System.getProperty("user.name")); this.subnet = createDefaultSubnet(resourceGroupName, subnetName, virtualNetworkName, "10.2.0.0/23"); assertNotNull(subnet); assertNotNull(subnet.id()); this.subnetId = subnet.id(); vmssName = String.format("%3.24s", System.getProperty("user.name") + RAND + this.getClass().getSimpleName()).toLowerCase().substring(0, 15); } private VirtualMachineScaleSetApi api() { return api.getVirtualMachineScaleSetApi(resourceGroupName); } @Test public void testCreate() { VirtualMachineScaleSet vmss = api().createOrUpdate(vmssName, LOCATIONDESCRIPTION, getSKU(), Collections.<String, String>emptyMap(), getProperties()); assertTrue(!vmss.name().isEmpty()); // waitUntilReady(vmssName); } @Test(dependsOnMethods = "testCreate") public void testList() throws InterruptedException { final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourceGroupName); assertEquals(vmssAPI.list().size(), 1); } @Test(dependsOnMethods = "testList") public void testGet() { final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourceGroupName); assertEquals(vmssAPI.get(vmssName).name(), vmssName); } @Test(dependsOnMethods = "testGet", alwaysRun = true) public void testDelete() throws Exception { final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourceGroupName); URI uri = vmssAPI.delete(vmssName); assertResourceDeleted(uri); } protected void assertResourceDeleted(URI uri) { if (uri != null) { assertTrue(resourceDeleted.apply(uri), String.format("Resource %s was not terminated in the configured timeout", uri)); } } /** * Create a standard SKU * * @return VirtualMachineScaleSetSKU */ public VirtualMachineScaleSetSKU getSKU() { return VirtualMachineScaleSetSKU.create("Standard_A1", "Standard", 10); } private VirtualMachineScaleSetUpgradePolicy getUpgradePolicy() { return VirtualMachineScaleSetUpgradePolicy.create("Manual"); } private StorageProfile getLinuxStorageProfile_Default() { return StorageProfile.create(getLinuxImageReference(), getLinuxOSDisk(), null); } private ManagedDiskParameters getManagedDiskParameters() { return ManagedDiskParameters.create(null, "Standard_LRS"); } private OSDisk getLinuxOSDisk() { return OSDisk.create("Linux", null, null, null, "FromImage", null, getManagedDiskParameters(), null); } private ImageReference getLinuxImageReference() { return ImageReference.create(null, "Canonical", "UbuntuServer", "16.04-LTS", "latest"); } private VirtualMachineScaleSetOSProfile getOSProfile() { VirtualMachineScaleSetOSProfile.LinuxConfiguration linuxConfiguration = VirtualMachineScaleSetOSProfile.LinuxConfiguration.create(false, null); VirtualMachineScaleSetOSProfile.WindowsConfiguration windowsConfiguration = null; return VirtualMachineScaleSetOSProfile.create(vmssName, "jclouds", "jClouds1!", linuxConfiguration, windowsConfiguration, null); } private VirtualMachineScaleSetNetworkProfile getNetworkProfile() { NetworkInterfaceCard nic = createNetworkInterfaceCard(resourceGroupName, "jc-nic-" + RAND, LOCATION, "ipConfig-" + RAND); assertNotNull(nic); NetworkProfile.NetworkInterface.create(nic.id(), NetworkProfile.NetworkInterface.NetworkInterfaceProperties.create(true)); List<NetworkInterfaceConfiguration> networkInterfaceConfigurations = new ArrayList<NetworkInterfaceConfiguration>(); List<VirtualMachineScaleSetIpConfiguration> virtualMachineScaleSetIpConfigurations = new ArrayList<VirtualMachineScaleSetIpConfiguration>(); VirtualMachineScaleSetPublicIPAddressConfiguration publicIPAddressConfiguration = VirtualMachineScaleSetPublicIPAddressConfiguration.create("pub1", VirtualMachineScaleSetPublicIPAddressProperties.create(15)); VirtualMachineScaleSetIpConfigurationProperties virtualMachineScaleSetIpConfigurationProperties = VirtualMachineScaleSetIpConfigurationProperties.create(publicIPAddressConfiguration, this.subnet, "IPv4", null, null, null); VirtualMachineScaleSetIpConfiguration virtualMachineScaleSetIpConfiguration = VirtualMachineScaleSetIpConfiguration.create("ipconfig1", virtualMachineScaleSetIpConfigurationProperties); virtualMachineScaleSetIpConfigurations.add(virtualMachineScaleSetIpConfiguration); VirtualMachineScaleSetNetworkSecurityGroup networkSecurityGroup = null; ArrayList<String> dnsList = new ArrayList<String>(); dnsList.add("8.8.8.8"); VirtualMachineScaleSetDNSSettings dnsSettings = VirtualMachineScaleSetDNSSettings.create(dnsList); NetworkInterfaceConfigurationProperties networkInterfaceConfigurationProperties = NetworkInterfaceConfigurationProperties.create(true, false, networkSecurityGroup, dnsSettings, virtualMachineScaleSetIpConfigurations); NetworkInterfaceConfiguration networkInterfaceConfiguration = NetworkInterfaceConfiguration.create("nicconfig1", networkInterfaceConfigurationProperties); networkInterfaceConfigurations.add(networkInterfaceConfiguration); return VirtualMachineScaleSetNetworkProfile.create(networkInterfaceConfigurations); } private ExtensionProfile getExtensionProfile() { List<Extension> extensions = new ArrayList<Extension>(); List<String> uris = new ArrayList<String>(); uris.add("https://mystorage1.blob.core.windows.net/winvmextekfacnt/SampleCmd_1.cmd"); ExtensionProfileSettings extensionProfileSettings = ExtensionProfileSettings.create(uris, "SampleCmd_1.cmd"); Map<String, String> protectedSettings = new HashMap<String, String>(); protectedSettings.put("StorageAccountKey", "jclouds-accountkey"); ExtensionProperties extensionProperties = ExtensionProperties.create("Microsoft.compute", "CustomScriptExtension", "1.1", false, extensionProfileSettings, protectedSettings); Extension extension = Extension.create("extensionName", extensionProperties); extensions.add(extension); return ExtensionProfile.create(extensions); } private VirtualMachineScaleSetVirtualMachineProfile getVirtualMachineProfile() { return VirtualMachineScaleSetVirtualMachineProfile.create(getLinuxStorageProfile_Default(), getOSProfile(), getNetworkProfile(), getExtensionProfile()); } public VirtualMachineScaleSetProperties getProperties() { return VirtualMachineScaleSetProperties.create(null, null, getUpgradePolicy(), null, getVirtualMachineProfile()); } private NetworkInterfaceCard createNetworkInterfaceCard(final String resourceGroupName, String networkInterfaceCardName, String locationName, String ipConfigurationName) { //Create properties object final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties .builder().ipConfigurations(Arrays.asList(IpConfiguration.create(ipConfigurationName, null, null, IpConfigurationProperties .create(null, null, "Dynamic", IdReference.create(subnetId), null, null, null, null)))).build(); final Map<String, String> tags = ImmutableMap.of("jclouds", "livetest"); return api.getNetworkInterfaceCardApi(resourceGroupName).createOrUpdate(networkInterfaceCardName, locationName, networkInterfaceCardProperties, tags); } public String getSubscriptionid() { return subscriptionid; } }
3,823
679
<reponame>Grosskopf/openoffice<filename>main/sw/source/core/doc/docfmt.cxx /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #define _ZFORLIST_DECLARE_TABLE #define _SVSTDARR_USHORTSSORT #define _SVSTDARR_USHORTS #include <hintids.hxx> #include <rtl/logfile.hxx> #include <svl/itemiter.hxx> #include <sfx2/app.hxx> #include <editeng/tstpitem.hxx> #include <editeng/eeitem.hxx> #include <editeng/langitem.hxx> #include <editeng/lrspitem.hxx> #include <editeng/brkitem.hxx> #include <svl/whiter.hxx> #ifndef _ZFORLIST_HXX //autogen #define _ZFORLIST_DECLARE_TABLE #include <svl/zforlist.hxx> #endif #include <comphelper/processfactory.hxx> #include <unotools/misccfg.hxx> #include <com/sun/star/i18n/WordType.hdl> #include <fmtpdsc.hxx> #include <fmthdft.hxx> #include <fmtcntnt.hxx> #include <frmatr.hxx> #include <doc.hxx> #include <IDocumentUndoRedo.hxx> #include <rootfrm.hxx> #include <pagefrm.hxx> #include <hints.hxx> // fuer SwHyphenBug (in SetDefault) #include <ndtxt.hxx> #include <pam.hxx> #include <UndoCore.hxx> #include <UndoAttribute.hxx> #include <ndgrf.hxx> #include <pagedesc.hxx> // Fuer Sonderbehandlung in InsFrmFmt #include <rolbck.hxx> // Undo-Attr #include <mvsave.hxx> // servieren: Veraenderungen erkennen #include <txatbase.hxx> #include <swtable.hxx> #include <swtblfmt.hxx> #include <charfmt.hxx> #include <docary.hxx> #include <paratr.hxx> #include <redline.hxx> #include <reffld.hxx> #include <txtinet.hxx> #include <fmtinfmt.hxx> #include <breakit.hxx> #include <SwStyleNameMapper.hxx> #include <fmtautofmt.hxx> #include <istyleaccess.hxx> #include <SwUndoFmt.hxx> #include <docsh.hxx> using namespace ::com::sun::star::i18n; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::uno; SV_IMPL_PTRARR(SwFrmFmts,SwFrmFmtPtr) SV_IMPL_PTRARR(SwCharFmts,SwCharFmtPtr) //Spezifische Frameformate (Rahmen) SV_IMPL_PTRARR(SwSpzFrmFmts,SwFrmFmtPtr) /* * interne Funktionen */ sal_Bool SetTxtFmtCollNext( const SwTxtFmtCollPtr& rpTxtColl, void* pArgs ) { SwTxtFmtColl *pDel = (SwTxtFmtColl*) pArgs; if ( &rpTxtColl->GetNextTxtFmtColl() == pDel ) { rpTxtColl->SetNextTxtFmtColl( *rpTxtColl ); } return sal_True; } /* * Zuruecksetzen der harten Formatierung fuer Text */ // Uebergabeparameter fuer _Rst und lcl_SetTxtFmtColl struct ParaRstFmt { SwFmtColl* pFmtColl; SwHistory* pHistory; const SwPosition *pSttNd, *pEndNd; const SfxItemSet* pDelSet; sal_uInt16 nWhich; bool bReset; bool bResetListAttrs; bool bResetAll; bool bInclRefToxMark; ParaRstFmt( const SwPosition* pStt, const SwPosition* pEnd, SwHistory* pHst, sal_uInt16 nWhch = 0, const SfxItemSet* pSet = 0 ) : pFmtColl(0), pHistory(pHst), pSttNd(pStt), pEndNd(pEnd), pDelSet(pSet), nWhich(nWhch), bReset( false ), bResetListAttrs( false ), bResetAll( true ), bInclRefToxMark( false ) { } ParaRstFmt( SwHistory* pHst ) : pFmtColl(0), pHistory(pHst), pSttNd(0), pEndNd(0), pDelSet(0), nWhich(0), bReset( false ), bResetListAttrs( false ), bResetAll( true ), bInclRefToxMark( false ) { } }; /* in pArgs steht die ChrFmtTablle vom Dokument * (wird bei Selectionen am Start/Ende und bei keiner SSelection benoetigt) */ sal_Bool lcl_RstTxtAttr( const SwNodePtr& rpNd, void* pArgs ) { ParaRstFmt* pPara = (ParaRstFmt*)pArgs; SwTxtNode * pTxtNode = (SwTxtNode*)rpNd->GetTxtNode(); if( pTxtNode && pTxtNode->GetpSwpHints() ) { SwIndex aSt( pTxtNode, 0 ); sal_uInt16 nEnd = pTxtNode->Len(); if( &pPara->pSttNd->nNode.GetNode() == pTxtNode && pPara->pSttNd->nContent.GetIndex() ) aSt = pPara->pSttNd->nContent.GetIndex(); if( &pPara->pEndNd->nNode.GetNode() == rpNd ) nEnd = pPara->pEndNd->nContent.GetIndex(); if( pPara->pHistory ) { // fuers Undo alle Attribute sichern SwRegHistory aRHst( *pTxtNode, pPara->pHistory ); pTxtNode->GetpSwpHints()->Register( &aRHst ); pTxtNode->RstTxtAttr( aSt, nEnd - aSt.GetIndex(), pPara->nWhich, pPara->pDelSet, pPara->bInclRefToxMark ); if( pTxtNode->GetpSwpHints() ) pTxtNode->GetpSwpHints()->DeRegister(); } else pTxtNode->RstTxtAttr( aSt, nEnd - aSt.GetIndex(), pPara->nWhich, pPara->pDelSet, pPara->bInclRefToxMark ); } return sal_True; } sal_Bool lcl_RstAttr( const SwNodePtr& rpNd, void* pArgs ) { const ParaRstFmt* pPara = (ParaRstFmt*) pArgs; SwCntntNode* pNode = (SwCntntNode*) rpNd->GetCntntNode(); if( pNode && pNode->HasSwAttrSet() ) { const sal_Bool bLocked = pNode->IsModifyLocked(); pNode->LockModify(); SwDoc* pDoc = pNode->GetDoc(); SfxItemSet aSavedAttrsSet( pDoc->GetAttrPool(), RES_PAGEDESC, RES_BREAK, RES_PARATR_NUMRULE, RES_PARATR_NUMRULE, RES_PARATR_LIST_BEGIN, RES_PARATR_LIST_END - 1, 0 ); const SfxItemSet* pAttrSetOfNode = pNode->GetpSwAttrSet(); SvUShorts aClearWhichIds; // restoring all paragraph list attributes { SfxItemSet aListAttrSet( pDoc->GetAttrPool(), RES_PARATR_LIST_BEGIN, RES_PARATR_LIST_END - 1, 0 ); aListAttrSet.Set( *pAttrSetOfNode ); if ( aListAttrSet.Count() ) { aSavedAttrsSet.Put( aListAttrSet ); SfxItemIter aIter( aListAttrSet ); const SfxPoolItem* pItem = aIter.GetCurItem(); while( pItem ) { aClearWhichIds.Insert( pItem->Which(), aClearWhichIds.Count() ); pItem = aIter.NextItem(); } } } const SfxPoolItem* pItem; sal_uInt16 __READONLY_DATA aSavIds[3] = { RES_PAGEDESC, RES_BREAK, RES_PARATR_NUMRULE }; for ( sal_uInt16 n = 0; n < 3; ++n ) { if ( SFX_ITEM_SET == pAttrSetOfNode->GetItemState( aSavIds[n], sal_False, &pItem ) ) { bool bSave = false; switch (aSavIds[n]) { case RES_PAGEDESC: bSave = 0 != ( (SwFmtPageDesc*) pItem )->GetPageDesc(); break; case RES_BREAK: bSave = SVX_BREAK_NONE != ( (SvxFmtBreakItem*) pItem )->GetBreak(); break; case RES_PARATR_NUMRULE: bSave = 0 != ( (SwNumRuleItem*) pItem )->GetValue().Len(); break; } if ( bSave ) { aSavedAttrsSet.Put( *pItem ); aClearWhichIds.Insert( aSavIds[n], aClearWhichIds.Count() ); } } } // do not clear items directly from item set and only clear to be kept // attributes, if no deletion item set is found. const bool bKeepAttributes = !pPara || !pPara->pDelSet || pPara->pDelSet->Count() == 0; if ( bKeepAttributes ) { pNode->ResetAttr( aClearWhichIds ); } if( !bLocked ) pNode->UnlockModify(); if ( pPara ) { SwRegHistory aRegH( pNode, *pNode, pPara->pHistory ); if ( pPara->pDelSet && pPara->pDelSet->Count() ) { ASSERT( !bKeepAttributes, "<lcl_RstAttr(..)> - certain attributes are kept, but not needed. -> please inform OD" ); SfxItemIter aIter( *pPara->pDelSet ); pItem = aIter.FirstItem(); while ( sal_True ) { if ( ( pItem->Which() != RES_PAGEDESC && pItem->Which() != RES_BREAK && pItem->Which() != RES_PARATR_NUMRULE ) || ( aSavedAttrsSet.GetItemState( pItem->Which(), sal_False ) != SFX_ITEM_SET ) ) { pNode->ResetAttr( pItem->Which() ); } if ( aIter.IsAtEnd() ) break; pItem = aIter.NextItem(); } } else if ( pPara->bResetAll ) pNode->ResetAllAttr(); else pNode->ResetAttr( RES_PARATR_BEGIN, POOLATTR_END - 1 ); } else pNode->ResetAllAttr(); // only restore saved attributes, if needed if ( bKeepAttributes && aSavedAttrsSet.Count() ) { pNode->LockModify(); pNode->SetAttr( aSavedAttrsSet ); if ( !bLocked ) pNode->UnlockModify(); } } return sal_True; } void SwDoc::RstTxtAttrs(const SwPaM &rRg, sal_Bool bInclRefToxMark ) { SwHistory* pHst = 0; SwDataChanged aTmp( rRg, 0 ); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndoResetAttr* pUndo = new SwUndoResetAttr( rRg, RES_CHRFMT ); pHst = &pUndo->GetHistory(); GetIDocumentUndoRedo().AppendUndo(pUndo); } const SwPosition *pStt = rRg.Start(), *pEnd = rRg.End(); ParaRstFmt aPara( pStt, pEnd, pHst ); aPara.bInclRefToxMark = ( bInclRefToxMark == sal_True ); GetNodes().ForEach( pStt->nNode.GetIndex(), pEnd->nNode.GetIndex()+1, lcl_RstTxtAttr, &aPara ); SetModified(); } void SwDoc::ResetAttrs( const SwPaM &rRg, sal_Bool bTxtAttr, const SvUShortsSort* pAttrs, // --> OD 2008-11-28 #b96644# const bool bSendDataChangedEvents ) // <-- { SwPaM* pPam = (SwPaM*)&rRg; if( !bTxtAttr && pAttrs && pAttrs->Count() && RES_TXTATR_END > (*pAttrs)[ 0 ] ) bTxtAttr = sal_True; if( !rRg.HasMark() ) { SwTxtNode* pTxtNd = rRg.GetPoint()->nNode.GetNode().GetTxtNode(); if( !pTxtNd ) return ; pPam = new SwPaM( *rRg.GetPoint() ); SwIndex& rSt = pPam->GetPoint()->nContent; sal_uInt16 nMkPos, nPtPos = rSt.GetIndex(); // JP 22.08.96: Sonderfall: steht der Crsr in einem URL-Attribut // dann wird dessen Bereich genommen SwTxtAttr const*const pURLAttr( pTxtNd->GetTxtAttrAt(rSt.GetIndex(), RES_TXTATR_INETFMT)); if (pURLAttr && pURLAttr->GetINetFmt().GetValue().Len()) { nMkPos = *pURLAttr->GetStart(); nPtPos = *pURLAttr->End(); } else { Boundary aBndry; if( pBreakIt->GetBreakIter().is() ) aBndry = pBreakIt->GetBreakIter()->getWordBoundary( pTxtNd->GetTxt(), nPtPos, pBreakIt->GetLocale( pTxtNd->GetLang( nPtPos ) ), WordType::ANY_WORD /*ANYWORD_IGNOREWHITESPACES*/, sal_True ); if( aBndry.startPos < nPtPos && nPtPos < aBndry.endPos ) { nMkPos = (xub_StrLen)aBndry.startPos; nPtPos = (xub_StrLen)aBndry.endPos; } else { nPtPos = nMkPos = rSt.GetIndex(); if( bTxtAttr ) pTxtNd->DontExpandFmt( rSt, sal_True ); } } rSt = nMkPos; pPam->SetMark(); pPam->GetPoint()->nContent = nPtPos; } // --> OD 2008-11-28 #i96644# // SwDataChanged aTmp( *pPam, 0 ); std::auto_ptr< SwDataChanged > pDataChanged; if ( bSendDataChangedEvents ) { pDataChanged.reset( new SwDataChanged( *pPam, 0 ) ); } // <-- SwHistory* pHst = 0; if (GetIDocumentUndoRedo().DoesUndo()) { SwUndoResetAttr* pUndo = new SwUndoResetAttr( rRg, static_cast<sal_uInt16>(bTxtAttr ? RES_CONDTXTFMTCOLL : RES_TXTFMTCOLL )); if( pAttrs && pAttrs->Count() ) { pUndo->SetAttrs( *pAttrs ); } pHst = &pUndo->GetHistory(); GetIDocumentUndoRedo().AppendUndo(pUndo); } const SwPosition *pStt = pPam->Start(), *pEnd = pPam->End(); ParaRstFmt aPara( pStt, pEnd, pHst ); // mst: not including META here; it seems attrs with CH_TXTATR are omitted sal_uInt16 __FAR_DATA aResetableSetRange[] = { RES_FRMATR_BEGIN, RES_FRMATR_END-1, RES_CHRATR_BEGIN, RES_CHRATR_END-1, RES_PARATR_BEGIN, RES_PARATR_END-1, // --> OD 2008-02-25 #refactorlists# RES_PARATR_LIST_BEGIN, RES_PARATR_LIST_END-1, // <-- RES_TXTATR_INETFMT, RES_TXTATR_INETFMT, RES_TXTATR_CHARFMT, RES_TXTATR_CHARFMT, RES_TXTATR_CJK_RUBY, RES_TXTATR_CJK_RUBY, RES_TXTATR_UNKNOWN_CONTAINER, RES_TXTATR_UNKNOWN_CONTAINER, RES_UNKNOWNATR_BEGIN, RES_UNKNOWNATR_END-1, 0 }; SfxItemSet aDelSet( GetAttrPool(), aResetableSetRange ); if( pAttrs && pAttrs->Count() ) { for( sal_uInt16 n = pAttrs->Count(); n; ) if( POOLATTR_END > (*pAttrs)[ --n ] ) aDelSet.Put( *GetDfltAttr( (*pAttrs)[ n ] )); if( aDelSet.Count() ) aPara.pDelSet = &aDelSet; } sal_Bool bAdd = sal_True; SwNodeIndex aTmpStt( pStt->nNode ); SwNodeIndex aTmpEnd( pEnd->nNode ); if( pStt->nContent.GetIndex() ) // nur ein Teil { // dann spaeter aufsetzen und alle CharFmtAttr -> TxtFmtAttr SwTxtNode* pTNd = aTmpStt.GetNode().GetTxtNode(); if( pTNd && pTNd->HasSwAttrSet() && pTNd->GetpSwAttrSet()->Count() ) { if (pHst) { SwRegHistory history(pTNd, *pTNd, pHst); pTNd->FmtToTxtAttr(pTNd); } else { pTNd->FmtToTxtAttr(pTNd); } } aTmpStt++; } if( pEnd->nContent.GetIndex() == pEnd->nNode.GetNode().GetCntntNode()->Len() ) // dann spaeter aufsetzen und alle CharFmtAttr -> TxtFmtAttr aTmpEnd++, bAdd = sal_False; else if( pStt->nNode != pEnd->nNode || !pStt->nContent.GetIndex() ) { SwTxtNode* pTNd = aTmpEnd.GetNode().GetTxtNode(); if( pTNd && pTNd->HasSwAttrSet() && pTNd->GetpSwAttrSet()->Count() ) { if (pHst) { SwRegHistory history(pTNd, *pTNd, pHst); pTNd->FmtToTxtAttr(pTNd); } else { pTNd->FmtToTxtAttr(pTNd); } } } if( aTmpStt < aTmpEnd ) GetNodes().ForEach( pStt->nNode, aTmpEnd, lcl_RstAttr, &aPara ); else if( !rRg.HasMark() ) { aPara.bResetAll = false ; ::lcl_RstAttr( &pStt->nNode.GetNode(), &aPara ); aPara.bResetAll = true ; } if( bTxtAttr ) { if( bAdd ) aTmpEnd++; GetNodes().ForEach( pStt->nNode, aTmpEnd, lcl_RstTxtAttr, &aPara ); } if( pPam != &rRg ) delete pPam; SetModified(); } #define DELETECHARSETS if ( bDelete ) { delete pCharSet; delete pOtherSet; } // Einfuegen der Hints nach Inhaltsformen; // wird in SwDoc::Insert(..., SwFmtHint &rHt) benutzt static bool lcl_InsAttr( SwDoc *const pDoc, const SwPaM &rRg, const SfxItemSet& rChgSet, const SetAttrMode nFlags, SwUndoAttr *const pUndo, //Modify here for #119405, by easyfan, 2012-05-24 const bool bExpandCharToPara=false) //End of modification, by easyfan { // teil die Sets auf (fuer Selektion in Nodes) const SfxItemSet* pCharSet = 0; const SfxItemSet* pOtherSet = 0; bool bDelete = false; bool bCharAttr = false; bool bOtherAttr = false; // Check, if we can work with rChgSet or if we have to create additional SfxItemSets if ( 1 == rChgSet.Count() ) { SfxItemIter aIter( rChgSet ); const SfxPoolItem* pItem = aIter.FirstItem(); if (!IsInvalidItem(pItem)) { const sal_uInt16 nWhich = pItem->Which(); if ( isCHRATR(nWhich) || (RES_TXTATR_CHARFMT == nWhich) || (RES_TXTATR_INETFMT == nWhich) || (RES_TXTATR_AUTOFMT == nWhich) || (RES_TXTATR_UNKNOWN_CONTAINER == nWhich) ) { pCharSet = &rChgSet; bCharAttr = true; } if ( isPARATR(nWhich) || isPARATR_LIST(nWhich) || isFRMATR(nWhich) || isGRFATR(nWhich) || isUNKNOWNATR(nWhich) || isDrawingLayerAttribute(nWhich) ) //UUUU { pOtherSet = &rChgSet; bOtherAttr = true; } } } // Build new itemset if either // - rChgSet.Count() > 1 or // - The attribute in rChgSet does not belong to one of the above categories if ( !bCharAttr && !bOtherAttr ) { SfxItemSet* pTmpCharItemSet = new SfxItemSet( pDoc->GetAttrPool(), RES_CHRATR_BEGIN, RES_CHRATR_END-1, RES_TXTATR_AUTOFMT, RES_TXTATR_AUTOFMT, RES_TXTATR_INETFMT, RES_TXTATR_INETFMT, RES_TXTATR_CHARFMT, RES_TXTATR_CHARFMT, RES_TXTATR_UNKNOWN_CONTAINER, RES_TXTATR_UNKNOWN_CONTAINER, 0 ); SfxItemSet* pTmpOtherItemSet = new SfxItemSet( pDoc->GetAttrPool(), RES_PARATR_BEGIN, RES_PARATR_END-1, RES_PARATR_LIST_BEGIN, RES_PARATR_LIST_END-1, RES_FRMATR_BEGIN, RES_FRMATR_END-1, RES_GRFATR_BEGIN, RES_GRFATR_END-1, RES_UNKNOWNATR_BEGIN, RES_UNKNOWNATR_END-1, //UUUU FillAttribute support XATTR_FILL_FIRST, XATTR_FILL_LAST, 0 ); pTmpCharItemSet->Put( rChgSet ); pTmpOtherItemSet->Put( rChgSet ); pCharSet = pTmpCharItemSet; pOtherSet = pTmpOtherItemSet; bDelete = true; } SwHistory* pHistory = pUndo ? &pUndo->GetHistory() : 0; bool bRet = false; const SwPosition *pStt = rRg.Start(), *pEnd = rRg.End(); SwCntntNode* pNode = pStt->nNode.GetNode().GetCntntNode(); if( pNode && pNode->IsTxtNode() ) { // -> #i27615# if (rRg.IsInFrontOfLabel()) { SwTxtNode * pTxtNd = pNode->GetTxtNode(); SwNumRule * pNumRule = pTxtNd->GetNumRule(); if ( !pNumRule ) { ASSERT( false, "<InsAttr(..)> - PaM in front of label, but text node has no numbering rule set. This is a serious defect, please inform OD." ); DELETECHARSETS return false; } SwNumFmt aNumFmt = pNumRule->Get(static_cast<sal_uInt16>(pTxtNd->GetActualListLevel())); SwCharFmt * pCharFmt = pDoc->FindCharFmtByName(aNumFmt.GetCharFmtName()); if (pCharFmt) { if (pHistory) pHistory->Add(pCharFmt->GetAttrSet(), *pCharFmt); if ( pCharSet ) pCharFmt->SetFmtAttr(*pCharSet); } DELETECHARSETS return true; } const SwIndex& rSt = pStt->nContent; // Attribute ohne Ende haben keinen Bereich if ( !bCharAttr && !bOtherAttr ) { SfxItemSet aTxtSet( pDoc->GetAttrPool(), RES_TXTATR_NOEND_BEGIN, RES_TXTATR_NOEND_END-1 ); aTxtSet.Put( rChgSet ); if( aTxtSet.Count() ) { SwRegHistory history( pNode, *pNode, pHistory ); bRet = history.InsertItems( aTxtSet, rSt.GetIndex(), rSt.GetIndex(), nFlags ) || bRet; if (bRet && (pDoc->IsRedlineOn() || (!pDoc->IsIgnoreRedline() && pDoc->GetRedlineTbl().Count()))) { SwPaM aPam( pStt->nNode, pStt->nContent.GetIndex()-1, pStt->nNode, pStt->nContent.GetIndex() ); if( pUndo ) pUndo->SaveRedlineData( aPam, sal_True ); if( pDoc->IsRedlineOn() ) pDoc->AppendRedline( new SwRedline( nsRedlineType_t::REDLINE_INSERT, aPam ), true); else pDoc->SplitRedline( aPam ); } } } // TextAttribute mit Ende expandieren nie ihren Bereich if ( !bCharAttr && !bOtherAttr ) { // CharFmt wird gesondert behandelt !!! // JP 22.08.96: URL-Attribute auch!! // TEST_TEMP ToDo: AutoFmt! SfxItemSet aTxtSet( pDoc->GetAttrPool(), RES_TXTATR_REFMARK, RES_TXTATR_TOXMARK, RES_TXTATR_META, RES_TXTATR_METAFIELD, RES_TXTATR_CJK_RUBY, RES_TXTATR_CJK_RUBY, RES_TXTATR_INPUTFIELD, RES_TXTATR_INPUTFIELD, 0 ); aTxtSet.Put( rChgSet ); if( aTxtSet.Count() ) { sal_uInt16 nInsCnt = rSt.GetIndex(); sal_uInt16 nEnd = pStt->nNode == pEnd->nNode ? pEnd->nContent.GetIndex() : pNode->Len(); SwRegHistory history( pNode, *pNode, pHistory ); bRet = history.InsertItems( aTxtSet, nInsCnt, nEnd, nFlags ) || bRet; if (bRet && (pDoc->IsRedlineOn() || (!pDoc->IsIgnoreRedline() && pDoc->GetRedlineTbl().Count()))) { // wurde Text-Inhalt eingefuegt? (RefMark/TOXMarks ohne Ende) sal_Bool bTxtIns = nInsCnt != rSt.GetIndex(); // wurde Inhalt eingefuegt oder ueber die Selektion gesetzt? SwPaM aPam( pStt->nNode, bTxtIns ? nInsCnt + 1 : nEnd, pStt->nNode, nInsCnt ); if( pUndo ) pUndo->SaveRedlineData( aPam, bTxtIns ); if( pDoc->IsRedlineOn() ) pDoc->AppendRedline( new SwRedline( bTxtIns ? nsRedlineType_t::REDLINE_INSERT : nsRedlineType_t::REDLINE_FORMAT, aPam ), true); else if( bTxtIns ) pDoc->SplitRedline( aPam ); } } } } // bei PageDesc's, die am Node gesetzt werden, muss immer das // Auto-Flag gesetzt werden!! if( pOtherSet && pOtherSet->Count() ) { SwTableNode* pTblNd; const SwFmtPageDesc* pDesc; if( SFX_ITEM_SET == pOtherSet->GetItemState( RES_PAGEDESC, sal_False, (const SfxPoolItem**)&pDesc )) { if( pNode ) { // Auto-Flag setzen, nur in Vorlagen ist ohne Auto ! SwFmtPageDesc aNew( *pDesc ); // Bug 38479: AutoFlag wird jetzt in der WrtShell gesetzt // aNew.SetAuto(); // Tabellen kennen jetzt auch Umbrueche if( 0 == (nFlags & nsSetAttrMode::SETATTR_APICALL) && 0 != ( pTblNd = pNode->FindTableNode() ) ) { SwTableNode* pCurTblNd = pTblNd; while ( 0 != ( pCurTblNd = pCurTblNd->StartOfSectionNode()->FindTableNode() ) ) pTblNd = pCurTblNd; // dann am Tabellen Format setzen SwFrmFmt* pFmt = pTblNd->GetTable().GetFrmFmt(); SwRegHistory aRegH( pFmt, *pTblNd, pHistory ); pFmt->SetFmtAttr( aNew ); bRet = true; } else { SwRegHistory aRegH( pNode, *pNode, pHistory ); bRet = pNode->SetAttr( aNew ) || bRet; } } // bOtherAttr = true means that pOtherSet == rChgSet. In this case // we know, that there is only one attribute in pOtherSet. We cannot // perform the following operations, instead we return: if ( bOtherAttr ) return bRet; const_cast<SfxItemSet*>(pOtherSet)->ClearItem( RES_PAGEDESC ); if( !pOtherSet->Count() ) { DELETECHARSETS return bRet; } } // Tabellen kennen jetzt auch Umbrueche const SvxFmtBreakItem* pBreak; if( pNode && 0 == (nFlags & nsSetAttrMode::SETATTR_APICALL) && 0 != (pTblNd = pNode->FindTableNode() ) && SFX_ITEM_SET == pOtherSet->GetItemState( RES_BREAK, sal_False, (const SfxPoolItem**)&pBreak ) ) { SwTableNode* pCurTblNd = pTblNd; while ( 0 != ( pCurTblNd = pCurTblNd->StartOfSectionNode()->FindTableNode() ) ) pTblNd = pCurTblNd; // dann am Tabellen Format setzen SwFrmFmt* pFmt = pTblNd->GetTable().GetFrmFmt(); SwRegHistory aRegH( pFmt, *pTblNd, pHistory ); pFmt->SetFmtAttr( *pBreak ); bRet = true; // bOtherAttr = true means that pOtherSet == rChgSet. In this case // we know, that there is only one attribute in pOtherSet. We cannot // perform the following operations, instead we return: if ( bOtherAttr ) return bRet; const_cast<SfxItemSet*>(pOtherSet)->ClearItem( RES_BREAK ); if( !pOtherSet->Count() ) { DELETECHARSETS return bRet; } } { // wenns eine PoolNumRule ist, diese ggfs. anlegen const SwNumRuleItem* pRule; sal_uInt16 nPoolId; if( SFX_ITEM_SET == pOtherSet->GetItemState( RES_PARATR_NUMRULE, sal_False, (const SfxPoolItem**)&pRule ) && !pDoc->FindNumRulePtr( pRule->GetValue() ) && USHRT_MAX != (nPoolId = SwStyleNameMapper::GetPoolIdFromUIName ( pRule->GetValue(), nsSwGetPoolIdFromName::GET_POOLID_NUMRULE )) ) pDoc->GetNumRuleFromPool( nPoolId ); } } if( !rRg.HasMark() ) // kein Bereich { if( !pNode ) { DELETECHARSETS return bRet; } if( pNode->IsTxtNode() && pCharSet && pCharSet->Count() ) { SwTxtNode* pTxtNd = static_cast<SwTxtNode*>(pNode); const SwIndex& rSt = pStt->nContent; sal_uInt16 nMkPos, nPtPos = rSt.GetIndex(); const String& rStr = pTxtNd->GetTxt(); // JP 22.08.96: Sonderfall: steht der Crsr in einem URL-Attribut // dann wird dessen Bereich genommen SwTxtAttr const*const pURLAttr( pTxtNd->GetTxtAttrAt(rSt.GetIndex(), RES_TXTATR_INETFMT)); if (pURLAttr && pURLAttr->GetINetFmt().GetValue().Len()) { nMkPos = *pURLAttr->GetStart(); nPtPos = *pURLAttr->End(); } else { Boundary aBndry; if( pBreakIt->GetBreakIter().is() ) aBndry = pBreakIt->GetBreakIter()->getWordBoundary( pTxtNd->GetTxt(), nPtPos, pBreakIt->GetLocale( pTxtNd->GetLang( nPtPos ) ), WordType::ANY_WORD /*ANYWORD_IGNOREWHITESPACES*/, sal_True ); if( aBndry.startPos < nPtPos && nPtPos < aBndry.endPos ) { nMkPos = (xub_StrLen)aBndry.startPos; nPtPos = (xub_StrLen)aBndry.endPos; } else nPtPos = nMkPos = rSt.GetIndex(); } // erstmal die zu ueberschreibenden Attribute aus dem // SwpHintsArray entfernen, wenn die Selektion den gesamten // Absatz umspannt. (Diese Attribute werden als FormatAttr. // eingefuegt und verdraengen nie die TextAttr.!) if( !(nFlags & nsSetAttrMode::SETATTR_DONTREPLACE ) && pTxtNd->HasHints() && !nMkPos && nPtPos == rStr.Len() ) { SwIndex aSt( pTxtNd ); if( pHistory ) { // fuers Undo alle Attribute sichern SwRegHistory aRHst( *pTxtNd, pHistory ); pTxtNd->GetpSwpHints()->Register( &aRHst ); pTxtNd->RstTxtAttr( aSt, nPtPos, 0, pCharSet ); if( pTxtNd->GetpSwpHints() ) pTxtNd->GetpSwpHints()->DeRegister(); } else pTxtNd->RstTxtAttr( aSt, nPtPos, 0, pCharSet ); } // the SwRegHistory inserts the attribute into the TxtNode! SwRegHistory history( pNode, *pNode, pHistory ); bRet = history.InsertItems( *pCharSet, nMkPos, nPtPos, nFlags ) || bRet; if( pDoc->IsRedlineOn() ) { SwPaM aPam( *pNode, nMkPos, *pNode, nPtPos ); if( pUndo ) pUndo->SaveRedlineData( aPam, sal_False ); pDoc->AppendRedline( new SwRedline( nsRedlineType_t::REDLINE_FORMAT, aPam ), true); } } if( pOtherSet && pOtherSet->Count() ) { SwRegHistory aRegH( pNode, *pNode, pHistory ); //UUUU Need to check for unique item for DrawingLayer items of type NameOrIndex // and evtl. correct that item to ensure unique names for that type. This call may // modify/correct entries inside of the given SfxItemSet SfxItemSet aTempLocalCopy(*pOtherSet); pDoc->CheckForUniqueItemForLineFillNameOrIndex(aTempLocalCopy); bRet = pNode->SetAttr(aTempLocalCopy) || bRet; } DELETECHARSETS return bRet; } if( pDoc->IsRedlineOn() && pCharSet && pCharSet->Count() ) { if( pUndo ) pUndo->SaveRedlineData( rRg, sal_False ); pDoc->AppendRedline( new SwRedline( nsRedlineType_t::REDLINE_FORMAT, rRg ), true); } /* jetzt wenn Bereich */ sal_uLong nNodes = 0; SwNodeIndex aSt( pDoc->GetNodes() ); SwNodeIndex aEnd( pDoc->GetNodes() ); SwIndex aCntEnd( pEnd->nContent ); if( pNode ) { sal_uInt16 nLen = pNode->Len(); if( pStt->nNode != pEnd->nNode ) aCntEnd.Assign( pNode, nLen ); if( pStt->nContent.GetIndex() != 0 || aCntEnd.GetIndex() != nLen ) { // the SwRegHistory inserts the attribute into the TxtNode! if( pNode->IsTxtNode() && pCharSet && pCharSet->Count() ) { SwRegHistory history( pNode, *pNode, pHistory ); bRet = history.InsertItems(*pCharSet, pStt->nContent.GetIndex(), aCntEnd.GetIndex(), nFlags) || bRet; } if( pOtherSet && pOtherSet->Count() ) { SwRegHistory aRegH( pNode, *pNode, pHistory ); bRet = pNode->SetAttr( *pOtherSet ) || bRet; } // lediglich Selektion in einem Node. if( pStt->nNode == pEnd->nNode ) { //Modify here for #119405, by easyfan, 2012-05-24 //The data parameter flag: bExpandCharToPara, comes from the data member of SwDoc, //Which is set in SW MS word Binary filter WW8ImplRreader. With this flag on, means that //current setting attribute set is a character range properties set and comes from a MS word //binary file, And the setting range include a paragraph end position (0X0D); //More specifications, as such property inside the character range properties set recorded in //MS word binary file are dealed and inserted into data model (SwDoc) one by one, so we //only dealing the scenario that the char properties set with 1 item inside; if (bExpandCharToPara && pCharSet && pCharSet->Count() ==1 ) { SwTxtNode* pCurrentNd = pStt->nNode.GetNode().GetTxtNode(); if (pCurrentNd) { pCurrentNd->TryCharSetExpandToNum(*pCharSet); } } //End of modification, by easyfan DELETECHARSETS return bRet; } ++nNodes; aSt.Assign( pStt->nNode.GetNode(), +1 ); } else aSt = pStt->nNode; aCntEnd = pEnd->nContent; // aEnd wurde veraendert !! } else aSt.Assign( pStt->nNode.GetNode(), +1 ); // aSt zeigt jetzt auf den ersten vollen Node /* * die Selektion umfasst mehr als einen Node */ if( pStt->nNode < pEnd->nNode ) { pNode = pEnd->nNode.GetNode().GetCntntNode(); if(pNode) { sal_uInt16 nLen = pNode->Len(); if( aCntEnd.GetIndex() != nLen ) { // the SwRegHistory inserts the attribute into the TxtNode! if( pNode->IsTxtNode() && pCharSet && pCharSet->Count() ) { SwRegHistory history( pNode, *pNode, pHistory ); history.InsertItems(*pCharSet, 0, aCntEnd.GetIndex(), nFlags); } if( pOtherSet && pOtherSet->Count() ) { SwRegHistory aRegH( pNode, *pNode, pHistory ); pNode->SetAttr( *pOtherSet ); } ++nNodes; aEnd = pEnd->nNode; } else aEnd.Assign( pEnd->nNode.GetNode(), +1 ); } else aEnd = pEnd->nNode; } else aEnd.Assign( pEnd->nNode.GetNode(), +1 ); // aEnd zeigt jetzt HINTER den letzten voll Node /* Bearbeitung der vollstaendig selektierten Nodes. */ // alle Attribute aus dem Set zuruecksetzen !! if( pCharSet && pCharSet->Count() && !( nsSetAttrMode::SETATTR_DONTREPLACE & nFlags ) ) { ParaRstFmt aPara( pStt, pEnd, pHistory, 0, pCharSet ); pDoc->GetNodes().ForEach( aSt, aEnd, lcl_RstTxtAttr, &aPara ); } sal_Bool bCreateSwpHints = pCharSet && ( SFX_ITEM_SET == pCharSet->GetItemState( RES_TXTATR_CHARFMT, sal_False ) || SFX_ITEM_SET == pCharSet->GetItemState( RES_TXTATR_INETFMT, sal_False ) ); for(; aSt < aEnd; aSt++ ) { pNode = aSt.GetNode().GetCntntNode(); if( !pNode ) continue; SwTxtNode* pTNd = pNode->GetTxtNode(); if( pHistory ) { SwRegHistory aRegH( pNode, *pNode, pHistory ); SwpHints *pSwpHints; if( pTNd && pCharSet && pCharSet->Count() ) { pSwpHints = bCreateSwpHints ? &pTNd->GetOrCreateSwpHints() : pTNd->GetpSwpHints(); if( pSwpHints ) pSwpHints->Register( &aRegH ); pTNd->SetAttr( *pCharSet, 0, pTNd->GetTxt().Len(), nFlags ); if( pSwpHints ) pSwpHints->DeRegister(); } if( pOtherSet && pOtherSet->Count() ) pNode->SetAttr( *pOtherSet ); } else { if( pTNd && pCharSet && pCharSet->Count() ) pTNd->SetAttr( *pCharSet, 0, pTNd->GetTxt().Len(), nFlags ); if( pOtherSet && pOtherSet->Count() ) pNode->SetAttr( *pOtherSet ); } ++nNodes; } //The data parameter flag: bExpandCharToPara, comes from the data member of SwDoc, //Which is set in SW MS word Binary filter WW8ImplRreader. With this flag on, means that //current setting attribute set is a character range properties set and comes from a MS word //binary file, And the setting range include a paragraph end position (0X0D); //More specifications, as such property inside the character range properties set recorded in //MS word binary file are dealed and inserted into data model (SwDoc) one by one, so we //only dealing the scenario that the char properties set with 1 item inside; if (bExpandCharToPara && pCharSet && pCharSet->Count() ==1) { SwPosition aStartPos (*rRg.Start()); SwPosition aEndPos (*rRg.End()); if (aEndPos.nNode.GetNode().GetTxtNode() && aEndPos.nContent != aEndPos.nNode.GetNode().GetTxtNode()->Len()) aEndPos.nNode--; for (;aStartPos<=aEndPos;aStartPos.nNode++) { SwTxtNode* pCurrentNd = aStartPos.nNode.GetNode().GetTxtNode(); if (pCurrentNd) { pCurrentNd->TryCharSetExpandToNum(*pCharSet); } } } DELETECHARSETS return (nNodes != 0) || bRet; } bool SwDoc::InsertPoolItem( const SwPaM &rRg, const SfxPoolItem &rHt, const SetAttrMode nFlags, const bool bExpandCharToPara) { SwDataChanged aTmp( rRg, 0 ); SwUndoAttr* pUndoAttr = 0; if (GetIDocumentUndoRedo().DoesUndo()) { GetIDocumentUndoRedo().ClearRedo(); pUndoAttr = new SwUndoAttr( rRg, rHt, nFlags ); } SfxItemSet aSet( GetAttrPool(), rHt.Which(), rHt.Which() ); aSet.Put( rHt ); const bool bRet = lcl_InsAttr( this, rRg, aSet, nFlags, pUndoAttr,bExpandCharToPara ); if (GetIDocumentUndoRedo().DoesUndo()) { GetIDocumentUndoRedo().AppendUndo( pUndoAttr ); } if( bRet ) { SetModified(); } return bRet; } bool SwDoc::InsertItemSet ( const SwPaM &rRg, const SfxItemSet &rSet, const SetAttrMode nFlags ) { SwDataChanged aTmp( rRg, 0 ); SwUndoAttr* pUndoAttr = 0; if (GetIDocumentUndoRedo().DoesUndo()) { GetIDocumentUndoRedo().ClearRedo(); pUndoAttr = new SwUndoAttr( rRg, rSet, nFlags ); } bool bRet = lcl_InsAttr( this, rRg, rSet, nFlags, pUndoAttr ); if (GetIDocumentUndoRedo().DoesUndo()) { GetIDocumentUndoRedo().AppendUndo( pUndoAttr ); } if( bRet ) SetModified(); return bRet; } // Setze das Attribut im angegebenen Format. Ist Undo aktiv, wird // das alte in die Undo-History aufgenommen void SwDoc::SetAttr( const SfxPoolItem& rAttr, SwFmt& rFmt ) { SfxItemSet aSet( GetAttrPool(), rAttr.Which(), rAttr.Which() ); aSet.Put( rAttr ); SetAttr( aSet, rFmt ); } // Setze das Attribut im angegebenen Format. Ist Undo aktiv, wird // das alte in die Undo-History aufgenommen void SwDoc::SetAttr( const SfxItemSet& rSet, SwFmt& rFmt ) { if (GetIDocumentUndoRedo().DoesUndo()) { SwUndoFmtAttrHelper aTmp( rFmt ); rFmt.SetFmtAttr( rSet ); if ( aTmp.GetUndo() ) { GetIDocumentUndoRedo().AppendUndo( aTmp.ReleaseUndo() ); } else { GetIDocumentUndoRedo().ClearRedo(); } } else { rFmt.SetFmtAttr( rSet ); } SetModified(); } // --> OD 2008-02-12 #newlistlevelattrs# void SwDoc::ResetAttrAtFormat( const sal_uInt16 nWhichId, SwFmt& rChangedFormat ) { SwUndo *const pUndo = (GetIDocumentUndoRedo().DoesUndo()) ? new SwUndoFmtResetAttr( rChangedFormat, nWhichId ) : 0; const sal_Bool bAttrReset = rChangedFormat.ResetFmtAttr( nWhichId ); if ( bAttrReset ) { if ( pUndo ) { GetIDocumentUndoRedo().AppendUndo( pUndo ); } SetModified(); } else if ( pUndo ) delete pUndo; } // <-- int lcl_SetNewDefTabStops( SwTwips nOldWidth, SwTwips nNewWidth, SvxTabStopItem& rChgTabStop ) { // dann aender bei allen TabStop die default's auf den neuen Wert // !!! Achtung: hier wird immer auf dem PoolAttribut gearbeitet, // damit nicht in allen Sets die gleiche Berechnung // auf dem gleichen TabStop (gepoolt!) vorgenommen // wird. Als Modify wird ein FmtChg verschickt. sal_uInt16 nOldCnt = rChgTabStop.Count(); if( !nOldCnt || nOldWidth == nNewWidth ) return sal_False; // suche den Anfang der Defaults SvxTabStop* pTabs = ((SvxTabStop*)rChgTabStop.GetStart()) + (nOldCnt-1); sal_uInt16 n; for( n = nOldCnt; n ; --n, --pTabs ) if( SVX_TAB_ADJUST_DEFAULT != pTabs->GetAdjustment() ) break; ++n; if( n < nOldCnt ) // die DefTabStops loeschen rChgTabStop.Remove( n, nOldCnt - n ); return sal_True; } // Setze das Attribut als neues default Attribut in diesem Dokument. // Ist Undo aktiv, wird das alte in die Undo-History aufgenommen void SwDoc::SetDefault( const SfxPoolItem& rAttr ) { SfxItemSet aSet( GetAttrPool(), rAttr.Which(), rAttr.Which() ); aSet.Put( rAttr ); SetDefault( aSet ); } void SwDoc::SetDefault( const SfxItemSet& rSet ) { if( !rSet.Count() ) return; SwModify aCallMod( 0 ); SwAttrSet aOld( GetAttrPool(), rSet.GetRanges() ), aNew( GetAttrPool(), rSet.GetRanges() ); SfxItemIter aIter( rSet ); sal_uInt16 nWhich; const SfxPoolItem* pItem = aIter.GetCurItem(); SfxItemPool* pSdrPool = GetAttrPool().GetSecondaryPool(); while( sal_True ) { sal_Bool bCheckSdrDflt = sal_False; nWhich = pItem->Which(); aOld.Put( GetAttrPool().GetDefaultItem( nWhich ) ); GetAttrPool().SetPoolDefaultItem( *pItem ); aNew.Put( GetAttrPool().GetDefaultItem( nWhich ) ); if (isCHRATR(nWhich) || isTXTATR(nWhich)) { aCallMod.Add( pDfltTxtFmtColl ); aCallMod.Add( pDfltCharFmt ); bCheckSdrDflt = 0 != pSdrPool; } else if ( isPARATR(nWhich) || // --> OD 2008-02-25 #refactorlists# isPARATR_LIST(nWhich) ) // <-- { aCallMod.Add( pDfltTxtFmtColl ); bCheckSdrDflt = 0 != pSdrPool; } else if (isGRFATR(nWhich)) { aCallMod.Add( pDfltGrfFmtColl ); } else if (isFRMATR(nWhich) || isDrawingLayerAttribute(nWhich) ) //UUUU { aCallMod.Add( pDfltGrfFmtColl ); aCallMod.Add( pDfltTxtFmtColl ); aCallMod.Add( pDfltFrmFmt ); } else if (isBOXATR(nWhich)) { aCallMod.Add( pDfltFrmFmt ); } // copy also the defaults if( bCheckSdrDflt ) { sal_uInt16 nEdtWhich, nSlotId; if( 0 != (nSlotId = GetAttrPool().GetSlotId( nWhich ) ) && nSlotId != nWhich && 0 != (nEdtWhich = pSdrPool->GetWhich( nSlotId )) && nSlotId != nEdtWhich ) { SfxPoolItem* pCpy = pItem->Clone(); pCpy->SetWhich( nEdtWhich ); pSdrPool->SetPoolDefaultItem( *pCpy ); delete pCpy; } } if( aIter.IsAtEnd() ) break; pItem = aIter.NextItem(); } if( aNew.Count() && aCallMod.GetDepends() ) { if (GetIDocumentUndoRedo().DoesUndo()) { GetIDocumentUndoRedo().AppendUndo( new SwUndoDefaultAttr( aOld ) ); } const SfxPoolItem* pTmpItem; if( ( SFX_ITEM_SET == aNew.GetItemState( RES_PARATR_TABSTOP, sal_False, &pTmpItem ) ) && ((SvxTabStopItem*)pTmpItem)->Count() ) { // TabStop-Aenderungen behandeln wir erstmal anders: // dann aender bei allen TabStop die dafault's auf den neuen Wert // !!! Achtung: hier wird immer auf dem PoolAttribut gearbeitet, // damit nicht in allen Sets die gleiche Berechnung // auf dem gleichen TabStop (gepoolt!) vorgenommen // wird. Als Modify wird ein FmtChg verschickt. SwTwips nNewWidth = (*(SvxTabStopItem*)pTmpItem)[ 0 ].GetTabPos(), nOldWidth = ((SvxTabStopItem&)aOld.Get(RES_PARATR_TABSTOP))[ 0 ].GetTabPos(); int bChg = sal_False; sal_uInt32 nMaxItems = GetAttrPool().GetItemCount2( RES_PARATR_TABSTOP ); for( sal_uInt32 n = 0; n < nMaxItems; ++n ) if( 0 != (pTmpItem = GetAttrPool().GetItem2( RES_PARATR_TABSTOP, n ) )) bChg |= lcl_SetNewDefTabStops( nOldWidth, nNewWidth, *(SvxTabStopItem*)pTmpItem ); aNew.ClearItem( RES_PARATR_TABSTOP ); aOld.ClearItem( RES_PARATR_TABSTOP ); if( bChg ) { SwFmtChg aChgFmt( pDfltCharFmt ); // dann sage mal den Frames bescheid aCallMod.ModifyNotification( &aChgFmt, &aChgFmt ); } } } if( aNew.Count() && aCallMod.GetDepends() ) { SwAttrSetChg aChgOld( aOld, aOld ); SwAttrSetChg aChgNew( aNew, aNew ); aCallMod.ModifyNotification( &aChgOld, &aChgNew ); // alle veraenderten werden verschickt } // und die default-Formate wieder beim Object austragen SwClient* pDep; while( 0 != ( pDep = (SwClient*)aCallMod.GetDepends()) ) aCallMod.Remove( pDep ); SetModified(); } // Erfrage das Default Attribut in diesem Dokument. const SfxPoolItem& SwDoc::GetDefault( sal_uInt16 nFmtHint ) const { return GetAttrPool().GetDefaultItem( nFmtHint ); } /* * Loeschen der Formate */ void SwDoc::DelCharFmt(sal_uInt16 nFmt, sal_Bool bBroadcast) { SwCharFmt * pDel = (*pCharFmtTbl)[nFmt]; if (bBroadcast) BroadcastStyleOperation(pDel->GetName(), SFX_STYLE_FAMILY_CHAR, SFX_STYLESHEET_ERASED); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndo * pUndo = new SwUndoCharFmtDelete(pDel, this); GetIDocumentUndoRedo().AppendUndo(pUndo); } pCharFmtTbl->DeleteAndDestroy(nFmt); SetModified(); } void SwDoc::DelCharFmt( SwCharFmt *pFmt, sal_Bool bBroadcast ) { sal_uInt16 nFmt = pCharFmtTbl->GetPos( pFmt ); ASSERT( USHRT_MAX != nFmt, "Fmt not found," ); DelCharFmt( nFmt, bBroadcast ); } void SwDoc::DelFrmFmt( SwFrmFmt *pFmt, sal_Bool bBroadcast ) { if( pFmt->ISA( SwTableBoxFmt ) || pFmt->ISA( SwTableLineFmt )) { ASSERT( sal_False, "Format is no longer in DocArray, " "can be deleted by delete" ); delete pFmt; } else { //Das Format muss in einem der beiden Arrays stehen, in welchem //werden wir schon merken. sal_uInt16 nPos; if ( USHRT_MAX != ( nPos = pFrmFmtTbl->GetPos( pFmt )) ) { if (bBroadcast) BroadcastStyleOperation(pFmt->GetName(), SFX_STYLE_FAMILY_FRAME, SFX_STYLESHEET_ERASED); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndo * pUndo = new SwUndoFrmFmtDelete(pFmt, this); GetIDocumentUndoRedo().AppendUndo(pUndo); } pFrmFmtTbl->DeleteAndDestroy( nPos ); } else { nPos = GetSpzFrmFmts()->GetPos( pFmt ); ASSERT( nPos != USHRT_MAX, "FrmFmt not found." ); if( USHRT_MAX != nPos ) GetSpzFrmFmts()->DeleteAndDestroy( nPos ); } } } void SwDoc::DelTblFrmFmt( SwTableFmt *pFmt ) { sal_uInt16 nPos = pTblFrmFmtTbl->GetPos( pFmt ); ASSERT( USHRT_MAX != nPos, "Fmt not found," ); pTblFrmFmtTbl->DeleteAndDestroy( nPos ); } /* * Erzeugen der Formate */ SwFlyFrmFmt *SwDoc::MakeFlyFrmFmt( const String &rFmtName, SwFrmFmt *pDerivedFrom ) { SwFlyFrmFmt *pFmt = new SwFlyFrmFmt( GetAttrPool(), rFmtName, pDerivedFrom ); GetSpzFrmFmts()->Insert(pFmt, GetSpzFrmFmts()->Count()); SetModified(); return pFmt; } SwDrawFrmFmt *SwDoc::MakeDrawFrmFmt( const String &rFmtName, SwFrmFmt *pDerivedFrom ) { SwDrawFrmFmt *pFmt = new SwDrawFrmFmt( GetAttrPool(), rFmtName, pDerivedFrom); GetSpzFrmFmts()->Insert(pFmt,GetSpzFrmFmts()->Count()); SetModified(); return pFmt; } sal_uInt16 SwDoc::GetTblFrmFmtCount(sal_Bool bUsed) const { sal_uInt16 nCount = pTblFrmFmtTbl->Count(); if(bUsed) { SwAutoFmtGetDocNode aGetHt( &GetNodes() ); for ( sal_uInt16 i = nCount; i; ) { if((*pTblFrmFmtTbl)[--i]->GetInfo( aGetHt )) --nCount; } } return nCount; } SwFrmFmt& SwDoc::GetTblFrmFmt(sal_uInt16 nFmt, sal_Bool bUsed ) const { sal_uInt16 nRemoved = 0; if(bUsed) { SwAutoFmtGetDocNode aGetHt( &GetNodes() ); for ( sal_uInt16 i = 0; i <= nFmt; i++ ) { while ( (*pTblFrmFmtTbl)[ i + nRemoved]->GetInfo( aGetHt )) { nRemoved++; } } } return *((*pTblFrmFmtTbl)[nRemoved + nFmt]); } SwTableFmt* SwDoc::MakeTblFrmFmt( const String &rFmtName, SwFrmFmt *pDerivedFrom ) { SwTableFmt* pFmt = new SwTableFmt( GetAttrPool(), rFmtName, pDerivedFrom ); pTblFrmFmtTbl->Insert( pFmt, pTblFrmFmtTbl->Count() ); SetModified(); return pFmt; } SwFrmFmt *SwDoc::MakeFrmFmt(const String &rFmtName, SwFrmFmt *pDerivedFrom, sal_Bool bBroadcast, sal_Bool bAuto) { SwFrmFmt *pFmt = new SwFrmFmt( GetAttrPool(), rFmtName, pDerivedFrom ); pFmt->SetAuto(bAuto); pFrmFmtTbl->Insert( pFmt, pFrmFmtTbl->Count()); SetModified(); if (bBroadcast) { BroadcastStyleOperation(rFmtName, SFX_STYLE_FAMILY_PARA, SFX_STYLESHEET_CREATED); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndo * pUndo = new SwUndoFrmFmtCreate(pFmt, pDerivedFrom, this); GetIDocumentUndoRedo().AppendUndo(pUndo); } } return pFmt; } SwFmt *SwDoc::_MakeFrmFmt(const String &rFmtName, SwFmt *pDerivedFrom, sal_Bool bBroadcast, sal_Bool bAuto) { SwFrmFmt *pFrmFmt = dynamic_cast<SwFrmFmt*>(pDerivedFrom); pFrmFmt = MakeFrmFmt( rFmtName, pFrmFmt, bBroadcast, bAuto ); return dynamic_cast<SwFmt*>(pFrmFmt); } // --> OD 2005-01-13 #i40550# - add parameter <bAuto> - not relevant SwCharFmt *SwDoc::MakeCharFmt( const String &rFmtName, SwCharFmt *pDerivedFrom, sal_Bool bBroadcast, sal_Bool ) // <-- { SwCharFmt *pFmt = new SwCharFmt( GetAttrPool(), rFmtName, pDerivedFrom ); pCharFmtTbl->Insert( pFmt, pCharFmtTbl->Count() ); pFmt->SetAuto( sal_False ); SetModified(); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndo * pUndo = new SwUndoCharFmtCreate(pFmt, pDerivedFrom, this); GetIDocumentUndoRedo().AppendUndo(pUndo); } if (bBroadcast) { BroadcastStyleOperation(rFmtName, SFX_STYLE_FAMILY_CHAR, SFX_STYLESHEET_CREATED); } return pFmt; } SwFmt *SwDoc::_MakeCharFmt(const String &rFmtName, SwFmt *pDerivedFrom, sal_Bool bBroadcast, sal_Bool bAuto) { SwCharFmt *pCharFmt = dynamic_cast<SwCharFmt*>(pDerivedFrom); pCharFmt = MakeCharFmt( rFmtName, pCharFmt, bBroadcast, bAuto ); return dynamic_cast<SwFmt*>(pCharFmt); } /* * Erzeugen der FormatCollections */ // TXT // --> OD 2005-01-13 #i40550# - add parameter <bAuto> - not relevant SwTxtFmtColl* SwDoc::MakeTxtFmtColl( const String &rFmtName, SwTxtFmtColl *pDerivedFrom, sal_Bool bBroadcast, sal_Bool ) // <-- { SwTxtFmtColl *pFmtColl = new SwTxtFmtColl( GetAttrPool(), rFmtName, pDerivedFrom ); pTxtFmtCollTbl->Insert(pFmtColl, pTxtFmtCollTbl->Count()); pFmtColl->SetAuto( sal_False ); SetModified(); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndo * pUndo = new SwUndoTxtFmtCollCreate(pFmtColl, pDerivedFrom, this); GetIDocumentUndoRedo().AppendUndo(pUndo); } if (bBroadcast) BroadcastStyleOperation(rFmtName, SFX_STYLE_FAMILY_PARA, SFX_STYLESHEET_CREATED); return pFmtColl; } SwFmt *SwDoc::_MakeTxtFmtColl(const String &rFmtName, SwFmt *pDerivedFrom, sal_Bool bBroadcast, sal_Bool bAuto) { SwTxtFmtColl *pTxtFmtColl = dynamic_cast<SwTxtFmtColl*>(pDerivedFrom); pTxtFmtColl = MakeTxtFmtColl( rFmtName, pTxtFmtColl, bBroadcast, bAuto ); return dynamic_cast<SwFmt*>(pTxtFmtColl); } //FEATURE::CONDCOLL SwConditionTxtFmtColl* SwDoc::MakeCondTxtFmtColl( const String &rFmtName, SwTxtFmtColl *pDerivedFrom, sal_Bool bBroadcast) { SwConditionTxtFmtColl*pFmtColl = new SwConditionTxtFmtColl( GetAttrPool(), rFmtName, pDerivedFrom ); pTxtFmtCollTbl->Insert(pFmtColl, pTxtFmtCollTbl->Count()); pFmtColl->SetAuto( sal_False ); SetModified(); if (bBroadcast) BroadcastStyleOperation(rFmtName, SFX_STYLE_FAMILY_PARA, SFX_STYLESHEET_CREATED); return pFmtColl; } //FEATURE::CONDCOLL // GRF SwGrfFmtColl* SwDoc::MakeGrfFmtColl( const String &rFmtName, SwGrfFmtColl *pDerivedFrom ) { SwGrfFmtColl *pFmtColl = new SwGrfFmtColl( GetAttrPool(), rFmtName, pDerivedFrom ); pGrfFmtCollTbl->Insert( pFmtColl, pGrfFmtCollTbl->Count() ); pFmtColl->SetAuto( sal_False ); SetModified(); return pFmtColl; } void SwDoc::DelTxtFmtColl(sal_uInt16 nFmtColl, sal_Bool bBroadcast) { ASSERT( nFmtColl, "Remove fuer Coll 0." ); // Wer hat die zu loeschende als Next SwTxtFmtColl *pDel = (*pTxtFmtCollTbl)[nFmtColl]; if( pDfltTxtFmtColl == pDel ) return; // default nie loeschen !! if (bBroadcast) BroadcastStyleOperation(pDel->GetName(), SFX_STYLE_FAMILY_PARA, SFX_STYLESHEET_ERASED); if (GetIDocumentUndoRedo().DoesUndo()) { SwUndoTxtFmtCollDelete * pUndo = new SwUndoTxtFmtCollDelete(pDel, this); GetIDocumentUndoRedo().AppendUndo(pUndo); } // Die FmtColl austragen pTxtFmtCollTbl->Remove(nFmtColl); // Next korrigieren pTxtFmtCollTbl->ForEach( 1, pTxtFmtCollTbl->Count(), &SetTxtFmtCollNext, pDel ); delete pDel; SetModified(); } void SwDoc::DelTxtFmtColl( SwTxtFmtColl *pColl, sal_Bool bBroadcast ) { sal_uInt16 nFmt = pTxtFmtCollTbl->GetPos( pColl ); ASSERT( USHRT_MAX != nFmt, "Collection not found," ); DelTxtFmtColl( nFmt, bBroadcast ); } sal_Bool lcl_SetTxtFmtColl( const SwNodePtr& rpNode, void* pArgs ) { SwCntntNode* pCNd = (SwCntntNode*) rpNode->GetTxtNode(); if ( pCNd ) { ParaRstFmt* pPara = (ParaRstFmt*) pArgs; SwTxtFmtColl* pFmt = static_cast< SwTxtFmtColl* >( pPara->pFmtColl ); if ( pPara->bReset ) { lcl_RstAttr( pCNd, pPara ); // check, if paragraph style has changed if ( pPara->bResetListAttrs && pFmt != pCNd->GetFmtColl() && pFmt->GetItemState( RES_PARATR_NUMRULE ) == SFX_ITEM_SET ) { // --> OD 2009-09-07 #b6876367# // Check, if the list style of the paragraph will change. bool bChangeOfListStyleAtParagraph( true ); SwTxtNode* pTNd( dynamic_cast<SwTxtNode*>(pCNd) ); ASSERT( pTNd, "<lcl_SetTxtFmtColl(..)> - text node expected -> crash" ); { SwNumRule* pNumRuleAtParagraph( pTNd->GetNumRule() ); if ( pNumRuleAtParagraph ) { const SwNumRuleItem& rNumRuleItemAtParagraphStyle = pFmt->GetNumRule(); if ( rNumRuleItemAtParagraphStyle.GetValue() == pNumRuleAtParagraph->GetName() ) { bChangeOfListStyleAtParagraph = false; } } } if ( bChangeOfListStyleAtParagraph ) { std::auto_ptr< SwRegHistory > pRegH; if ( pPara->pHistory ) { pRegH.reset( new SwRegHistory( pTNd, *pTNd, pPara->pHistory ) ); } pCNd->ResetAttr( RES_PARATR_NUMRULE ); // reset all list attributes pCNd->ResetAttr( RES_PARATR_LIST_LEVEL ); pCNd->ResetAttr( RES_PARATR_LIST_ISRESTART ); pCNd->ResetAttr( RES_PARATR_LIST_RESTARTVALUE ); pCNd->ResetAttr( RES_PARATR_LIST_ISCOUNTED ); pCNd->ResetAttr( RES_PARATR_LIST_ID ); } } } // erst in die History aufnehmen, damit ggfs. alte Daten // gesichert werden koennen if( pPara->pHistory ) pPara->pHistory->Add( pCNd->GetFmtColl(), pCNd->GetIndex(), ND_TEXTNODE ); pCNd->ChgFmtColl( pFmt ); pPara->nWhich++; } return sal_True; } sal_Bool SwDoc::SetTxtFmtColl( const SwPaM &rRg, SwTxtFmtColl *pFmt, const bool bReset, const bool bResetListAttrs ) { SwDataChanged aTmp( rRg, 0 ); const SwPosition *pStt = rRg.Start(), *pEnd = rRg.End(); SwHistory* pHst = 0; sal_Bool bRet = sal_True; if (GetIDocumentUndoRedo().DoesUndo()) { SwUndoFmtColl* pUndo = new SwUndoFmtColl( rRg, pFmt, bReset, bResetListAttrs ); pHst = pUndo->GetHistory(); GetIDocumentUndoRedo().AppendUndo(pUndo); } ParaRstFmt aPara( pStt, pEnd, pHst ); aPara.pFmtColl = pFmt; aPara.bReset = bReset; aPara.bResetListAttrs = bResetListAttrs; GetNodes().ForEach( pStt->nNode.GetIndex(), pEnd->nNode.GetIndex()+1, lcl_SetTxtFmtColl, &aPara ); if ( !aPara.nWhich ) bRet = sal_False; // keinen gueltigen Node gefunden if ( bRet ) { SetModified(); } return bRet; } // ---- Kopiere die Formate in sich selbst (SwDoc) ---------------------- SwFmt* SwDoc::CopyFmt( const SwFmt& rFmt, const SvPtrarr& rFmtArr, FNCopyFmt fnCopyFmt, const SwFmt& rDfltFmt ) { // kein-Autoformat || default Format || Collection-Format // dann suche danach. if( !rFmt.IsAuto() || !rFmt.GetRegisteredIn() ) for( sal_uInt16 n = 0; n < rFmtArr.Count(); n++ ) { // ist die Vorlage schon im Doc vorhanden ?? if( ((SwFmt*)rFmtArr[n])->GetName().Equals( rFmt.GetName() )) return (SwFmt*)rFmtArr[n]; } // suche erstmal nach dem "Parent" SwFmt* pParent = (SwFmt*)&rDfltFmt; if( rFmt.DerivedFrom() && pParent != rFmt.DerivedFrom() ) pParent = CopyFmt( *rFmt.DerivedFrom(), rFmtArr, fnCopyFmt, rDfltFmt ); // erzeuge das Format und kopiere die Attribute // --> OD 2005-01-13 #i40550# SwFmt* pNewFmt = (this->*fnCopyFmt)( rFmt.GetName(), pParent, sal_False, sal_True ); // <-- pNewFmt->SetAuto( rFmt.IsAuto() ); pNewFmt->CopyAttrs( rFmt, sal_True ); // kopiere Attribute pNewFmt->SetPoolFmtId( rFmt.GetPoolFmtId() ); pNewFmt->SetPoolHelpId( rFmt.GetPoolHelpId() ); // HelpFile-Id immer auf dflt setzen !! pNewFmt->SetPoolHlpFileId( UCHAR_MAX ); return pNewFmt; } // ---- kopiere das Frame-Format -------- SwFrmFmt* SwDoc::CopyFrmFmt( const SwFrmFmt& rFmt ) { return (SwFrmFmt*)CopyFmt( rFmt, *GetFrmFmts(), &SwDoc::_MakeFrmFmt, *GetDfltFrmFmt() ); } // ---- kopiere das Char-Format -------- SwCharFmt* SwDoc::CopyCharFmt( const SwCharFmt& rFmt ) { return (SwCharFmt*)CopyFmt( rFmt, *GetCharFmts(), &SwDoc::_MakeCharFmt, *GetDfltCharFmt() ); } // --- Kopiere TextNodes ---- SwTxtFmtColl* SwDoc::CopyTxtColl( const SwTxtFmtColl& rColl ) { SwTxtFmtColl* pNewColl = FindTxtFmtCollByName( rColl.GetName() ); if( pNewColl ) return pNewColl; // suche erstmal nach dem "Parent" SwTxtFmtColl* pParent = pDfltTxtFmtColl; if( pParent != rColl.DerivedFrom() ) pParent = CopyTxtColl( *(SwTxtFmtColl*)rColl.DerivedFrom() ); //FEATURE::CONDCOLL if( RES_CONDTXTFMTCOLL == rColl.Which() ) { pNewColl = new SwConditionTxtFmtColl( GetAttrPool(), rColl.GetName(), pParent); pTxtFmtCollTbl->Insert( pNewColl, pTxtFmtCollTbl->Count() ); pNewColl->SetAuto( sal_False ); SetModified(); // Kopiere noch die Bedingungen ((SwConditionTxtFmtColl*)pNewColl)->SetConditions( ((SwConditionTxtFmtColl&)rColl).GetCondColls() ); } else //FEATURE::CONDCOLL pNewColl = MakeTxtFmtColl( rColl.GetName(), pParent ); // kopiere jetzt noch die Auto-Formate oder kopiere die Attribute pNewColl->CopyAttrs( rColl, sal_True ); // setze noch den Outline-Level if ( rColl.IsAssignedToListLevelOfOutlineStyle() ) pNewColl->AssignToListLevelOfOutlineStyle( rColl.GetAssignedOutlineStyleLevel() ); pNewColl->SetPoolFmtId( rColl.GetPoolFmtId() ); pNewColl->SetPoolHelpId( rColl.GetPoolHelpId() ); // HelpFile-Id immer auf dflt setzen !! pNewColl->SetPoolHlpFileId( UCHAR_MAX ); if( &rColl.GetNextTxtFmtColl() != &rColl ) pNewColl->SetNextTxtFmtColl( *CopyTxtColl( rColl.GetNextTxtFmtColl() )); // ggfs. die NumRule erzeugen if( this != rColl.GetDoc() ) { const SfxPoolItem* pItem; if( SFX_ITEM_SET == pNewColl->GetItemState( RES_PARATR_NUMRULE, sal_False, &pItem )) { const SwNumRule* pRule; const String& rName = ((SwNumRuleItem*)pItem)->GetValue(); if( rName.Len() && 0 != ( pRule = rColl.GetDoc()->FindNumRulePtr( rName )) && !pRule->IsAutoRule() ) { SwNumRule* pDestRule = FindNumRulePtr( rName ); if( pDestRule ) pDestRule->SetInvalidRule( sal_True ); else MakeNumRule( rName, pRule ); } } } return pNewColl; } // --- Kopiere GrafikNodes ---- SwGrfFmtColl* SwDoc::CopyGrfColl( const SwGrfFmtColl& rColl ) { SwGrfFmtColl* pNewColl = FindGrfFmtCollByName( rColl.GetName() ); if( pNewColl ) return pNewColl; // suche erstmal nach dem "Parent" SwGrfFmtColl* pParent = pDfltGrfFmtColl; if( pParent != rColl.DerivedFrom() ) pParent = CopyGrfColl( *(SwGrfFmtColl*)rColl.DerivedFrom() ); // falls nicht, so kopiere sie pNewColl = MakeGrfFmtColl( rColl.GetName(), pParent ); // noch die Attribute kopieren pNewColl->CopyAttrs( rColl ); pNewColl->SetPoolFmtId( rColl.GetPoolFmtId() ); pNewColl->SetPoolHelpId( rColl.GetPoolHelpId() ); // HelpFile-Id immer auf dflt setzen !! pNewColl->SetPoolHlpFileId( UCHAR_MAX ); return pNewColl; } SwPageDesc* lcl_FindPageDesc( const SwPageDescs& rArr, const String& rName ) { for( sal_uInt16 n = rArr.Count(); n; ) { SwPageDesc* pDesc = rArr[ --n ]; if( pDesc->GetName() == rName ) return pDesc; } return 0; } void SwDoc::CopyFmtArr( const SvPtrarr& rSourceArr, SvPtrarr& rDestArr, FNCopyFmt fnCopyFmt, SwFmt& rDfltFmt ) { sal_uInt16 nSrc; SwFmt* pSrc, *pDest; // 1. Schritt alle Formate anlegen (das 0. ueberspringen - Default!) for( nSrc = rSourceArr.Count(); nSrc > 1; ) { pSrc = (SwFmt*)rSourceArr[ --nSrc ]; if( pSrc->IsDefault() || pSrc->IsAuto() ) continue; if( 0 == FindFmtByName( rDestArr, pSrc->GetName() ) ) { if( RES_CONDTXTFMTCOLL == pSrc->Which() ) MakeCondTxtFmtColl( pSrc->GetName(), (SwTxtFmtColl*)&rDfltFmt ); else // --> OD 2005-01-13 #i40550# (this->*fnCopyFmt)( pSrc->GetName(), &rDfltFmt, sal_False, sal_True ); // <-- } } // 2. Schritt alle Attribute kopieren, richtige Parents setzen for( nSrc = rSourceArr.Count(); nSrc > 1; ) { pSrc = (SwFmt*)rSourceArr[ --nSrc ]; if( pSrc->IsDefault() || pSrc->IsAuto() ) continue; pDest = FindFmtByName( rDestArr, pSrc->GetName() ); pDest->SetAuto( sal_False ); pDest->DelDiffs( *pSrc ); // #i94285#: existing <SwFmtPageDesc> instance, before copying attributes const SfxPoolItem* pItem; if( &GetAttrPool() != pSrc->GetAttrSet().GetPool() && SFX_ITEM_SET == pSrc->GetAttrSet().GetItemState( RES_PAGEDESC, sal_False, &pItem ) && ((SwFmtPageDesc*)pItem)->GetPageDesc() ) { SwFmtPageDesc aPageDesc( *(SwFmtPageDesc*)pItem ); const String& rNm = aPageDesc.GetPageDesc()->GetName(); SwPageDesc* pPageDesc = ::lcl_FindPageDesc( aPageDescs, rNm ); if( !pPageDesc ) { pPageDesc = aPageDescs[ MakePageDesc( rNm ) ]; } aPageDesc.RegisterToPageDesc( *pPageDesc ); SwAttrSet aTmpAttrSet( pSrc->GetAttrSet() ); aTmpAttrSet.Put( aPageDesc ); pDest->SetFmtAttr( aTmpAttrSet ); } else { pDest->SetFmtAttr( pSrc->GetAttrSet() ); } pDest->SetPoolFmtId( pSrc->GetPoolFmtId() ); pDest->SetPoolHelpId( pSrc->GetPoolHelpId() ); // HelpFile-Id immer auf dflt setzen !! pDest->SetPoolHlpFileId( UCHAR_MAX ); if( pSrc->DerivedFrom() ) pDest->SetDerivedFrom( FindFmtByName( rDestArr, pSrc->DerivedFrom()->GetName() ) ); if( RES_TXTFMTCOLL == pSrc->Which() || RES_CONDTXTFMTCOLL == pSrc->Which() ) { SwTxtFmtColl* pSrcColl = (SwTxtFmtColl*)pSrc, * pDstColl = (SwTxtFmtColl*)pDest; if( &pSrcColl->GetNextTxtFmtColl() != pSrcColl ) pDstColl->SetNextTxtFmtColl( *(SwTxtFmtColl*)FindFmtByName( rDestArr, pSrcColl->GetNextTxtFmtColl().GetName() ) ); // setze noch den Outline-Level if(pSrcColl->IsAssignedToListLevelOfOutlineStyle()) pDstColl->AssignToListLevelOfOutlineStyle(pSrcColl->GetAssignedOutlineStyleLevel()); //FEATURE::CONDCOLL if( RES_CONDTXTFMTCOLL == pSrc->Which() ) // Kopiere noch die Bedingungen // aber erst die alten loeschen! ((SwConditionTxtFmtColl*)pDstColl)->SetConditions( ((SwConditionTxtFmtColl*)pSrc)->GetCondColls() ); //FEATURE::CONDCOLL } } } void SwDoc::CopyPageDescHeaderFooterImpl( bool bCpyHeader, const SwFrmFmt& rSrcFmt, SwFrmFmt& rDestFmt ) { // jetzt noch Header-/Footer-Attribute richtig behandeln // Contenten Nodes Dokumentuebergreifend kopieren! sal_uInt16 nAttr = static_cast<sal_uInt16>( bCpyHeader ? RES_HEADER : RES_FOOTER ); const SfxPoolItem* pItem; if( SFX_ITEM_SET != rSrcFmt.GetAttrSet().GetItemState( nAttr, sal_False, &pItem )) return ; // Im Header steht noch der Verweis auf das Format aus dem // anderen Document!! SfxPoolItem* pNewItem = pItem->Clone(); SwFrmFmt* pOldFmt; if( bCpyHeader ) pOldFmt = ((SwFmtHeader*)pNewItem)->GetHeaderFmt(); else pOldFmt = ((SwFmtFooter*)pNewItem)->GetFooterFmt(); if( pOldFmt ) { SwFrmFmt* pNewFmt = new SwFrmFmt( GetAttrPool(), "CpyDesc", GetDfltFrmFmt() ); pNewFmt->CopyAttrs( *pOldFmt, sal_True ); if( SFX_ITEM_SET == pNewFmt->GetAttrSet().GetItemState( RES_CNTNT, sal_False, &pItem )) { SwFmtCntnt* pCntnt = (SwFmtCntnt*)pItem; if( pCntnt->GetCntntIdx() ) { SwNodeIndex aTmpIdx( GetNodes().GetEndOfAutotext() ); const SwNodes& rSrcNds = rSrcFmt.GetDoc()->GetNodes(); SwStartNode* pSttNd = GetNodes().MakeEmptySection( aTmpIdx, bCpyHeader ? SwHeaderStartNode : SwFooterStartNode ); const SwNode& rCSttNd = pCntnt->GetCntntIdx()->GetNode(); SwNodeRange aRg( rCSttNd, 0, *rCSttNd.EndOfSectionNode() ); aTmpIdx = *pSttNd->EndOfSectionNode(); rSrcNds._Copy( aRg, aTmpIdx ); aTmpIdx = *pSttNd; rSrcFmt.GetDoc()->CopyFlyInFlyImpl( aRg, 0, aTmpIdx ); pNewFmt->SetFmtAttr( SwFmtCntnt( pSttNd )); } else pNewFmt->ResetFmtAttr( RES_CNTNT ); } if( bCpyHeader ) ((SwFmtHeader*)pNewItem)->RegisterToFormat(*pNewFmt); else ((SwFmtFooter*)pNewItem)->RegisterToFormat(*pNewFmt); rDestFmt.SetFmtAttr( *pNewItem ); } delete pNewItem; } void SwDoc::CopyPageDesc( const SwPageDesc& rSrcDesc, SwPageDesc& rDstDesc, sal_Bool bCopyPoolIds ) { sal_Bool bNotifyLayout = sal_False; SwRootFrm* pTmpRoot = GetCurrentLayout();//swmod 080219 rDstDesc.SetLandscape( rSrcDesc.GetLandscape() ); rDstDesc.SetNumType( rSrcDesc.GetNumType() ); if( rDstDesc.ReadUseOn() != rSrcDesc.ReadUseOn() ) { rDstDesc.WriteUseOn( rSrcDesc.ReadUseOn() ); bNotifyLayout = sal_True; } if( bCopyPoolIds ) { rDstDesc.SetPoolFmtId( rSrcDesc.GetPoolFmtId() ); rDstDesc.SetPoolHelpId( rSrcDesc.GetPoolHelpId() ); // HelpFile-Id immer auf dflt setzen !! rDstDesc.SetPoolHlpFileId( UCHAR_MAX ); } if( rSrcDesc.GetFollow() != &rSrcDesc ) { SwPageDesc* pFollow = ::lcl_FindPageDesc( aPageDescs, rSrcDesc.GetFollow()->GetName() ); if( !pFollow ) { // dann mal kopieren sal_uInt16 nPos = MakePageDesc( rSrcDesc.GetFollow()->GetName() ); pFollow = aPageDescs[ nPos ]; CopyPageDesc( *rSrcDesc.GetFollow(), *pFollow ); } rDstDesc.SetFollow( pFollow ); bNotifyLayout = sal_True; } // die Header/Footer-Attribute werden gesondert kopiert, die Content- // Sections muessen vollstaendig mitgenommen werden! { SfxItemSet aAttrSet( rSrcDesc.GetMaster().GetAttrSet() ); aAttrSet.ClearItem( RES_HEADER ); aAttrSet.ClearItem( RES_FOOTER ); rDstDesc.GetMaster().DelDiffs( aAttrSet ); rDstDesc.GetMaster().SetFmtAttr( aAttrSet ); aAttrSet.ClearItem(); aAttrSet.Put( rSrcDesc.GetLeft().GetAttrSet() ); aAttrSet.ClearItem( RES_HEADER ); aAttrSet.ClearItem( RES_FOOTER ); rDstDesc.GetLeft().DelDiffs( aAttrSet ); rDstDesc.GetLeft().SetFmtAttr( aAttrSet ); } CopyHeader( rSrcDesc.GetMaster(), rDstDesc.GetMaster() ); CopyFooter( rSrcDesc.GetMaster(), rDstDesc.GetMaster() ); if( !rDstDesc.IsHeaderShared() ) CopyHeader( rSrcDesc.GetLeft(), rDstDesc.GetLeft() ); else rDstDesc.GetLeft().SetFmtAttr( rDstDesc.GetMaster().GetHeader() ); if( !rDstDesc.IsFooterShared() ) CopyFooter( rSrcDesc.GetLeft(), rDstDesc.GetLeft() ); else rDstDesc.GetLeft().SetFmtAttr( rDstDesc.GetMaster().GetFooter() ); if( bNotifyLayout && pTmpRoot ) { std::set<SwRootFrm*> aAllLayouts = GetAllLayouts();//swmod 080225 std::for_each( aAllLayouts.begin(), aAllLayouts.end(),std::mem_fun(&SwRootFrm::AllCheckPageDescs));//swmod 080226 } //Wenn sich FussnotenInfo veraendert, so werden die Seiten //angetriggert. if( !(rDstDesc.GetFtnInfo() == rSrcDesc.GetFtnInfo()) ) { rDstDesc.SetFtnInfo( rSrcDesc.GetFtnInfo() ); SwMsgPoolItem aInfo( RES_PAGEDESC_FTNINFO ); { rDstDesc.GetMaster().ModifyBroadcast( &aInfo, 0, TYPE(SwFrm) ); } { rDstDesc.GetLeft().ModifyBroadcast( &aInfo, 0, TYPE(SwFrm) ); } } } void SwDoc::ReplaceStyles( SwDoc& rSource ) { ::sw::UndoGuard const undoGuard(GetIDocumentUndoRedo()); CopyFmtArr( *rSource.pCharFmtTbl, *pCharFmtTbl, &SwDoc::_MakeCharFmt, *pDfltCharFmt ); CopyFmtArr( *rSource.pFrmFmtTbl, *pFrmFmtTbl, &SwDoc::_MakeFrmFmt, *pDfltFrmFmt ); CopyFmtArr( *rSource.pTxtFmtCollTbl, *pTxtFmtCollTbl, &SwDoc::_MakeTxtFmtColl, *pDfltTxtFmtColl ); // und jetzt noch die Seiten-Vorlagen sal_uInt16 nCnt = rSource.aPageDescs.Count(); if( nCnt ) { // ein anderes Doc -> Numberformatter muessen gemergt werden SwTblNumFmtMerge aTNFM( rSource, *this ); // 1. Schritt alle Formate anlegen (das 0. ueberspringen - Default!) while( nCnt ) { SwPageDesc *pSrc = rSource.aPageDescs[ --nCnt ]; if( 0 == ::lcl_FindPageDesc( aPageDescs, pSrc->GetName() ) ) MakePageDesc( pSrc->GetName() ); } // 2. Schritt alle Attribute kopieren, richtige Parents setzen for( nCnt = rSource.aPageDescs.Count(); nCnt; ) { SwPageDesc *pSrc = rSource.aPageDescs[ --nCnt ]; CopyPageDesc( *pSrc, *::lcl_FindPageDesc( aPageDescs, pSrc->GetName() )); } } //JP 08.04.99: und dann sind da noch die Numerierungs-Vorlagen nCnt = rSource.GetNumRuleTbl().Count(); if( nCnt ) { const SwNumRuleTbl& rArr = rSource.GetNumRuleTbl(); for( sal_uInt16 n = 0; n < nCnt; ++n ) { const SwNumRule& rR = *rArr[ n ]; if( !rR.IsAutoRule() ) { SwNumRule* pNew = FindNumRulePtr( rR.GetName()); if( pNew ) pNew->CopyNumRule( this, rR ); else MakeNumRule( rR.GetName(), &rR ); } } } if (undoGuard.UndoWasEnabled()) { // nodes array was modified! GetIDocumentUndoRedo().DelAllUndoObj(); } SetModified(); } SwFmt* SwDoc::FindFmtByName( const SvPtrarr& rFmtArr, const String& rName ) const { SwFmt* pFnd = 0; for( sal_uInt16 n = 0; n < rFmtArr.Count(); n++ ) { // ist die Vorlage schon im Doc vorhanden ?? if( ((SwFmt*)rFmtArr[n])->GetName() == rName ) { pFnd = (SwFmt*)rFmtArr[n]; break; } } return pFnd; } void SwDoc::MoveLeftMargin( const SwPaM& rPam, sal_Bool bRight, sal_Bool bModulus ) { SwHistory* pHistory = 0; if (GetIDocumentUndoRedo().DoesUndo()) { SwUndoMoveLeftMargin* pUndo = new SwUndoMoveLeftMargin( rPam, bRight, bModulus ); pHistory = &pUndo->GetHistory(); GetIDocumentUndoRedo().AppendUndo( pUndo ); } const SvxTabStopItem& rTabItem = (SvxTabStopItem&)GetDefault( RES_PARATR_TABSTOP ); sal_uInt16 nDefDist = rTabItem.Count() ? static_cast<sal_uInt16>(rTabItem[0].GetTabPos()) : 1134; const SwPosition &rStt = *rPam.Start(), &rEnd = *rPam.End(); SwNodeIndex aIdx( rStt.nNode ); while( aIdx <= rEnd.nNode ) { SwTxtNode* pTNd = aIdx.GetNode().GetTxtNode(); if( pTNd ) { SvxLRSpaceItem aLS( (SvxLRSpaceItem&)pTNd->SwCntntNode::GetAttr( RES_LR_SPACE ) ); // --> FME 2008-09-16 #i93873# See also lcl_MergeListLevelIndentAsLRSpaceItem in thints.cxx if ( pTNd->AreListLevelIndentsApplicable() ) { const SwNumRule* pRule = pTNd->GetNumRule(); if ( pRule ) { const int nListLevel = pTNd->GetActualListLevel(); if ( nListLevel >= 0 ) { const SwNumFmt& rFmt = pRule->Get(static_cast<sal_uInt16>(nListLevel)); if ( rFmt.GetPositionAndSpaceMode() == SvxNumberFormat::LABEL_ALIGNMENT ) { aLS.SetTxtLeft( rFmt.GetIndentAt() ); aLS.SetTxtFirstLineOfst( static_cast<short>(rFmt.GetFirstLineIndent()) ); } } } } long nNext = aLS.GetTxtLeft(); if( bModulus ) nNext = ( nNext / nDefDist ) * nDefDist; if( bRight ) nNext += nDefDist; else nNext -= nDefDist; aLS.SetTxtLeft( nNext ); SwRegHistory aRegH( pTNd, *pTNd, pHistory ); pTNd->SetAttr( aLS ); } aIdx++; } SetModified(); } sal_Bool SwDoc::DontExpandFmt( const SwPosition& rPos, sal_Bool bFlag ) { sal_Bool bRet = sal_False; SwTxtNode* pTxtNd = rPos.nNode.GetNode().GetTxtNode(); if( pTxtNd ) { bRet = pTxtNd->DontExpandFmt( rPos.nContent, bFlag ); if( bRet && GetIDocumentUndoRedo().DoesUndo() ) { GetIDocumentUndoRedo().AppendUndo( new SwUndoDontExpandFmt(rPos) ); } } return bRet; } SwTableBoxFmt* SwDoc::MakeTableBoxFmt() { SwTableBoxFmt* pFmt = new SwTableBoxFmt( GetAttrPool(), aEmptyStr, pDfltFrmFmt ); SetModified(); return pFmt; } SwTableLineFmt* SwDoc::MakeTableLineFmt() { SwTableLineFmt* pFmt = new SwTableLineFmt( GetAttrPool(), aEmptyStr, pDfltFrmFmt ); SetModified(); return pFmt; } void SwDoc::_CreateNumberFormatter() { RTL_LOGFILE_CONTEXT_AUTHOR( aLog, "SW", "JP93722", "SwDoc::_CreateNumberFormatter" ); ASSERT( !pNumberFormatter, "ist doch schon vorhanden" ); LanguageType eLang = LANGUAGE_SYSTEM; //System::GetLanguage(); /* ((const SvxLanguageItem&)GetAttrPool(). GetDefaultItem( RES_CHRATR_LANGUAGE )).GetLanguage(); */ Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory(); pNumberFormatter = new SvNumberFormatter( xMSF, eLang ); pNumberFormatter->SetEvalDateFormat( NF_EVALDATEFORMAT_FORMAT_INTL ); pNumberFormatter->SetYear2000(static_cast<sal_uInt16>(::utl::MiscCfg().GetYear2000())); } SwTblNumFmtMerge::SwTblNumFmtMerge( const SwDoc& rSrc, SwDoc& rDest ) : pNFmt( 0 ) { // ein anderes Doc -> Numberformatter muessen gemergt werden SvNumberFormatter* pN; if( &rSrc != &rDest && 0 != ( pN = ((SwDoc&)rSrc).GetNumberFormatter( sal_False ) )) ( pNFmt = rDest.GetNumberFormatter( sal_True ))->MergeFormatter( *pN ); if( &rSrc != &rDest ) ((SwGetRefFieldType*)rSrc.GetSysFldType( RES_GETREFFLD ))-> MergeWithOtherDoc( rDest ); } SwTblNumFmtMerge::~SwTblNumFmtMerge() { if( pNFmt ) pNFmt->ClearMergeTable(); } void SwDoc::SetTxtFmtCollByAutoFmt( const SwPosition& rPos, sal_uInt16 nPoolId, const SfxItemSet* pSet ) { SwPaM aPam( rPos ); SwTxtNode* pTNd = rPos.nNode.GetNode().GetTxtNode(); if( mbIsAutoFmtRedline && pTNd ) { // dann das Redline Object anlegen const SwTxtFmtColl& rColl = *pTNd->GetTxtColl(); SwRedline* pRedl = new SwRedline( nsRedlineType_t::REDLINE_FMTCOLL, aPam ); pRedl->SetMark(); // interressant sind nur die Items, die vom Set NICHT wieder // in den Node gesetzt werden. Also muss man die Differenz nehmen SwRedlineExtraData_FmtColl aExtraData( rColl.GetName(), rColl.GetPoolFmtId() ); if( pSet && pTNd->HasSwAttrSet() ) { SfxItemSet aTmp( *pTNd->GetpSwAttrSet() ); aTmp.Differentiate( *pSet ); // das Adjust Item behalten wir extra const SfxPoolItem* pItem; if( SFX_ITEM_SET == pTNd->GetpSwAttrSet()->GetItemState( RES_PARATR_ADJUST, sal_False, &pItem )) aTmp.Put( *pItem ); aExtraData.SetItemSet( aTmp ); } pRedl->SetExtraData( &aExtraData ); // !!!!!!!!! Undo fehlt noch !!!!!!!!!!!!!!!!!! AppendRedline( pRedl, true ); } SetTxtFmtColl( aPam, GetTxtCollFromPool( nPoolId ) ); if( pSet && pTNd && pSet->Count() ) { aPam.SetMark(); aPam.GetMark()->nContent.Assign( pTNd, pTNd->GetTxt().Len() ); InsertItemSet( aPam, *pSet, 0 ); } } void SwDoc::SetFmtItemByAutoFmt( const SwPaM& rPam, const SfxItemSet& rSet ) { SwTxtNode* pTNd = rPam.GetPoint()->nNode.GetNode().GetTxtNode(); RedlineMode_t eOld = GetRedlineMode(); if( mbIsAutoFmtRedline && pTNd ) { // dann das Redline Object anlegen SwRedline* pRedl = new SwRedline( nsRedlineType_t::REDLINE_FORMAT, rPam ); if( !pRedl->HasMark() ) pRedl->SetMark(); // interressant sind nur die Items, die vom Set NICHT wieder // in den Node gesetzt werden. Also muss man die Differenz nehmen SwRedlineExtraData_Format aExtraData( rSet ); /* if( pSet && pTNd->HasSwAttrSet() ) { SfxItemSet aTmp( *pTNd->GetpSwAttrSet() ); aTmp.Differentiate( *pSet ); // das Adjust Item behalten wir extra const SfxPoolItem* pItem; if( SFX_ITEM_SET == pTNd->GetpSwAttrSet()->GetItemState( RES_PARATR_ADJUST, sal_False, &pItem )) aTmp.Put( *pItem ); aExtraData.SetItemSet( aTmp ); } */ pRedl->SetExtraData( &aExtraData ); // !!!!!!!!! Undo fehlt noch !!!!!!!!!!!!!!!!!! AppendRedline( pRedl, true ); SetRedlineMode_intern( (RedlineMode_t)(eOld | nsRedlineMode_t::REDLINE_IGNORE)); } InsertItemSet( rPam, rSet, nsSetAttrMode::SETATTR_DONTEXPAND ); SetRedlineMode_intern( eOld ); } void SwDoc::ChgFmt(SwFmt & rFmt, const SfxItemSet & rSet) { if (GetIDocumentUndoRedo().DoesUndo()) { // copying <rSet> to <aSet> SfxItemSet aSet(rSet); // remove from <aSet> all items, which are already set at the format aSet.Differentiate(rFmt.GetAttrSet()); // <aSet> contains now all *new* items for the format // copying current format item set to <aOldSet> SfxItemSet aOldSet(rFmt.GetAttrSet()); // insert new items into <aOldSet> aOldSet.Put(aSet); // invalidate all new items in <aOldSet> in order to clear these items, // if the undo action is triggered. { SfxItemIter aIter(aSet); const SfxPoolItem * pItem = aIter.FirstItem(); while (pItem != NULL) { aOldSet.InvalidateItem(pItem->Which()); pItem = aIter.NextItem(); } } SwUndo * pUndo = new SwUndoFmtAttr(aOldSet, rFmt); GetIDocumentUndoRedo().AppendUndo(pUndo); } rFmt.SetFmtAttr(rSet); } void SwDoc::RenameFmt(SwFmt & rFmt, const String & sNewName, sal_Bool bBroadcast) { SfxStyleFamily eFamily = SFX_STYLE_FAMILY_ALL; if (GetIDocumentUndoRedo().DoesUndo()) { SwUndo * pUndo = NULL; switch (rFmt.Which()) { case RES_CHRFMT: pUndo = new SwUndoRenameCharFmt(rFmt.GetName(), sNewName, this); eFamily = SFX_STYLE_FAMILY_PARA; break; case RES_TXTFMTCOLL: pUndo = new SwUndoRenameFmtColl(rFmt.GetName(), sNewName, this); eFamily = SFX_STYLE_FAMILY_CHAR; break; case RES_FRMFMT: pUndo = new SwUndoRenameFrmFmt(rFmt.GetName(), sNewName, this); eFamily = SFX_STYLE_FAMILY_FRAME; break; default: break; } if (pUndo) { GetIDocumentUndoRedo().AppendUndo(pUndo); } } rFmt.SetName(sNewName); if (bBroadcast) BroadcastStyleOperation(sNewName, eFamily, SFX_STYLESHEET_MODIFIED); } // --> OD 2006-09-27 #i69627# namespace docfunc { bool HasOutlineStyleToBeWrittenAsNormalListStyle( SwDoc& rDoc ) { // If a parent paragraph style of one of the parargraph styles, which // are assigned to the list levels of the outline style, has a list style // set or inherits a list style from its parent style, the outline style // has to be written as a normal list style to the OpenDocument file // format or the OpenOffice.org file format. bool bRet( false ); const SwTxtFmtColls* pTxtFmtColls( rDoc.GetTxtFmtColls() ); if ( pTxtFmtColls ) { const sal_uInt16 nCount = pTxtFmtColls->Count(); for ( sal_uInt16 i = 0; i < nCount; ++i ) { SwTxtFmtColl* pTxtFmtColl = (*pTxtFmtColls)[i]; if ( pTxtFmtColl->IsDefault() || // pTxtFmtColl->GetOutlineLevel() == NO_NUMBERING ) //#outline level,zhaojianwei ! pTxtFmtColl->IsAssignedToListLevelOfOutlineStyle() ) //<-end,zhaojianwei { continue; } const SwTxtFmtColl* pParentTxtFmtColl = dynamic_cast<const SwTxtFmtColl*>( pTxtFmtColl->DerivedFrom()); if ( !pParentTxtFmtColl ) continue; if ( SFX_ITEM_SET == pParentTxtFmtColl->GetItemState( RES_PARATR_NUMRULE ) ) { // --> OD 2009-11-12 #i106218# // consider that the outline style is set const SwNumRuleItem& rDirectItem = pParentTxtFmtColl->GetNumRule(); if ( rDirectItem.GetValue() != rDoc.GetOutlineNumRule()->GetName() ) { bRet = true; break; } // <-- } } } return bRet; } } // <--
44,572
328
<reponame>zxzxzxygithub/AndroidMore /* * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * Vestibulum commodo. Ut rhoncus gravida arcu. */ package com.example.god.androidmore.datastructure; /** * 顺序存储方式线性表(ArrayList):查找效率高,插入删除效率低(ArrayList删除元素后,后面元素会向前位移) * ArrayList的本质是维护了一个对象数组,对ArrayList的增删改查即对数组进行操作 * 1. List接口中有sort方法,需要实现Comparator方法就能进行排序 * 2. List接口继承Collection,Collection集成Iterable * 3. System.arraycopy 是用于复制数组的native方法,应学会使用。 * * Vector: * 矢量队列,它是JDK1.0版本添加的类。 * 和ArrayList类似,内部维护一个对象数组。 * Vector 实现了RandmoAccess接口,即提供了随机访问功能。 * Vector中的操作是线程安全的,但比ArrayList稍微慢。 * @param <T> */ public class ArrayList<T> implements List<T> { private Object[] elementData; private int size; @Override public boolean isEmpty() { return elementData.length == 0; } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public boolean add(T t) { elementData[size++]=t; return true; } @Override public void clear() { for (int i = 0; i < elementData.length; i++) { elementData[i] = null; } } @Override public boolean remove(Object o) { int num = indexOf(o) - elementData.length - 1; System.arraycopy(elementData, indexOf(o) + 1, elementData, indexOf(o), num); return true; } @Override public boolean remove() { return false; } @Override public T get(int index) { if (index > elementData.length) { throw new IndexOutOfBoundsException(index + "越界"); } return (T) elementData[index]; } @Override public T set(int index, T t) { if (index > elementData.length) { throw new IndexOutOfBoundsException("index"); } elementData[index] = t; return t; } @Override public int indexOf(Object o) { if (o == null) { for (int i = 0; i < elementData.length; i++) { if (elementData[i] == null) { return i; } } } else { for (int i = 0; i < elementData.length; i++) { if (o.equals(elementData[i])) { return i; } } } return -1; } }
1,265
348
<filename>docs/data/leg-t2/040/04003289.json {"nom":"Sarraziet","circ":"3ème circonscription","dpt":"Landes","inscrits":160,"abs":58,"votants":102,"blancs":12,"nuls":4,"exp":86,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":44},{"nuance":"REM","nom":"<NAME>","voix":42}]}
112
1,144
#include <linux/init.h> #include <linux/kernel.h> #include <linux/clk.h> #include <asm/time.h> #include <adm8668.h> void __init plat_time_init(void) { struct clk *sys_clk; adm8668_init_clocks(); sys_clk = clk_get(NULL, "sys"); if (IS_ERR(sys_clk)) panic("unable to get system clock\n"); mips_hpt_frequency = clk_get_rate(sys_clk) / 2; }
163
392
<filename>mrec/examples/convert.py """ Convert sparse matrix from one file format to another. """ import os import subprocess def tsv2mtx(infile,outfile): num_users,num_items,nnz = 0,0,0 for line in open(infile): u,i,v = line.strip().split() u = int(u) i = int(i) if u > num_users: num_users = u if i > num_items: num_items = i nnz += 1 headerfile = outfile+'.header' with open(headerfile,'w') as header: print >>header,'%%MatrixMarket matrix coordinate real general' print >>header,'{0} {1} {2}'.format(num_users,num_items,nnz) subprocess.check_call(['cat',headerfile,infile],stdout=open(outfile,'w')) subprocess.check_call(['rm',headerfile]) def main(): from optparse import OptionParser from mrec import load_sparse_matrix, save_sparse_matrix parser = OptionParser() parser.add_option('--input_format',dest='input_format',help='format of input dataset tsv | csv | mm (matrixmarket) | csr (scipy.sparse.csr_matrix) | fsm (mrec.sparse.fast_sparse_matrix)') parser.add_option('--input',dest='input',help='filepath to input') parser.add_option('--output_format',dest='output_format',help='format of output dataset(s) tsv | csv | mm (matrixmarket) | csr (scipy.sparse.csr_matrix) | fsm (mrec.sparse.fast_sparse_matrix)') parser.add_option('--output',dest='output',help='filepath for output') (opts,args) = parser.parse_args() if not opts.input or not opts.output or not opts.input_format or not opts.output_format: parser.print_help() raise SystemExit if opts.output_format == opts.input_format: raise SystemExit('input and output format are the same, not doing anything') if opts.input_format == 'tsv' and opts.output_format == 'mm': # we can do this without loading the data tsv2mtx(opts.input,opts.output) else: data = load_sparse_matrix(opts.input_format,opts.input) save_sparse_matrix(data,opts.output_format,opts.output) if __name__ == '__main__': main()
858
3,451
<filename>website/package-lock.json { "requires": true, "lockfileVersion": 1, "dependencies": { "bulma": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/bulma/-/bulma-0.7.2.tgz", "integrity": "<KEY> "dev": true }, "bulma-dashboard": { "version": "0.1.34", "resolved": "https://registry.npmjs.org/bulma-dashboard/-/bulma-dashboard-0.1.34.tgz", "integrity": "<KEY> "dev": true }, "bulma-toc": { "version": "0.1.11", "resolved": "https://registry.npmjs.org/bulma-toc/-/bulma-toc-0.1.11.tgz", "integrity": "<KEY> "dev": true } } }
330
3,705
#pragma once #include <memory> #include <mutex> #include <ostream> #include <vector> #include "chainerx/array_body.h" namespace chainerx { namespace internal { // Keep track of array body allocation. // Used in combination with ArrayBodyLeakDetectionScope to detect leaks. // This class is thread safe. class ArrayBodyLeakTracker { public: void operator()(const std::shared_ptr<ArrayBody>& array_body); // Returns the array bodies which are still alive. // It is useful to detect unreleased array bodies, leaking from the scope of ArrayBodyLeakDetectionScope. std::vector<std::shared_ptr<ArrayBody>> GetAliveArrayBodies() const; // Asserts all the array bodies are freed in the leak tracker. bool IsAllArrayBodiesFreed(std::ostream& os) const; private: std::vector<std::weak_ptr<ArrayBody>> weak_ptrs_; mutable std::mutex mutex_; }; // A scope object to detect array body leaks. // It tracks newly created array bodies which are being set to arrays within the scope. // New array bodies are reported to the tracker specified in the constructor. // Only one leak detection scope can exist at any given moment class ArrayBodyLeakDetectionScope { public: explicit ArrayBodyLeakDetectionScope(ArrayBodyLeakTracker& tracker); ~ArrayBodyLeakDetectionScope(); ArrayBodyLeakDetectionScope(const ArrayBodyLeakDetectionScope&) = delete; ArrayBodyLeakDetectionScope& operator=(const ArrayBodyLeakDetectionScope&) = delete; ArrayBodyLeakDetectionScope(ArrayBodyLeakDetectionScope&& other) = delete; ArrayBodyLeakDetectionScope& operator=(ArrayBodyLeakDetectionScope&& other) = delete; static ArrayBodyLeakTracker* GetGlobalTracker() { return array_body_leak_tracker_; } private: // The global array body leak tracker. static ArrayBodyLeakTracker* array_body_leak_tracker_; }; // Throws an ChainerxError if any leakage is detected. Else, does nothing. void CheckAllArrayBodiesFreed(ArrayBodyLeakTracker& tracker); } // namespace internal } // namespace chainerx
614
1,025
<gh_stars>1000+ #import <Cocoa/Cocoa.h> @interface CDEEntityTableCellView : NSTableCellView #pragma mark - Properties @property (nonatomic, assign) NSInteger badgeValue; @property (nonatomic, weak) IBOutlet NSButton *badgeButton; @end
85
2,003
<filename>src/quota/helpers/quota_utils.h // Copyright (c) 2015-2018, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <string> #include "proto/quota.pb.h" namespace tera { namespace quota { class QuotaUtils { public: static std::string DebugPrintTableQuota(const TableQuota& table_quota); static std::string GetQuotaOperation(QuotaOperationType type); }; } }
163
368
// // push_session.h // my_push_server // // Created by luoning on 14-11-6. // Copyright (c) 2014年 luoning. All rights reserved. // #ifndef __my_push_server__push_session__ #define __my_push_server__push_session__ #include <stdio.h> #include "socket/epoll_io_loop.h" #include "socket/tcp_session_async.h" #include "push_session_handler.h" #include <memory> class CPushSession : public std::enable_shared_from_this<CPushSession> { public: CPushSession(CEpollIOLoop& io, S_SOCKET sock); virtual ~CPushSession(); uint32_t GetSocketID() { return m_pSession->GetSocketID(); } const char* GetRemoteIP() { return m_pSession->GetRemoteIP(); } int32_t GetRemotePort() { return m_pSession->GetRemotePort(); } BOOL Start(); BOOL Stop(); BOOL SendMsg(const char* szMsg, uint32_t nMsgSize); void SetHeartBeat(uint64_t nHeartBeat) { m_nLastHeartBeat = nHeartBeat; } uint64_t GetLastHeartBeat() { return m_nLastHeartBeat; } private: uint64_t m_nLastHeartBeat; CTCPSessionAsync* m_pSession; CEpollIOLoop& m_io; CPushSessionHandler m_handler; }; typedef std::shared_ptr<CPushSession> push_session_ptr; #endif /* defined(__my_push_server__push_session__) */
486
2,724
{ "default": { "sapUiThemeParamUrl1": "url(../../img1.jpg)", "sapUiThemeParamUrl2": "url('../../foo/img2.jpg')", "sapUiThemeParamUrl3": "url(\"../../foo/bar/img3.jpg\")", "sapUiThemeParamUrl4": "url()", "sapUiThemeParamUrl5": "url('')", "sapUiThemeParamUrl6": "url(\"\")", "sapUiThemeParamUrl7": "url('blob:http://example.com/6e88648c-00e1-4512-9695-5b702d8455b4')", "sapUiThemeParamUrl8": "url('data:text/plain;utf-8,foo')", "sapUiThemeParamUrl9": "none" }, "scopes": { } }
253
319
<filename>tools/LocalFeaturesTool/src/main/java/org/openimaj/tools/localfeature/LocalFeaturesMain.java<gh_stars>100-1000 /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * 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 University of Southampton 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. */ package org.openimaj.tools.localfeature; import java.lang.reflect.Method; /** * Main tool entry point * * @author <NAME> (<EMAIL>) */ public class LocalFeaturesMain { /** * Run the tool * @param args the arguments */ public static void main(String [] args) { if (args.length < 1) { System.err.println("Class name not specified"); return; } String clzname = args[0]; Class<?> clz; try { clz = Class.forName(clzname); } catch (ClassNotFoundException e) { try { clz = Class.forName("org.openimaj.tools.localfeature." + clzname); } catch (ClassNotFoundException e1) { System.err.println("Class corresponding to " + clzname +" not found."); return; } } String [] newArgs = new String[args.length-1]; for (int i=0; i<newArgs.length; i++) newArgs[i] = args[i+1]; Method method; try { method = clz.getMethod("main", String[].class); method.invoke(null, (Object)newArgs); } catch (Exception e) { System.err.println("Error invoking class " + clz +". Nested exception is:\n"); e.printStackTrace(System.err); } } }
929
14,668
// Copyright 2018 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. #include "chrome/browser/offline_pages/android/downloads/offline_page_share_helper.h" #include <utility> #include <vector> #include "base/android/jni_string.h" #include "base/bind.h" #include "base/callback.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/download/android/download_controller_base.h" #include "chrome/browser/download/android/download_utils.h" #include "chrome/browser/offline_pages/offline_page_mhtml_archiver.h" #include "components/offline_pages/core/offline_page_client_policy.h" #include "components/offline_pages/core/offline_page_feature.h" #include "components/offline_pages/core/offline_page_model.h" #include "components/offline_pages/core/page_criteria.h" using OfflineItemShareInfo = offline_items_collection::OfflineItemShareInfo; namespace offline_pages { namespace { content::WebContents* EmptyWebContentGetter() { return nullptr; } // Create share info with a content URI or file URI. We try best effort to get // content URI if |file_path| is in Android public directory. Then try to // fall back to file URI. If both failed, we will share the URL of the page // when share info is null or has empty URI. std::unique_ptr<OfflineItemShareInfo> CreateShareInfo( const base::FilePath& file_path) { auto share_info = std::make_unique<OfflineItemShareInfo>(); share_info->uri = DownloadUtils::GetUriStringForPath(file_path); return share_info; } } // namespace OfflinePageShareHelper::OfflinePageShareHelper(OfflinePageModel* model) : model_(model) {} OfflinePageShareHelper::~OfflinePageShareHelper() = default; void OfflinePageShareHelper::GetShareInfo(const ContentId& id, ResultCallback result_cb) { content_id_ = id; result_cb_ = std::move(result_cb); PageCriteria criteria; criteria.guid = content_id_.id; criteria.maximum_matches = 1; model_->GetPagesWithCriteria( criteria, base::BindOnce(&OfflinePageShareHelper::OnPageGetForShare, weak_ptr_factory_.GetWeakPtr())); } void OfflinePageShareHelper::OnPageGetForShare( const std::vector<OfflinePageItem>& pages) { if (pages.empty()) { // Continue to share without share info. NotifyCompletion(ShareResult::kSuccess, nullptr); return; } const OfflinePageItem& page = pages[0]; const bool is_suggested = GetPolicy(page.client_id.name_space).is_suggested; const bool in_private_dir = model_->IsArchiveInInternalDir(page.file_path); // Need to publish internal page to public directory to share the file with // content URI instead of the web page URL. if (!is_suggested && in_private_dir) { AcquireFileAccessPermission(); return; } // Try to share the mhtml file if the page is in public directory. NotifyCompletion(ShareResult::kSuccess, CreateShareInfo(page.file_path)); } void OfflinePageShareHelper::AcquireFileAccessPermission() { DownloadControllerBase::Get()->AcquireFileAccessPermission( base::BindRepeating(&EmptyWebContentGetter), base::BindOnce(&OfflinePageShareHelper::OnFileAccessPermissionDone, weak_ptr_factory_.GetWeakPtr())); } void OfflinePageShareHelper::OnFileAccessPermissionDone(bool granted) { if (!granted) { NotifyCompletion(ShareResult::kFileAccessPermissionDenied, nullptr); return; } // Retrieve the offline page again in case it's deleted. PageCriteria criteria; criteria.guid = content_id_.id; criteria.maximum_matches = 1; model_->GetPagesWithCriteria( criteria, base::BindOnce(&OfflinePageShareHelper::OnPageGetForPublish, weak_ptr_factory_.GetWeakPtr())); } void OfflinePageShareHelper::OnPageGetForPublish( const std::vector<OfflinePageItem>& pages) { if (pages.empty()) return; // Publish the page. model_->PublishInternalArchive( pages[0], base::BindOnce(&OfflinePageShareHelper::OnPagePublished, weak_ptr_factory_.GetWeakPtr())); } void OfflinePageShareHelper::OnPagePublished(const base::FilePath& file_path, SavePageResult result) { // Get the content URI after the page is published. NotifyCompletion(ShareResult::kSuccess, CreateShareInfo(file_path)); } void OfflinePageShareHelper::NotifyCompletion( ShareResult result, std::unique_ptr<OfflineItemShareInfo> share_info) { DCHECK(result_cb_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(result_cb_), result, content_id_, std::move(share_info))); } } // namespace offline_pages
1,694
1,191
/*****************************************************************************\ * * * Filename debugm.h * * * * Description Debug macros * * * * Notes OS-independant macros for managing distinct debug and * * release versions of a C or C++ program. * * The debug version is generated if the _DEBUG constant * * is defined. Else the release version is generated. * * These macros produce no extra code in the release version,* * and thus have no overhead in that release version. * * Even in the debug version, the debug output is disabled * * by default. It must be enabled by using DEBUG_ON(). * * * * Usage: * * - One source file must instanciate DEBUG_GLOBALS. * * - The source file parsing the arguments must look for one * * argument (Ex: --debug) and enable the debug mode. Ex: * * DEBUG_CODE( * * if (!strcmp(arg, "--debug")) DEBUG_ON(); * * ) * * - Insert DEBUG_ENTER() calls at the beginning of all * * routines that should be traced, and replace all their * * return instructions with RETURN_XXX() macros. * * - Pepper the sources with DEBUG_PRINTF() calls displaying * * critical intermediate values. * * * * The debug output will show the function call stack by * * indenting traced subroutines proportionally to their call * * depth. * * To make the debug output more readable, it is recommended * * to format it so that it looks like valid C code. * * * * The macros actually support multiple debug levels. * * Level 1 is the normal debug mode. * * Level 2 is the eXtra debug mode. Use it for displaying * * more detailed debug information, that is not needed in * * normal debugging sessions. * * More levels could be used if desired. * * * * DEBUG_GLOBALS Define global functions and variables used by * * macros below. Don't use the variables directly. * int iDebug = FALSE; Global variable enabling debug output if TRUE.* * int iIndent = 0; Global variable controlling debug indentation.* * int (*pdput)(const char *) Pointer to the put() routine for debug output.* * * * DEBUG_ON() Turn the debug mode on (Enables debug output) * * DEBUG_MORE() Increase the debug level * * DEBUG_LESS() Decrease the debug level * * DEBUG_OFF() Turn the debug mode off * * * * DEBUG_IS_ON() Test if the debug mode is enabled * * XDEBUG_ON() Turn eXtra debug mode on <==> 2*DEBUG_MORE() * * XDEBUG_IS_ON() Test if the eXtra debug mode is enabled * * * * DEBUG_CODE(code) Define code only in the _DEBUG version * * DEBUG_CODE_IF_ON(code) Debug code executed if debug mode is on * * XDEBUG_CODE_IF_ON(code) Debug code executed if eXtra debug mode is on * * * * SET_DEBUG_PUT(pFunc) Set the routine to use for debug output. * * Useful to replace the default routine with a * * thread-safe routine in multi-threaded programs. * * * DEBUG_PRINTF((format, ...)) Print a debug string if debug is on. * * The double parenthesis are necessary * * because C90 does not support macros * * with variable list of arguments. * * DEBUG_FPRINTF((iFile, fmt, ...)) Print a debug string to a stream * * * * Important: Any call to DEBUG_ENTER MUST be matched by one call to * * DEBUG_LEAVE or RETURN_... when the function returns . * * * * DEBUG_ENTER((format, ...)) Print a function name and arguments. * * Increase indentation of further calls.* * It's the caller's responsibility to * * format the routine name and arguments.* * DEBUG_LEAVE((format, ...)) Print a function return value. * * Decrease indentation of further calls.* * It's the caller's responsibility to * * format the return instruction & value.* * RETURN() Leave and trace return * * RETURN_CONST(value) Leave and trace return constant * * RETURN_BOOL(b) Leave and trace return boolean * * RETURN_INT(i) Leave and trace return integer * * RETURN_CHAR(c) Leave and trace return character * * RETURN_STRING(s) Leave and trace return string * * RETURN_PTR(p) Leave and trace return pointer * * RETURN_LONG(l) Leave and trace return long * * RETURN_CSTRING(s) Leave and trace return const. string * * RETURN_CPTR(p) Leave and trace return const. pointer * * * * RETURN_COMMENT((format, ...)) Leave, print comment and return * * RETURN_CONST_COMMENT(value, (...)) Leave, print comment & return a const.* * RETURN_BOOL_COMMENT(b, (...)) Leave, print comment & return a bool. * * RETURN_INT_COMMENT(i, (...)) Leave, print comment & return an int. * * * * Windows only: * * char *pszUtf8 = DEBUG_WSTR2NEWUTF8(pszUtf16); Create a new UTF-8 string * * DEBUG_FREEUTF8(pszUtf8); Free the UTF-8 string * * * * History: * * 2012-01-16 JFL <EMAIL> created this file. * * 2012-02-03 JFL Renamed DEBUG_IF_IS_ON DEBUG_CODE_IF_ON. * * Renamed file from debug.h to debugm.h because of a file * * name collision with another library on my PC. * * 2014-02-10 JFL Added macros for an extra debug mode. * * 2014-07-02 JFL renamed macro RETURN() as RETURN_CONST(), and defined * * new macro RETURN() to return nothing. * * Idem for RETURN_COMMENT() as RETURN_CONST_COMMENT(). * * 2016-09-09 JFL Flush every DEBUG_PRINTF output, to make sure to see * * every debug string printed before a program crash. * * 2016-09-13 JFL Added macros DEBUG_WSTR2NEWUTF8() and DEBUG_FREEUTF8(). * * 2016-10-04 JFL Added macros DEBUG_OFF(), DEBUG_MORE(), DEBUG_LESS(). * * Allow using DEBUG_ON()/MORE()/LESS()/OFF() in release mode. * 2017-03-22 JFL Rewrote DEBUG_PRINTF() and similar macros to generate a * * string, and output it in a single call to puts(). * * This is useful for multi-threaded programs, that need * * to use a semaphore for synchronizing debug output from * * multiple threads. * * The cost to pay for all this is that DEBUG_GLOBALS now * * defines several functions in addition to global variables.* * 2017-03-24 JFL Added macro SET_DEBUG_PUTS() to hide the global variable. * * 2017-03-29 JFL Revert to the old implementation for DOS, as the big * * DEBUG_GLOBALS macro sometimes chokes the DOS compiler. * * 2017-08-25 JFL Added an OS identification string definition. * * Bug fix in _VSNPRINTF_EMULATION. * * 2017-10-30 JFL Added macro DEBUG_QUIET_LEAVE(). * * 2018-02-02 JFL Added several missing DEBUG_xxx_COMMENT() macros. * * 2018-04-25 JFL Added macro DEBUG_WPRINTF(). * * Added macros DEBUG_WENTER() and DEBUG_WLEAVE(). * * 2018-10-01 JFL DEBUG_FREEUTF8() now clears the buffer pointer. * * 2019-04-15 JFL Changed the debug puts() routine to an fputs-based routine* * which does not implicitely outputs an \n in the end. * * Likewise, renamed SET_DEBUG_PUTS() as SET_DEBUG_PUT(). * * 2019-09-24 JFL Fixed bug in debug_vsprintf() using new try_vsnprintf(). * * 2020-03-19 JFL Fixed DEBUG_PRINT_MACRO() which sometimes failed in DOS * * and WIN95 when used with undefined macros. * * 2020-07-22 JFL Fixed bug in debug_vsprintf(): Make sure _vsnprintf() * * in try_vsnprintf() always appends a NUL to its output. * * 2020-07-24 JFL Rewrote debug_printf() to use the standard asprintf() as * * much as possible. * * 2020-12-11 JFL Added XDEBUG_WPRINTF and RETURN_DWORD* macros. * * * * (C) Copyright 2016 Hewlett Packard Enterprise Development LP * * Licensed under the Apache 2.0 license - www.apache.org/licenses/LICENSE-2.0 * \*****************************************************************************/ #ifndef _DEBUGM_H #define _DEBUGM_H 1 #include <stdio.h> /* Macros use printf */ #include <stdarg.h> #include <string.h> #include <stdlib.h> /* Macros use malloc */ #ifdef __cplusplus extern "C" { #endif #ifdef _MSC_VER #pragma warning(disable:4127) /* Avoid warnings on while(0) below */ #endif #define DEBUG_DO(code) do {code} while (0) #define DEBUG_DO_NOTHING() do {} while (0) /* Define Thread Local Storage attributes */ #if defined(_MSC_VER) && defined(_WIN32) /* Microsoft C in Windows */ #define DEBUG_TLS __declspec(thread) #elif defined(__unix__) /* Any Unix compiler */ #define DEBUG_TLS __thread #else /* _MSDOS */ /* MS-DOS */ #define DEBUG_TLS #endif #if defined(HAS_MSVCLIBX) || defined(GNU_SOURCE) /* If we have MsvcLibX or GNU asprintf() functions, use them */ #define _DEBUG_USE_ASPRINTF 1 #endif /* #undef _DEBUG_USE_ASPRINTF // For testing the alternate implementation */ #if _DEBUG_USE_ASPRINTF || (!defined(_MSC_VER)) || defined(_UCRT) /* If this library has a standard vsnprintf() function, use it */ #define _DEBUG_VSNPRINTF_DEFINITION #define debug_vsnprintf vsnprintf #elif !defined(_MSDOS) /* Else redefine them for MSVC versions before the UCRT was introduced, except for MS-DOS which does not support very large macros like that */ #define _DEBUG_VSNPRINTF_DEFINITION \ int debug_vsnprintf(char *pBuf, size_t nBufSize, const char *pszFormat, va_list vl) { \ char *pBuf2; \ int iRet; \ va_list vl0; \ /* First try it with the original arguments */ \ /* This consumes the vl arguments, which needs to be done once */ \ /* This also optimizes the number of calls, in the normal case where the output buffer was sized correctly */ \ va_copy(vl0, vl); /* Save a copy of the caller's va_list */ \ iRet = _vsnprintf(pBuf, nBufSize, pszFormat, vl); \ if (iRet >= 0) { /* Success, the output apparently fits in the buffer */ \ if ((size_t)iRet == nBufSize) if (pBuf && nBufSize) pBuf[nBufSize-1] = '\0'; /* Fix the missing NUL */ \ va_end(vl0); \ return iRet; \ } \ /* OK, this does not fit. Try it with larger and larger buffers, until we know the full output size */ \ iRet = vasprintf(&pBuf2, pszFormat, vl0); \ if (iRet >= 0) { /* Success at last, now we know the necessary size */ \ if (pBuf && nBufSize) { /* Copy whatever fits in the output buffer */ \ if (nBufSize-1) memcpy(pBuf, pBuf2, nBufSize-1); \ pBuf[nBufSize-1] = '\0'; /* Make sure there's a NUL in the end */ \ } \ free(pBuf2); \ } \ va_end(vl0); \ return iRet; \ } #endif #if _DEBUG_USE_ASPRINTF /* If we have MsvcLibX or GNU asprintf() functions, use them */ #define _DEBUG_ASPRINTF_DEFINITION #define debug_vasprintf vasprintf #define debug_asprintf asprintf #elif !defined(_MSDOS) /* Else redefine them, except for MS-DOS which does not support very large macros like that */ #define _DEBUG_ASPRINTF_DEFINITION \ int debug_vasprintf(char **ppszBuf, const char *pszFormat, va_list vl) { \ char *pBuf, *pBuf2; \ int n, nBufSize = 64; \ va_list vl0, vl2; \ /* First try it once with the original va_list (When nBufSize == 128) */ \ /* This consumes the vl arguments, which needs to be done once */ \ va_copy(vl0, vl); /* Save a copy of the caller's va_list */ \ for (pBuf = NULL; (pBuf2 = (char *)realloc(pBuf, nBufSize *= 2)) != NULL; ) { \ va_copy(vl2, vl0); \ n = debug_vsnprintf(pBuf = pBuf2, nBufSize, pszFormat, (nBufSize == 128) ? vl : vl2); \ va_end(vl2); \ if ((n >= 0) && (n < nBufSize)) { /* Success, now we know the necessary size */ \ pBuf2 = (char *)realloc(pBuf, n+1); /* Free the unused space in the end - May fail */ \ *ppszBuf = pBuf2 ? pBuf2 : pBuf; /* Return the valid one */ \ va_end(vl0); \ return n; \ } /* Else if n == nBufSize, actually not success, as there's no NUL in the end */ \ } \ va_end(vl0); \ return -1; \ } \ int debug_asprintf(char **ppszBuf, const char *pszFormat, ...) { \ int n; \ va_list vl; \ va_start(vl, pszFormat); \ n = debug_vasprintf(ppszBuf, pszFormat, vl); \ va_end(vl); \ return n; \ } #endif #if defined(HAS_MSVCLIBX) /* If we have the MsvcLibX dasprintf() functions, use it */ #define _DEBUG_DASPRINTF_DEFINITION #define debug_dasprintf dasprintf #else #define _DEBUG_DASPRINTF_DEFINITION \ char *debug_dasprintf(const char *pszFormat, ...) { \ char *pszBuf = NULL; \ va_list vl; \ va_start(vl, pszFormat); \ debug_vasprintf(&pszBuf, pszFormat, vl); /* Updates pszBuf only if successful */ \ va_end(vl); \ return pszBuf; \ } #endif /* Conditional compilation based on Microsoft's standard _DEBUG definition */ #if defined(_DEBUG) #define DEBUG_VERSION " Debug" #define DEBUG_GLOBAL_VARS \ int iDebug = 0; /* Global variable enabling debug output if TRUE. */ \ int DEBUG_TLS iIndent = 0; /* Global variable controlling debug indentation. */\ int debug_put(const char *str) { return fputs(str, stdout); } \ int (*pdput)(const char *) = debug_put; /* Debug output routine. Default: debug_put */ #if defined(_MSDOS) #define DEBUG_GLOBALS DEBUG_GLOBAL_VARS #else /* !defined(_MSDOS) */ #define DEBUG_GLOBALS \ DEBUG_GLOBAL_VARS \ _DEBUG_VSNPRINTF_DEFINITION \ _DEBUG_ASPRINTF_DEFINITION \ _DEBUG_DASPRINTF_DEFINITION \ int debug_printf(const char *pszFormat, ...) { \ char *pszBuf1, *pszBuf2; \ int n; \ va_list vl; \ va_start(vl, pszFormat); \ n = debug_vasprintf(&pszBuf1, pszFormat, vl); \ va_end(vl); \ if (n == -1) return -1; /* No memory for generating the debug output */ \ n = debug_asprintf(&pszBuf2, "%*s%s", iIndent, "", pszBuf1); \ if (n == -1) goto abort_debug_printf; \ pdput(pszBuf2); /* Output everything in a single system call. Useful if multithreaded. */ \ fflush(stdout); /* Make sure we see the output. Useful to see everything before a crash */\ free(pszBuf2); \ abort_debug_printf: \ free(pszBuf1); \ return n; \ } #endif /* defined(_MSDOS) */ extern int iDebug; /* Global variable enabling of disabling debug messages */ extern int (*pdput)(const char *); /* Pointer to the debug puts routine */ #if !defined(_MSDOS) extern int debug_printf(const char *fmt, ...); /* Print debug messages */ extern int debug_asprintf(char **, const char *fmt, ...); /* Print debug messages to a new buffer */ extern int debug_vasprintf(char **, const char *fmt, va_list vl); /* Common subroutine of the previous two */ extern char *debug_dasprintf(const char *fmt, ...); /* Shorter alternative used by other macros below */ #endif /* !defined(_MSDOS) */ #define DEBUG_ON() iDebug = 1 /* Turn debug mode on */ #define DEBUG_MORE() iDebug += 1 /* Increase the debug level */ #define DEBUG_LESS() iDebug -= 1 /* Decrease the debug level */ #define DEBUG_OFF() iDebug = 0 /* Turn debug mode off */ #define DEBUG_IS_ON() (iDebug > 0) /* Check if the debug mode is enabled */ #define XDEBUG_ON() iDebug = 2 /* Turn extra debug mode on. Same as calling DEBUG_MORE() twice. */ #define XDEBUG_IS_ON() (iDebug > 1) /* Check if the extra debug mode is enabled */ #define DEBUG_CODE(code) code /* Code included in the _DEBUG version only */ #define DEBUG_CODE_IF_ON(code) DEBUG_CODE(if (DEBUG_IS_ON()) {code}) /* Debug code executed if debug mode is on */ #define XDEBUG_CODE_IF_ON(code) DEBUG_CODE(if (XDEBUG_IS_ON()) {code}) /* Debug code executed if extra debug mode is on */ extern DEBUG_TLS int iIndent; /* Debug messages indentation. Thread local. */ #define DEBUG_INDENT_STEP 2 /* How many spaces to add for each indentation level */ #define DEBUG_PRINT_INDENT() printf("%*s", iIndent, "") /* Debug code, conditionally printing a string based on global variable 'debug' */ /* The enter and leave variants print, then respectively increase or decrease indentation, to make recursive calls easier to review. */ #define DEBUG_FPRINTF(args) DEBUG_DO(if (DEBUG_IS_ON()) {DEBUG_PRINT_INDENT(); fprintf args;}) #define DEBUG_WPRINTF(args) DEBUG_DO(if (DEBUG_IS_ON()) {DEBUG_PRINT_INDENT(); wprintf args;}) #define XDEBUG_WPRINTF(args) DEBUG_DO(if (XDEBUG_IS_ON()) {DEBUG_PRINT_INDENT(); wprintf args;}) #if defined(_MSDOS) #define DEBUG_PRINTF(args) DEBUG_DO(if (DEBUG_IS_ON()) {DEBUG_PRINT_INDENT(); printf args; fflush(stdout);}) #define XDEBUG_PRINTF(args) DEBUG_DO(if (XDEBUG_IS_ON()) {DEBUG_PRINT_INDENT(); printf args; fflush(stdout);}) #else /* !defined(_MSDOS) */ #define DEBUG_PRINTF(args) DEBUG_DO(if (DEBUG_IS_ON()) {debug_printf args;}) #define XDEBUG_PRINTF(args) DEBUG_DO(if (XDEBUG_IS_ON()) {debug_printf args;}) #endif /* defined(_MSDOS) */ #define DEBUG_ENTER(args) DEBUG_DO(DEBUG_PRINTF(args); iIndent += DEBUG_INDENT_STEP;) #define DEBUG_WENTER(args) DEBUG_DO(DEBUG_WPRINTF(args); iIndent += DEBUG_INDENT_STEP;) #define DEBUG_LEAVE(args) DEBUG_DO(DEBUG_PRINTF(args); iIndent -= DEBUG_INDENT_STEP;) #define DEBUG_WLEAVE(args) DEBUG_DO(DEBUG_WPRINTF(args); iIndent -= DEBUG_INDENT_STEP;) #define DEBUG_QUIET_LEAVE() DEBUG_DO(iIndent -= DEBUG_INDENT_STEP;) #define DEBUG_RETURN_INT(i, comment) DEBUG_DO(int DEBUG_i = (i); \ DEBUG_LEAVE(("return %d; // " comment "\n", DEBUG_i)); return DEBUG_i;) /* print return instruction and decrease indent */ #define RETURN() DEBUG_DO(DEBUG_LEAVE(("return;\n")); return;) #define RETURN_CONST(k) DEBUG_DO(DEBUG_LEAVE(("return %s;\n", #k)); return k;) #define RETURN_INT(i) DEBUG_DO(int DEBUG_i = (i); \ DEBUG_LEAVE(("return %d;\n", DEBUG_i)); return DEBUG_i;) #define RETURN_STRING(s) DEBUG_DO(char *DEBUG_s = (s); \ DEBUG_LEAVE(("return \"%s\";\n", DEBUG_s)); return DEBUG_s;) #define RETURN_CHAR(c) DEBUG_DO(char DEBUG_c = (c); \ DEBUG_LEAVE(("return '%c';\n", DEBUG_c)); return DEBUG_c;) #define RETURN_BOOL(b) DEBUG_DO(int DEBUG_b = (b); \ DEBUG_LEAVE(("return %s;\n", DEBUG_b ? "TRUE" : "FALSE")); return DEBUG_b;) #define RETURN_PTR(p) DEBUG_DO(void *DEBUG_p = (p); \ DEBUG_LEAVE(("return %p;\n", DEBUG_p)); return DEBUG_p;) #define RETURN_LONG(l) DEBUG_DO(long DEBUG_l = (l); \ DEBUG_LEAVE(("return %ld;\n", DEBUG_l)); return DEBUG_l;) #define RETURN_CSTRING(s) DEBUG_DO(const char *DEBUG_s = (s); \ DEBUG_LEAVE(("return \"%s\";\n", DEBUG_s)); return DEBUG_s;) #define RETURN_CPTR(p) DEBUG_DO(const void *DEBUG_p = (p); \ DEBUG_LEAVE(("return %p;\n", DEBUG_p)); return DEBUG_p;) #define RETURN_DWORD(dw) DEBUG_DO(DWORD DEBUG_dw = (dw); \ DEBUG_LEAVE(("return 0x%lX;\n", DEBUG_dw)); return DEBUG_dw;) #if defined(_MSDOS) #define RETURN_COMMENT(args) DEBUG_DO(DEBUG_LEAVE(("return; // ")); \ if (DEBUG_IS_ON()) printf args; return;) #define RETURN_CONST_COMMENT(k, args) DEBUG_DO(DEBUG_LEAVE(("return %s; // ", #k)); \ if (DEBUG_IS_ON()) printf args; return k;) #define RETURN_INT_COMMENT(i, args) DEBUG_DO(int DEBUG_i = (i); \ DEBUG_LEAVE(("return %d; // ", DEBUG_i)); if (DEBUG_IS_ON()) printf args; return DEBUG_i;) #define RETURN_STRING_COMMENT(s, args) DEBUG_DO(char *DEBUG_s = (s); \ DEBUG_LEAVE(("return \"%s\"; // \n", DEBUG_s)); if (DEBUG_IS_ON()) printf args; return DEBUG_s;) #define RETURN_CHAR_COMMENT(c, args) DEBUG_DO(char DEBUG_c = (c); \ DEBUG_LEAVE(("return '%c'; // \n", DEBUG_c)); if (DEBUG_IS_ON()) printf args; return DEBUG_c;) #define RETURN_BOOL_COMMENT(b, args) DEBUG_DO(int DEBUG_b = (b); \ DEBUG_LEAVE(("return %s; // ", DEBUG_b ? "TRUE" : "FALSE")); if (DEBUG_IS_ON()) printf args; return DEBUG_b;) #define RETURN_PTR_COMMENT(p, args) DEBUG_DO(void *DEBUG_p = (p); \ DEBUG_LEAVE(("return %p; // \n", DEBUG_p)); if (DEBUG_IS_ON()) printf args; return DEBUG_p;) #define RETURN_LONG_COMMENT(l, args) DEBUG_DO(long DEBUG_l = (l); \ DEBUG_LEAVE(("return %ld; // \n", DEBUG_l)); if (DEBUG_IS_ON()) printf args; return DEBUG_l;) #define RETURN_CSTRING_COMMENT(s, args) DEBUG_DO(const char *DEBUG_s = (s); \ DEBUG_LEAVE(("return \"%s\"; // \n", DEBUG_s)); if (DEBUG_IS_ON()) printf args; return DEBUG_s;) #define RETURN_CPTR_COMMENT(p, args) DEBUG_DO(const void *DEBUG_p = (p); \ DEBUG_LEAVE(("return %p; // \n", DEBUG_p)); if (DEBUG_IS_ON()) printf args; return DEBUG_p;) #define RETURN_DWORD_COMMENT(dw, args) DEBUG_DO(DWORD DEBUG_dw = (dw); \ DEBUG_LEAVE(("return 0x%lX; // \n", DEBUG_dw)); if (DEBUG_IS_ON()) printf args; return DEBUG_dw;) #else /* !defined(_MSDOS) */ #define RETURN_COMMENT(args) DEBUG_DO(char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return; // %s", DEBUG_buf)); free(DEBUG_buf); return;) #define RETURN_CONST_COMMENT(k, args) DEBUG_DO(char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %s; // %s", #k, DEBUG_buf)); free(DEBUG_buf); return k;) #define RETURN_INT_COMMENT(i, args) DEBUG_DO(int DEBUG_i = (i); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %d; // %s", DEBUG_i, DEBUG_buf)); free(DEBUG_buf); return DEBUG_i;) #define RETURN_STRING_COMMENT(s, args) DEBUG_DO(char *DEBUG_s = (s); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %s; // %s", DEBUG_s, DEBUG_buf)); free(DEBUG_buf); return DEBUG_s;) #define RETURN_CHAR_COMMENT(c, args) DEBUG_DO(char DEBUG_c = (c); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %c; // %s", DEBUG_c, DEBUG_buf)); free(DEBUG_buf); return DEBUG_c;) #define RETURN_BOOL_COMMENT(b, args) DEBUG_DO(int DEBUG_b = (b); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %s; // %s", DEBUG_b ? "TRUE" : "FALSE", DEBUG_buf)); free(DEBUG_buf); return DEBUG_b;) #define RETURN_PTR_COMMENT(p, args) DEBUG_DO(void *DEBUG_p = (p); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %p; // %s", DEBUG_p, DEBUG_buf)); free(DEBUG_buf); return DEBUG_p;) #define RETURN_LONG_COMMENT(l, args) DEBUG_DO(long DEBUG_l = (l); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %l; // %s", DEBUG_l, DEBUG_buf)); free(DEBUG_buf); return DEBUG_l;) #define RETURN_CSTRING_COMMENT(s, args) DEBUG_DO(const char *DEBUG_s = (s); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %s; // %s", DEBUG_s, DEBUG_buf)); free(DEBUG_buf); return DEBUG_s;) #define RETURN_CPTR_COMMENT(p, args) DEBUG_DO(const void *DEBUG_p = (p); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return %p; // %s", DEBUG_p, DEBUG_buf)); free(DEBUG_buf); return DEBUG_p;) #define RETURN_DWORD_COMMENT(dw, args) DEBUG_DO(DWORD DEBUG_dw = (dw); char *DEBUG_buf = NULL; \ if (DEBUG_IS_ON()) DEBUG_buf = debug_dasprintf args; DEBUG_LEAVE(("return 0x%X; // %s", DEBUG_dw, DEBUG_buf)); free(DEBUG_buf); return DEBUG_dw;) #endif /* defined(_MSDOS) */ #define SET_DEBUG_PUT(pFunc) pdput = pFunc /* Set the debug put routine */ #else /* !defined(_DEBUG) */ #define DEBUG_VERSION "" /* Non debug version: Simply don't say it */ #define DEBUG_GLOBALS #define DEBUG_ON() (void)0 #define DEBUG_MORE() (void)0 #define DEBUG_LESS() (void)0 #define DEBUG_OFF() (void)0 #define DEBUG_IS_ON() 0 #define XDEBUG_IS_ON() 0 #define DEBUG_CODE(code) /* Code included in _DEBUG version only */ #define DEBUG_CODE_IF_ON(code) /* Code included in _DEBUG version only */ #define XDEBUG_CODE_IF_ON(code) /* Code included in _DEBUG version only */ #define DEBUG_PRINT_INDENT() DEBUG_DO_NOTHING() /* Print call-depth spaces */ #define DEBUG_FPRINTF(args) DEBUG_DO_NOTHING() /* Print a debug string to a stream */ #define DEBUG_WPRINTF(args) DEBUG_DO_NOTHING() /* Print a wide debug string to stdout */ #define DEBUG_PRINTF(args) DEBUG_DO_NOTHING() /* Print a debug string to stdout */ #define XDEBUG_PRINTF(args) DEBUG_DO_NOTHING() /* Print an extra debug string to stdout */ #define XDEBUG_WPRINTF(args) DEBUG_DO_NOTHING() /* Print an extra debug string to stdout */ #define DEBUG_ENTER(args) DEBUG_DO_NOTHING() /* Print and increase indent */ #define DEBUG_WENTER(args) DEBUG_DO_NOTHING() /* Print and increase indent */ #define DEBUG_LEAVE(args) DEBUG_DO_NOTHING() /* Print and decrease indent */ #define DEBUG_WLEAVE(args) DEBUG_DO_NOTHING() /* Print and decrease indent */ #define DEBUG_QUIET_LEAVE() DEBUG_DO_NOTHING() /* Print and decrease indent */ #define DEBUG_RETURN_INT(i, comment) return(i) /* print return instruction and decrease indent */ #define RETURN() return #define RETURN_CONST(k) return(k) #define RETURN_INT(i) return(i) #define RETURN_STRING(s) return(s) #define RETURN_CHAR(c) return(c) #define RETURN_BOOL(b) return(b) #define RETURN_PTR(p) return(p) #define RETURN_LONG(l) return(l) #define RETURN_CSTRING(s) return(s) #define RETURN_CPTR(p) return(p) #define RETURN_DWORD(dw) return(dw) #define RETURN_COMMENT(args) return #define RETURN_CONST_COMMENT(k, args) return(k) #define RETURN_INT_COMMENT(i, args) return(i) #define RETURN_STRING_COMMENT(s, args) return(s) #define RETURN_CHAR_COMMENT(c, args) return(c) #define RETURN_BOOL_COMMENT(b, args) return(b) #define RETURN_PTR_COMMENT(p, args) return(p) #define RETURN_LONG_COMMENT(l, args) return(l) #define RETURN_CSTRING_COMMENT(s, args) return(s) #define RETURN_CPTR_COMMENT(p, args) return(p) #define RETURN_DWORD_COMMENT(dw, args) return(dw) #define SET_DEBUG_PUT(pFunc) DEBUG_DO_NOTHING() /* Set the debug put routine */ #endif /* defined(_DEBUG) */ #define STRINGIZE(s) #s /* Convert a macro name to a string */ #define VALUEIZE(s) STRINGIZE(s) /* Convert a macro value to a string */ #define MACRODEF(s) "#define " #s " " STRINGIZE(s) /* Display a macro name and value. */ #define DEBUG_PRINT_MACRO(name) DEBUG_DO( \ const char *pszName = #name; /* Don't use STRINGIZE because we're already inside a macro */ \ const char *pszValue = "" STRINGIZE(name); /* Don't use VALUEIZE because we're already inside a macro */ \ DEBUG_PRINT_INDENT(); \ if (strcmp(pszName, pszValue)) { \ printf("#define %s %s\n", pszName, pszValue); \ } else { /* Not 100% certain, but most likely. */ \ printf("#undef %s\n", pszName); \ } \ ) #ifdef _WIN32 /* Helper macros for displaying Unicode strings */ #define DEBUG_WSTR2UTF8(from, to, toSize) DEBUG_CODE( \ WideCharToMultiByte(CP_UTF8, 0, from, lstrlenW(from)+1, to, toSize, NULL, NULL); \ ) /* Dynamically allocate a new buffer, then convert a Unicode string to UTF-8 */ /* The dynamic allocation is useful in modules using lots of UTF-16 pathnames. This avoids having many local buffers of length UTF8_PATH_MAX, which may make the stack grow too large and overflow. */ #define DEBUG_WSTR2NEWUTF8(pwStr, pUtf8) \ DEBUG_CODE( \ do { \ int nUtf8 = (int)lstrlenW(pwStr) * 2 + 1; \ pUtf8 = malloc(nUtf8); \ DEBUG_WSTR2UTF8(pwStr, pUtf8, nUtf8); \ } while (0); \ ) /* DEBUG_FREE(pUtf8) MUST be used to free the UTF-8 string after use, else there will be a memory leak */ /* Clear the pointer, so that DEBUG_FREEUTF8() can safely be called again */ #define DEBUG_FREEUTF8(pUtf8) DEBUG_CODE(do {free(pUtf8); pUtf8 = NULL;} while (0)) #endif /* defined(_WIN32) */ #ifdef __cplusplus } #endif #endif /* !defined(_DEBUGM_H) */
13,228
2,406
<filename>inference-engine/tests/functional/inference_engine/transformations/convert_nms_gather_path_to_unsigned_test.cpp<gh_stars>1000+ // Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include "common_test_utils/ngraph_test_utils.hpp" #include "ngraph/pass/visualize_tree.hpp" #include <ngraph/function.hpp> #include <ngraph/opsets/opset8.hpp> #include <ngraph/pass/manager.hpp> #include <transformations/common_optimizations/convert_nms_gather_path_to_unsigned.hpp> #include <transformations/init_node_info.hpp> using namespace testing; using namespace ngraph; using namespace std; TEST(TransformationTests, test_convert_to_unsigned_nms_gather_1) { // if Convert doesn't exist shared_ptr<Function> f(nullptr), f_ref(nullptr); { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, squeeze_node, opset8::Constant::create(element::i32, Shape{1}, {0})); f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u64); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); f_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } auto res = compare_functions(f, f_ref); ASSERT_TRUE(res.first) << res.second; } TEST(TransformationTests, test_convert_to_unsigned_nms_gather_2) { // if Convert already exists shared_ptr<Function> f(nullptr), f_ref(nullptr); { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::i32); // usually input to gather data goes after reshape NMS scores auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); } { auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto begin = opset8::Constant::create(element::i32, Shape{1}, {3}); auto end = opset8::Constant::create(element::i32, Shape{1}, {4}); auto strides = opset8::Constant::create(element::i32, Shape{1}, {1}); auto ss_node = make_shared<opset8::StridedSlice>(nms->output(0), begin, end, strides, vector<int64_t>{1, 0}, vector<int64_t>{1, 0}); // squeeze can be represented as reshape auto squeeze_node = make_shared<opset8::Reshape>(ss_node, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto convert = make_shared<opset8::Convert>(squeeze_node, element::Type_t::u32); auto reshape_node = make_shared<opset8::Reshape>(scores, opset8::Constant::create(element::i32, Shape{1}, {-1}), true); auto gather = make_shared<opset8::Gather>(reshape_node, convert, opset8::Constant::create(element::i32, Shape{1}, {0})); f_ref = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); } auto res = compare_functions(f, f_ref); ASSERT_TRUE(res.first) << res.second; } TEST(TransformationTests, test_convert_to_unsigned_nms_gather_3) { // if NMS output goes not into Gather indices no converts should be inserted auto boxes = make_shared<opset8::Parameter>(element::f32, Shape{1, 1000, 4}); auto scores = make_shared<opset8::Parameter>(element::f32, Shape{1, 1, 1000}); auto nms = make_shared<opset8::NonMaxSuppression>(boxes, scores); auto gather = make_shared<opset8::Gather>(nms->output(0), opset8::Constant::create(element::i32, Shape{1}, {2}), opset8::Constant::create(element::i32, Shape{1}, {0})); shared_ptr<Function> f = make_shared<Function>(NodeVector{gather}, ParameterVector{boxes, scores}); pass::Manager manager; manager.register_pass<pass::InitNodeInfo>(); manager.register_pass<pass::ConvertNmsGatherPathToUnsigned>(); manager.run_passes(f); ASSERT_NO_THROW(check_rt_info(f)); ASSERT_EQ(count_ops_of_type<opset1::Convert>(f), 0); }
3,074
777
// 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. #include "content/browser/service_worker/service_worker_cache_writer.h" #include <algorithm> #include <string> #include "content/browser/appcache/appcache_response.h" #include "content/browser/service_worker/service_worker_disk_cache.h" #include "content/browser/service_worker/service_worker_storage.h" namespace { const size_t kCopyBufferSize = 16 * 1024; // Shim class used to turn always-async functions into async-or-result // functions. See the comments below near ReadInfoHelper. class AsyncOnlyCompletionCallbackAdaptor : public base::RefCounted<AsyncOnlyCompletionCallbackAdaptor> { public: explicit AsyncOnlyCompletionCallbackAdaptor( const net::CompletionCallback& callback) : async_(false), result_(net::ERR_IO_PENDING), callback_(callback) {} void set_async(bool async) { async_ = async; } bool async() { return async_; } int result() { return result_; } void WrappedCallback(int result) { result_ = result; if (async_) callback_.Run(result); } private: friend class base::RefCounted<AsyncOnlyCompletionCallbackAdaptor>; virtual ~AsyncOnlyCompletionCallbackAdaptor() {} bool async_; int result_; net::CompletionCallback callback_; }; } // namespace namespace content { int ServiceWorkerCacheWriter::DoLoop(int status) { do { switch (state_) { case STATE_START: status = DoStart(status); break; case STATE_READ_HEADERS_FOR_COMPARE: status = DoReadHeadersForCompare(status); break; case STATE_READ_HEADERS_FOR_COMPARE_DONE: status = DoReadHeadersForCompareDone(status); break; case STATE_READ_DATA_FOR_COMPARE: status = DoReadDataForCompare(status); break; case STATE_READ_DATA_FOR_COMPARE_DONE: status = DoReadDataForCompareDone(status); break; case STATE_READ_HEADERS_FOR_COPY: status = DoReadHeadersForCopy(status); break; case STATE_READ_HEADERS_FOR_COPY_DONE: status = DoReadHeadersForCopyDone(status); break; case STATE_READ_DATA_FOR_COPY: status = DoReadDataForCopy(status); break; case STATE_READ_DATA_FOR_COPY_DONE: status = DoReadDataForCopyDone(status); break; case STATE_WRITE_HEADERS_FOR_PASSTHROUGH: status = DoWriteHeadersForPassthrough(status); break; case STATE_WRITE_HEADERS_FOR_PASSTHROUGH_DONE: status = DoWriteHeadersForPassthroughDone(status); break; case STATE_WRITE_DATA_FOR_PASSTHROUGH: status = DoWriteDataForPassthrough(status); break; case STATE_WRITE_DATA_FOR_PASSTHROUGH_DONE: status = DoWriteDataForPassthroughDone(status); break; case STATE_WRITE_HEADERS_FOR_COPY: status = DoWriteHeadersForCopy(status); break; case STATE_WRITE_HEADERS_FOR_COPY_DONE: status = DoWriteHeadersForCopyDone(status); break; case STATE_WRITE_DATA_FOR_COPY: status = DoWriteDataForCopy(status); break; case STATE_WRITE_DATA_FOR_COPY_DONE: status = DoWriteDataForCopyDone(status); break; case STATE_DONE: status = DoDone(status); break; default: NOTREACHED() << "Unknown state in DoLoop"; state_ = STATE_DONE; break; } } while (status != net::ERR_IO_PENDING && state_ != STATE_DONE); io_pending_ = (status == net::ERR_IO_PENDING); return status; } ServiceWorkerCacheWriter::ServiceWorkerCacheWriter( std::unique_ptr<ServiceWorkerResponseReader> compare_reader, std::unique_ptr<ServiceWorkerResponseReader> copy_reader, std::unique_ptr<ServiceWorkerResponseWriter> writer) : state_(STATE_START), io_pending_(false), comparing_(false), did_replace_(false), compare_reader_(std::move(compare_reader)), copy_reader_(std::move(copy_reader)), writer_(std::move(writer)), weak_factory_(this) {} ServiceWorkerCacheWriter::~ServiceWorkerCacheWriter() {} net::Error ServiceWorkerCacheWriter::MaybeWriteHeaders( HttpResponseInfoIOBuffer* headers, const OnWriteCompleteCallback& callback) { DCHECK(!io_pending_); headers_to_write_ = headers; pending_callback_ = callback; DCHECK_EQ(state_, STATE_START); int result = DoLoop(net::OK); // Synchronous errors and successes always go to STATE_DONE. if (result != net::ERR_IO_PENDING) DCHECK_EQ(state_, STATE_DONE); // ERR_IO_PENDING has to have one of the STATE_*_DONE states as the next state // (not STATE_DONE itself). if (result == net::ERR_IO_PENDING) { DCHECK(state_ == STATE_READ_HEADERS_FOR_COMPARE_DONE || state_ == STATE_WRITE_HEADERS_FOR_COPY_DONE || state_ == STATE_WRITE_HEADERS_FOR_PASSTHROUGH_DONE) << "Unexpected state: " << state_; io_pending_ = true; } return result >= 0 ? net::OK : static_cast<net::Error>(result); } net::Error ServiceWorkerCacheWriter::MaybeWriteData( net::IOBuffer* buf, size_t buf_size, const OnWriteCompleteCallback& callback) { DCHECK(!io_pending_); data_to_write_ = buf; len_to_write_ = buf_size; pending_callback_ = callback; if (comparing_) state_ = STATE_READ_DATA_FOR_COMPARE; else state_ = STATE_WRITE_DATA_FOR_PASSTHROUGH; int result = DoLoop(net::OK); // Synchronous completions are always STATE_DONE. if (result != net::ERR_IO_PENDING) DCHECK_EQ(state_, STATE_DONE); // Asynchronous completion means the state machine must be waiting in one of // the Done states for an IO operation to complete: if (result == net::ERR_IO_PENDING) { // Note that STATE_READ_HEADERS_FOR_COMPARE_DONE is excluded because the // headers are compared in MaybeWriteHeaders, not here, and // STATE_WRITE_HEADERS_FOR_PASSTHROUGH_DONE is excluded because that write // is done by MaybeWriteHeaders. DCHECK(state_ == STATE_READ_DATA_FOR_COMPARE_DONE || state_ == STATE_READ_HEADERS_FOR_COPY_DONE || state_ == STATE_READ_DATA_FOR_COPY_DONE || state_ == STATE_WRITE_HEADERS_FOR_COPY_DONE || state_ == STATE_WRITE_DATA_FOR_COPY_DONE || state_ == STATE_WRITE_DATA_FOR_PASSTHROUGH_DONE) << "Unexpected state: " << state_; } return result >= 0 ? net::OK : static_cast<net::Error>(result); } int ServiceWorkerCacheWriter::DoStart(int result) { bytes_written_ = 0; if (compare_reader_) { state_ = STATE_READ_HEADERS_FOR_COMPARE; comparing_ = true; } else { // No existing reader, just write the headers back directly. state_ = STATE_WRITE_HEADERS_FOR_PASSTHROUGH; comparing_ = false; } return net::OK; } int ServiceWorkerCacheWriter::DoReadHeadersForCompare(int result) { DCHECK_GE(result, 0); DCHECK(headers_to_write_); headers_to_read_ = new HttpResponseInfoIOBuffer; state_ = STATE_READ_HEADERS_FOR_COMPARE_DONE; return ReadInfoHelper(compare_reader_, headers_to_read_.get()); } int ServiceWorkerCacheWriter::DoReadHeadersForCompareDone(int result) { if (result < 0) { state_ = STATE_DONE; return result; } cached_length_ = headers_to_read_->response_data_size; bytes_compared_ = 0; state_ = STATE_DONE; return net::OK; } int ServiceWorkerCacheWriter::DoReadDataForCompare(int result) { DCHECK_GE(result, 0); DCHECK(data_to_write_); data_to_read_ = new net::IOBuffer(len_to_write_); len_to_read_ = len_to_write_; state_ = STATE_READ_DATA_FOR_COMPARE_DONE; compare_offset_ = 0; // If this was an EOF, don't issue a read. if (len_to_write_ > 0) result = ReadDataHelper(compare_reader_, data_to_read_.get(), len_to_read_); return result; } int ServiceWorkerCacheWriter::DoReadDataForCompareDone(int result) { DCHECK(data_to_read_); DCHECK(data_to_write_); DCHECK_EQ(len_to_read_, len_to_write_); if (result < 0) { state_ = STATE_DONE; return result; } DCHECK_LE(result + compare_offset_, static_cast<size_t>(len_to_write_)); // Premature EOF while reading the service worker script cache data to // compare. Fail the comparison. if (result == 0 && len_to_write_ != 0) { comparing_ = false; state_ = STATE_READ_HEADERS_FOR_COPY; return net::OK; } // Compare the data from the ServiceWorker script cache to the data from the // network. if (memcmp(data_to_read_->data(), data_to_write_->data() + compare_offset_, result)) { // Data mismatched. This method already validated that all the bytes through // |bytes_compared_| were identical, so copy the first |bytes_compared_| // over, then start writing network data back after the changed point. comparing_ = false; state_ = STATE_READ_HEADERS_FOR_COPY; return net::OK; } compare_offset_ += result; // This is a little bit tricky. It is possible that not enough data was read // to finish comparing the entire block of data from the network (which is // kept in len_to_write_), so this method may need to issue another read and // return to this state. // // Compare isn't complete yet. Issue another read for the remaining data. Note // that this reuses the same IOBuffer. if (compare_offset_ < static_cast<size_t>(len_to_read_)) { state_ = STATE_READ_DATA_FOR_COMPARE_DONE; return ReadDataHelper(compare_reader_, data_to_read_.get(), len_to_read_ - compare_offset_); } // Cached entry is longer than the network entry but the prefix matches. Copy // just the prefix. if (len_to_read_ == 0 && bytes_compared_ + compare_offset_ < cached_length_) { comparing_ = false; state_ = STATE_READ_HEADERS_FOR_COPY; return net::OK; } // bytes_compared_ only gets incremented when a full block is compared, to // avoid having to use only parts of the buffered network data. bytes_compared_ += result; state_ = STATE_DONE; return net::OK; } int ServiceWorkerCacheWriter::DoReadHeadersForCopy(int result) { DCHECK_GE(result, 0); DCHECK(copy_reader_); bytes_copied_ = 0; headers_to_read_ = new HttpResponseInfoIOBuffer; data_to_copy_ = new net::IOBuffer(kCopyBufferSize); state_ = STATE_READ_HEADERS_FOR_COPY_DONE; return ReadInfoHelper(copy_reader_, headers_to_read_.get()); } int ServiceWorkerCacheWriter::DoReadHeadersForCopyDone(int result) { if (result < 0) { state_ = STATE_DONE; return result; } state_ = STATE_WRITE_HEADERS_FOR_COPY; return net::OK; } // Write the just-read headers back to the cache. // Note that this *discards* the read headers and replaces them with the net // headers. int ServiceWorkerCacheWriter::DoWriteHeadersForCopy(int result) { DCHECK_GE(result, 0); DCHECK(writer_); state_ = STATE_WRITE_HEADERS_FOR_COPY_DONE; return WriteInfoHelper(writer_, headers_to_write_.get()); } int ServiceWorkerCacheWriter::DoWriteHeadersForCopyDone(int result) { if (result < 0) { state_ = STATE_DONE; return result; } state_ = STATE_READ_DATA_FOR_COPY; return net::OK; } int ServiceWorkerCacheWriter::DoReadDataForCopy(int result) { DCHECK_GE(result, 0); size_t to_read = std::min(kCopyBufferSize, bytes_compared_ - bytes_copied_); // At this point, all compared bytes have been read. Currently // |data_to_write_| and |len_to_write_| hold the chunk of network input that // caused the comparison failure, so those need to be written back and this // object needs to go into passthrough mode. if (to_read == 0) { state_ = STATE_WRITE_DATA_FOR_PASSTHROUGH; return net::OK; } state_ = STATE_READ_DATA_FOR_COPY_DONE; return ReadDataHelper(copy_reader_, data_to_copy_.get(), to_read); } int ServiceWorkerCacheWriter::DoReadDataForCopyDone(int result) { if (result < 0) { state_ = STATE_DONE; return result; } state_ = STATE_WRITE_DATA_FOR_COPY; return result; } int ServiceWorkerCacheWriter::DoWriteDataForCopy(int result) { state_ = STATE_WRITE_DATA_FOR_COPY_DONE; DCHECK_GT(result, 0); return WriteDataHelper(writer_, data_to_copy_.get(), result); } int ServiceWorkerCacheWriter::DoWriteDataForCopyDone(int result) { if (result < 0) { state_ = STATE_DONE; return result; } bytes_written_ += result; bytes_copied_ += result; state_ = STATE_READ_DATA_FOR_COPY; return result; } int ServiceWorkerCacheWriter::DoWriteHeadersForPassthrough(int result) { DCHECK_GE(result, 0); DCHECK(writer_); state_ = STATE_WRITE_HEADERS_FOR_PASSTHROUGH_DONE; return WriteInfoHelper(writer_, headers_to_write_.get()); } int ServiceWorkerCacheWriter::DoWriteHeadersForPassthroughDone(int result) { state_ = STATE_DONE; return result; } int ServiceWorkerCacheWriter::DoWriteDataForPassthrough(int result) { DCHECK_GE(result, 0); state_ = STATE_WRITE_DATA_FOR_PASSTHROUGH_DONE; if (len_to_write_ > 0) result = WriteDataHelper(writer_, data_to_write_.get(), len_to_write_); return result; } int ServiceWorkerCacheWriter::DoWriteDataForPassthroughDone(int result) { if (result < 0) { state_ = STATE_DONE; return result; } bytes_written_ += result; state_ = STATE_DONE; return net::OK; } int ServiceWorkerCacheWriter::DoDone(int result) { state_ = STATE_DONE; return result; } // These helpers adapt the AppCache "always use the callback" pattern to the // //net "only use the callback for async" pattern using // AsyncCompletionCallbackAdaptor. // // Specifically, these methods return result codes directly for synchronous // completions, and only run their callback (which is AsyncDoLoop) for // asynchronous completions. int ServiceWorkerCacheWriter::ReadInfoHelper( const std::unique_ptr<ServiceWorkerResponseReader>& reader, HttpResponseInfoIOBuffer* buf) { net::CompletionCallback run_callback = base::Bind( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(run_callback)); reader->ReadInfo( buf, base::Bind(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback, adaptor)); adaptor->set_async(true); return adaptor->result(); } int ServiceWorkerCacheWriter::ReadDataHelper( const std::unique_ptr<ServiceWorkerResponseReader>& reader, net::IOBuffer* buf, int buf_len) { net::CompletionCallback run_callback = base::Bind( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(run_callback)); reader->ReadData( buf, buf_len, base::Bind(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback, adaptor)); adaptor->set_async(true); return adaptor->result(); } int ServiceWorkerCacheWriter::WriteInfoHelper( const std::unique_ptr<ServiceWorkerResponseWriter>& writer, HttpResponseInfoIOBuffer* buf) { did_replace_ = true; net::CompletionCallback run_callback = base::Bind( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(run_callback)); writer->WriteInfo( buf, base::Bind(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback, adaptor)); adaptor->set_async(true); return adaptor->result(); } int ServiceWorkerCacheWriter::WriteDataHelper( const std::unique_ptr<ServiceWorkerResponseWriter>& writer, net::IOBuffer* buf, int buf_len) { net::CompletionCallback run_callback = base::Bind( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(run_callback)); writer->WriteData( buf, buf_len, base::Bind(&AsyncOnlyCompletionCallbackAdaptor::WrappedCallback, adaptor)); adaptor->set_async(true); return adaptor->result(); } void ServiceWorkerCacheWriter::AsyncDoLoop(int result) { result = DoLoop(result); // If the result is ERR_IO_PENDING, the pending callback will be run by a // later invocation of AsyncDoLoop. if (result != net::ERR_IO_PENDING) { OnWriteCompleteCallback callback = pending_callback_; pending_callback_.Reset(); net::Error error = result >= 0 ? net::OK : static_cast<net::Error>(result); io_pending_ = false; callback.Run(error); } } } // namespace content
6,199
567
<reponame>maxiko/jolokia<filename>agent/jvm/src/test/java/org/jolokia/jvmagent/Dummy.java package org.jolokia.jvmagent; import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.HttpExchange; import org.jolokia.config.Configuration; /** * Class that facilitates custom authenticator tests */ public class Dummy extends Authenticator { private Configuration config; public Dummy() { throw new UnsupportedOperationException("I expect to get some config parameters, use another constructor"); } public Dummy(Configuration configuration) { this.config = configuration; } @Override public Result authenticate(HttpExchange httpExchange) { throw new UnsupportedOperationException("I am a authenticator called Dummy, what else were you expecting?"); } public Configuration getConfig() { return config; } }
284
394
package net.earthcomputer.multiconnect.protocols.generic; public interface IServerboundSlotPacket { boolean multiconnect_isProcessed(); void multiconnect_setProcessed(); int multiconnect_getSlotId(); }
69
1,663
<gh_stars>1000+ #include <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #include "../../libdill.h" int main(int argc, char *argv[]) { if(argc != 4) { fprintf(stderr, "Usage: wget [protocol] [server] [resource]\n"); return 1; } int port; if(strcmp(argv[1], "http") == 0) port = 80; else if(strcmp(argv[1], "https") == 0) port = 443; else { fprintf(stderr, "Unsupported protocol.\n"); return 1; } struct ipaddr addr; int rc = ipaddr_remote(&addr, argv[2], port, 0, -1); if(rc != 0) { perror("Cannot resolve server address"); return 1; } int s = tcp_connect(&addr, -1); if(s < 0) { perror("Cannot connect to the remote server"); return 1; } if(port == 443) { s = tls_attach_client(s, -1); assert(s >= 0); } s = http_attach(s); assert(s >= 0); rc = http_sendrequest(s, "GET", argv[3], -1); assert(rc == 0); rc = http_sendfield(s, "Host", argv[2], -1); assert(rc == 0); rc = http_sendfield(s, "Connection", "close", -1); assert(rc == 0); rc = http_done(s, -1); assert(rc == 0); char reason[256]; rc = http_recvstatus(s, reason, sizeof(reason), -1); assert(rc >= 0); fprintf(stderr, "%d: %s\n", rc, reason); while(1) { char name[256]; char value[256]; rc = http_recvfield(s, name, sizeof(name), value, sizeof(value), -1); if(rc == -1 && errno == EPIPE) break; assert(rc == 0); fprintf(stderr, "%s: %s\n", name, value); } fprintf(stderr, "\n"); s = http_detach(s, -1); assert(s >= 0); if(port == 443) { s = tls_detach(s, -1); assert(s >= 0); } rc = tcp_close(s, -1); assert(rc == 0); return 0; }
905
2,577
<reponame>makkes/dcos<gh_stars>1000+ # Copyright (C) Mesosphere, Inc. See LICENSE file for details.
37
679
<gh_stars>100-1000 /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "connectivity/sdbcx/VIndexColumn.hxx" #include "TConnection.hxx" using namespace connectivity; using namespace connectivity::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::uno; // ----------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OIndexColumn::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) { if(isNew()) return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndexColumnDescriptor"); return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.VIndexColumn"); } // ----------------------------------------------------------------------------- ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL OIndexColumn::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1); if(isNew()) aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.IndexColumnDescriptor"); else aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.IndexColumn"); return aSupported; } // ----------------------------------------------------------------------------- sal_Bool SAL_CALL OIndexColumn::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) { Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames()); const ::rtl::OUString* pSupported = aSupported.getConstArray(); const ::rtl::OUString* pEnd = pSupported + aSupported.getLength(); for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported) ; return pSupported != pEnd; } // ----------------------------------------------------------------------------- OIndexColumn::OIndexColumn(sal_Bool _bCase) : OColumn(_bCase), m_IsAscending(sal_True) { construct(); } // ------------------------------------------------------------------------- OIndexColumn::OIndexColumn( sal_Bool _IsAscending, const ::rtl::OUString& _Name, const ::rtl::OUString& _TypeName, const ::rtl::OUString& _DefaultValue, sal_Int32 _IsNullable, sal_Int32 _Precision, sal_Int32 _Scale, sal_Int32 _Type, sal_Bool _IsAutoIncrement, sal_Bool _IsRowVersion, sal_Bool _IsCurrency, sal_Bool _bCase ) : OColumn(_Name, _TypeName, _DefaultValue, ::rtl::OUString(), _IsNullable, _Precision, _Scale, _Type, _IsAutoIncrement, _IsRowVersion, _IsCurrency, _bCase) , m_IsAscending(_IsAscending) { construct(); } // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* OIndexColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const { return doCreateArrayHelper(); } // ----------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& SAL_CALL OIndexColumn::getInfoHelper() { return *OIndexColumn_PROP::getArrayHelper(isNew() ? 1 : 0); } // ------------------------------------------------------------------------- void OIndexColumn::construct() { sal_Int32 nAttrib = isNew() ? 0 : PropertyAttribute::READONLY; registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING), PROPERTY_ID_ISASCENDING, nAttrib,&m_IsAscending, ::getBooleanCppuType()); } // -----------------------------------------------------------------------------
1,477
1,109
/** * Copyright 2016 Intuit * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.intuit.wasabi.authentication.impl; import com.google.inject.Guice; import com.google.inject.Injector; import com.intuit.wasabi.authentication.Authentication; import com.intuit.wasabi.authentication.AuthenticationModule; import com.intuit.wasabi.authentication.TestUtil; import com.intuit.wasabi.authenticationobjects.LoginToken; import com.intuit.wasabi.authenticationobjects.UserInfo; import com.intuit.wasabi.exceptions.AuthenticationException; import com.intuit.wasabi.userdirectory.UserDirectoryModule; import org.apache.commons.codec.binary.Base64; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; /** * Unit test for Default Authenication Test */ public class DefaultAuthenticationTest { public static final String WASABI_ADMIN_WASABI_ADMIN = "admin:admin"; public static final String WASABI_ADMIN_ADMIN_WASABI = "wasabi_admin:admin_wasabi"; public static final String WASABI_READER_WASABI01 = "wasabi_reader:wasabi01"; public static final String WASABI_ADMIN = "admin"; public static final String ADMIN_EXAMPLE_COM = "<EMAIL>"; private Authentication defaultAuthentication = null; @Before public void setUp() throws Exception { System.getProperties().put("user.lookup.class.name", "com.intuit.wasabi.userdirectory.impl.DefaultUserDirectory"); System.getProperties().put("authentication.class.name", "com.intuit.wasabi.authentication.impl.DefaultAuthentication"); System.getProperties().put("http.proxy.port", "8080"); Injector injector = Guice.createInjector(new UserDirectoryModule(), new AuthenticationModule()); defaultAuthentication = injector.getInstance(Authentication.class); assertNotNull(defaultAuthentication); } @Test(expected = AuthenticationException.class) public void testLogIn() { defaultAuthentication.logIn(null); } @Test(expected = AuthenticationException.class) public void testVerifyToken() throws Exception { LoginToken token = defaultAuthentication.verifyToken("Basic <KEY>"); LoginToken expected = LoginToken.withAccessToken("<KEY>").withTokenType("Basic").build(); assertThat(token, is(expected)); //finally cause an exception if token is null defaultAuthentication.verifyToken(null); } @Test(expected = AuthenticationException.class) public void testVerifyBadToken() throws Exception { LoginToken token = defaultAuthentication.verifyToken("Basic THISISABADTOKEN"); LoginToken expected = LoginToken.withAccessToken("<PASSWORD>").withTokenType("Basic").build(); assertThat(token, is(expected)); } @Test(expected = AuthenticationException.class) public void testVerifyBadTokenWithTamperedPassword() throws Exception { LoginToken token = defaultAuthentication.verifyToken("Basic <KEY>"); LoginToken expected = LoginToken.withAccessToken("<KEY>").withTokenType("Basic").build(); assertThat(token, is(expected)); } @Test public void testLogOut() throws Exception { boolean result = defaultAuthentication.logOut(null); assertThat(result, is(true)); result = defaultAuthentication.logOut("ANYTHING"); assertThat(result, is(true)); } @Test(expected = AuthenticationException.class) public void testGetNullUserExists() throws Exception { defaultAuthentication.getUserExists(null); } @Test public void testGetUserExists() { UserInfo user = defaultAuthentication.getUserExists(ADMIN_EXAMPLE_COM); UserInfo expected = UserInfo.from(UserInfo.Username.valueOf(WASABI_ADMIN)) .withEmail(ADMIN_EXAMPLE_COM) .withLastName("Admin") .withUserId(WASABI_ADMIN) .withFirstName("Wasabi").build(); assertEquals(user, expected); } @Test(expected = AuthenticationException.class) public void testBadPasswordLogIn() { LoginToken token = defaultAuthentication.logIn(DefaultAuthentication.BASIC + " " + new String(Base64.encodeBase64(WASABI_ADMIN_ADMIN_WASABI.getBytes(TestUtil.CHARSET)))); assertThat(token, is(LoginToken.withAccessToken( new String(Base64.encodeBase64(WASABI_ADMIN_ADMIN_WASABI.getBytes(TestUtil.CHARSET)))) .withTokenType(DefaultAuthentication.BASIC).build() ) ); } @Test public void testGoodPasswordLogIn() { LoginToken token = defaultAuthentication.logIn(DefaultAuthentication.BASIC + " " + new String(Base64.encodeBase64(WASABI_ADMIN_WASABI_ADMIN.getBytes(TestUtil.CHARSET)))); assertThat(token, is(LoginToken.withAccessToken( new String(Base64.encodeBase64(WASABI_ADMIN_WASABI_ADMIN.getBytes(TestUtil.CHARSET)))) .withTokenType(DefaultAuthentication.BASIC).build() ) ); // Test user with special charactors in the key token = defaultAuthentication.logIn(DefaultAuthentication.BASIC + " " + new String(Base64.encodeBase64(WASABI_READER_WASABI01.getBytes(TestUtil.CHARSET)))); assertThat(token, is(LoginToken.withAccessToken( new String(Base64.encodeBase64(WASABI_READER_WASABI01.getBytes(TestUtil.CHARSET)))) .withTokenType(DefaultAuthentication.BASIC).build() ) ); } }
2,415
511
/**************************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. * ****************************************************************************/ /// @file kernel_tc_main.c /// @brief Main Function for Kernel TestCase Example #include <tinyara/config.h> #include <stdio.h> #include <errno.h> #include <fcntl.h> #include <tinyara/os_api_test_drv.h> #include <tinyara/fs/fs.h> #include <tinyara/fs/ioctl.h> #include "tc_common.h" #include "tc_internal.h" static int g_tc_fd; int tc_get_drvfd(void) { return g_tc_fd; } #ifdef CONFIG_BUILD_KERNEL int main(int argc, FAR char *argv[]) #else int tc_kernel_main(int argc, char *argv[]) #endif { if (testcase_state_handler(TC_START, "Kernel TC") == ERROR) { return ERROR; } g_tc_fd = open(OS_API_TEST_DRVPATH, O_WRONLY); if (g_tc_fd < 0) { tckndbg("Failed to open OS API test driver %d\n", errno); return ERROR; } #ifdef CONFIG_TC_KERNEL_TASH_HEAPINFO tash_heapinfo_main(); #endif #ifdef CONFIG_TC_KERNEL_TASH_STACKMONITOR tash_stackmonitor_main(); #endif #ifdef CONFIG_TC_KERNEL_CLOCK clock_main(); #endif #ifdef CONFIG_TC_KERNEL_ENVIRON environ_main(); #endif #ifdef CONFIG_TC_KERNEL_ERRNO errno_main(); #endif #ifdef CONFIG_TC_KERNEL_GROUP #if !defined(CONFIG_SCHED_HAVE_PARENT) || !defined(CONFIG_SCHED_CHILD_STATUS) #error CONFIG_SCHED_HAVE_PARENT and CONFIG_SCHED_CHILD_STATUS are needed for testing GROUP TC #endif group_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_FIXEDMATH libc_fixedmath_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_INTTYPES libc_inttypes_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_LIBGEN libc_libgen_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_MATH libc_math_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_MISC libc_misc_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_PTHREAD libc_pthread_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_QUEUE libc_queue_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_SCHED libc_sched_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_SEMAPHORE libc_semaphore_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_SIGNAL libc_signal_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_STDIO libc_stdio_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_STDLIB #if !defined(CONFIG_FS_WRITABLE) #error CONFIG_FS_WRITABLE is needed for testing LIBC_STDLIB TC #endif libc_stdlib_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_STRING libc_string_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_SYSLOG libc_syslog_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_TIMER libc_timer_main(); #endif #ifdef CONFIG_TC_KERNEL_LIBC_UNISTD libc_unistd_main(); #endif #ifdef CONFIG_TC_KERNEL_MQUEUE mqueue_main(); #endif #ifdef CONFIG_TC_KERNEL_PTHREAD pthread_main(); #endif #ifdef CONFIG_TC_KERNEL_SCHED sched_main(); #endif #ifdef CONFIG_TC_KERNEL_SEMAPHORE semaphore_main(); #endif #ifdef CONFIG_TC_KERNEL_SIGNAL signal_main(); #endif #ifdef CONFIG_TC_KERNEL_SYSTEM_DEBUG debug_main(); #endif #ifdef CONFIG_TC_KERNEL_TASK task_main(); #endif #ifdef CONFIG_TC_KERNEL_TERMIOS termios_main(); #endif #ifdef CONFIG_TC_KERNEL_TIMER timer_tc_main(); #endif #ifdef CONFIG_TC_KERNEL_UMM_HEAP umm_heap_main(); #endif #ifdef CONFIG_TC_KERNEL_WORK_QUEUE wqueue_main(); #endif #ifdef CONFIG_TC_KERNEL_MEMORY_SAFETY memory_safety_main(); #endif #ifdef CONFIG_TC_KERNEL_IRQ irq_main(); #endif #ifdef CONFIG_ITC_KERNEL_ENVIRON itc_environ_main(); #endif #ifdef CONFIG_ITC_KERNEL_LIBC_PTHREAD itc_libc_pthread_main(); #endif #ifdef CONFIG_ITC_KERNEL_LIBC_SEMAPHORE itc_libc_semaphore_main(); #endif #ifdef CONFIG_ITC_KERNEL_SEMAPHORE itc_semaphore_main(); #endif #ifdef CONFIG_ITC_KERNEL_SCHED itc_sched_main(); #endif #ifdef CONFIG_ITC_KERNEL_TIMER itc_timer_main(); #endif #ifdef CONFIG_ITC_KERNEL_PTHREAD itc_pthread_main(); #endif close(g_tc_fd); g_tc_fd = -1; (void)testcase_state_handler(TC_END, "Kernel TC"); return 0; }
1,896
348
<gh_stars>100-1000 {"nom":"Busque","circ":"2ème circonscription","dpt":"Tarn","inscrits":602,"abs":273,"votants":329,"blancs":18,"nuls":9,"exp":302,"res":[{"nuance":"REM","nom":"<NAME>","voix":170},{"nuance":"FN","nom":"<NAME>","voix":132}]}
96
911
<reponame>BugLai/ApkToolPlus /* This library 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. */ package ee.ioc.cs.jbe.browser.detail.constants; import ee.ioc.cs.jbe.browser.config.window.*; import org.gjt.jclasslib.structures.CPInfo; import org.gjt.jclasslib.structures.InvalidByteCodeException; import org.gjt.jclasslib.structures.constants.*; import ee.ioc.cs.jbe.browser.BrowserTreeNode; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** Component that opens named references to methods and fields. @author <a href="mailto:<EMAIL>"><NAME></a> @version $Revision: 1.5 $ $Date: 2006/09/25 16:00:58 $ Modified by <NAME> */ public class ClassElementOpener implements ActionListener { private JButton btnShow; private CPInfo cpInfo; private AbstractConstantInfoDetailPane detailPane; /** * Constructor. * @param detailPane the parent detail pane. */ public ClassElementOpener(AbstractConstantInfoDetailPane detailPane) { this.detailPane = detailPane; btnShow = new JButton("Show"); btnShow.addActionListener(this); } public void actionPerformed(ActionEvent event) { try { ConstantClassInfo classInfo = null; BrowserPath browserPath = null; if (cpInfo instanceof ConstantClassInfo) { classInfo = (ConstantClassInfo)cpInfo; } else if (cpInfo instanceof ConstantReference) { ConstantReference reference = (ConstantReference)cpInfo; ConstantNameAndTypeInfo nameAndType = reference.getNameAndTypeInfo(); classInfo = reference.getClassInfo(); String category = null; if (cpInfo instanceof ConstantFieldrefInfo) { category = BrowserTreeNode.NODE_FIELD; } else if (cpInfo instanceof ConstantMethodrefInfo || cpInfo instanceof ConstantInterfaceMethodrefInfo){ category = BrowserTreeNode.NODE_METHOD; } if (category != null) { browserPath = new BrowserPath(); browserPath.addPathComponent(new CategoryHolder(category)); browserPath.addPathComponent(new ReferenceHolder(nameAndType.getName(), nameAndType.getDescriptor())); } } if (classInfo == null) { return; } String className = classInfo.getName().replace('/', '.'); detailPane.getBrowserServices().openClassFile(className, browserPath); } catch (InvalidByteCodeException ex) { ex.printStackTrace(); } } /** * Add an opening button to the supplied detail pane. * @param detailPane the detail pane. * @param gridy the current <tt>gridy</tt> of the <tt>GridBagLayout</tt> of the detail pane. * @return the number of added rows. */ public int addSpecial(AbstractConstantInfoDetailPane detailPane, int gridy) { GridBagConstraints gc = new GridBagConstraints(); gc.weightx = 1; gc.anchor = GridBagConstraints.FIRST_LINE_START; gc.insets = new Insets(5, 10, 0, 10); gc.gridy = gridy+1; gc.gridx =0; gc.gridwidth = 3; detailPane.add(btnShow, gc); return 1; } /** * Set the constant pool info that is to be the source of the link. * @param cpInfo the contant pool info. */ public void setCPInfo(CPInfo cpInfo) { this.cpInfo = cpInfo; String buttonText = null; if (cpInfo instanceof ConstantClassInfo) { buttonText = "Show class"; try { if (((ConstantClassInfo)cpInfo).getName().equals(detailPane.getBrowserServices().getClassFile().getThisClassName())) { buttonText = null; } } catch (InvalidByteCodeException e) { } } else if (cpInfo instanceof ConstantFieldrefInfo) { buttonText = "Show field"; } else if (cpInfo instanceof ConstantMethodrefInfo) { buttonText = "Show method"; } else if (cpInfo instanceof ConstantInterfaceMethodrefInfo) { buttonText = "Show interface method"; } if (buttonText != null) { btnShow.setVisible(true); btnShow.setText(buttonText); } else { btnShow.setVisible(false); } } }
2,033
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.security.attestation.implementation.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.Base64Util; import com.azure.core.util.logging.ClientLogger; import com.azure.security.attestation.models.AttestationSigner; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.util.Base64; import java.io.ByteArrayInputStream; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Represents an attestation signing certificate returned by the attestation service. */ @Fluent public class AttestationSignerImpl implements AttestationSigner { private static final ObjectMapper MAPPER = new ObjectMapper(); /** * Sets the signing certificate. * @param certificates Array of X509Certificate objects. * @return AttestationSigner */ AttestationSignerImpl setCertificates(final X509Certificate[] certificates) { this.certificates = cloneX509CertificateChain(certificates); return this; } /** * Clone an X.509 certificate chain. Used to ensure that the `certificates` property remains immutable. * * @param certificates X.509 certificate chain to clone. * @return Deep cloned X.509 certificate chain. */ private List<X509Certificate> cloneX509CertificateChain(X509Certificate[] certificates) { ClientLogger logger = new ClientLogger(AttestationSignerImpl.class); return Arrays.stream(certificates).map(certificate -> { X509Certificate newCert; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); newCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); } catch (CertificateException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } return newCert; }).collect(Collectors.toList()); } /** * Sets the KeyId. * * The KeyId is matched with the "kid" property in a JsonWebSignature object. It corresponds * to the kid property defined in <a href="https://datatracker.ietf.org/doc/html/rfc7517#section-4.5">JsonWebKey RFC section 4.5</a> * * @param keyId Key ID associated with this signer * @return AttestationSigner */ AttestationSignerImpl setKeyId(String keyId) { this.keyId = keyId; return this; } /** * Gets the Certificates associated with this signer. * * The Certificates is an X.509 certificate chain associated with a particular attestation signer. * * It corresponds to the `x5c` property on a JSON Web Key. See <a href="https://datatracker.ietf.org/doc/html/rfc7517#section-4.7">JsonWebKey RFC Section 4.7</a> * for more details. * * @return Certificate chain used to sign an attestation token. */ @Override public final List<X509Certificate> getCertificates() { return cloneX509CertificateChain(this.certificates.toArray(new X509Certificate[0])); } /** * Gets the KeyId. * * The KeyId is matched with the "kid" property in a JsonWebSignature object. It corresponds * to the kid property defined in <a href="https://datatracker.ietf.org/doc/html/rfc7517#section-4.5">JsonWebKey RFC section 4.5</a> * * @return KeyId. */ @Override public String getKeyId() { return keyId; } /** * Validate that the attestation signer is valid. */ @Override public void validate() { Objects.requireNonNull(certificates); for (X509Certificate certificate : certificates) { Objects.requireNonNull(certificate); } } /** * Create this signer from a base64 encoded certificate chain. * @param certificateChain Certificate chain holding the certificates to return. * @return An attestation signer associated with the specified certificate chain. */ public static AttestationSigner fromCertificateChain(List<Base64> certificateChain) { X509Certificate[] certChain = certificateChain .stream() .map(AttestationSignerImpl::certificateFromBase64) .toArray(X509Certificate[]::new); return new AttestationSignerImpl() .setCertificates(certChain); } /** * Create this signer from a Json Web Key. * @param jwk JSON Web Key for the signature. * @return {@link AttestationSigner} generated from the JWK. * @throws Error - when the attestation signer could not be created from the JWK. */ public static AttestationSigner fromJWK(JWK jwk) throws Error { ClientLogger logger = new ClientLogger(AttestationSignerImpl.class); String serializedKey = jwk.toJSONString(); JsonWebKey jsonWebKey; try { jsonWebKey = MAPPER.readValue(serializedKey, JsonWebKey.class); } catch (JsonProcessingException e) { throw logger.logExceptionAsError(new RuntimeException(e.getMessage())); } return AttestationSignerImpl.fromJsonWebKey(jsonWebKey); } public static AttestationSigner fromJsonWebKey(JsonWebKey jsonWebKey) { List<String> certificateChain = jsonWebKey.getX5C(); if (certificateChain != null) { X509Certificate[] certificateArray = certificateChain .stream() .map(AttestationSignerImpl::certificateFromBase64String) .toArray(X509Certificate[]::new); return new AttestationSignerImpl() .setCertificates(certificateArray) .setKeyId(jsonWebKey.getKid()); } throw new Error("Could not resolve AttestationSigner from JWK."); } /** * Private method to create an AttestationSigner from a JWKS. * @param jwks JWKS to create. * @return Array of {@link AttestationSigner}s created from the JWK. */ public static List<AttestationSigner> attestationSignersFromJwks(JsonWebKeySet jwks) { return jwks .getKeys() .stream() .map(AttestationSignerImpl::fromJsonWebKey) .collect(Collectors.toList()); } /** * Create an X.509 certificate from a Base64 encoded certificate. * @param base64certificate Base64 encoded certificate. * @return X.509 certificate. */ static X509Certificate certificateFromBase64(Base64 base64certificate) { return certificateFromBase64String(base64certificate.toString()); } static X509Certificate certificateFromBase64String(String base64certificate) { ClientLogger logger = new ClientLogger(AttestationSignerImpl.class); byte[] decodedCertificate = Base64Util.decodeString(base64certificate); CertificateFactory cf; try { cf = CertificateFactory.getInstance("X.509"); } catch (CertificateException e) { throw logger.logExceptionAsError(new RuntimeException(e.getMessage())); } Certificate cert; try { cert = cf.generateCertificate(new ByteArrayInputStream(decodedCertificate)); } catch (CertificateException e) { throw logger.logExceptionAsError(new RuntimeException(e.getMessage())); } return (X509Certificate) cert; } private List<X509Certificate> certificates; private String keyId; }
2,970
1,109
import logging def log_request_perf(handler): if handler.get_status() < 400: log_method = logging.info elif handler.get_status() < 500: log_method = logging.warning else: log_method = logging.error request_time = 1000.0 * handler.request.request_time() request_speed_message='' if request_time <= 100: request_speed_message = 'FAST' elif request_time <= 200: request_speed_message = 'SPEED OK' elif request_time <= 400: request_speed_message= 'PRETTY SLOW' elif request_time <= 600: request_speed_message= 'SLOW' elif request_time <= 800: request_speed_message= 'VERY SLOW' elif request_time > 800: request_speed_message= 'CRITICALLY SLOW' log_method("%d %s %.2fms - %s", handler.get_status(), handler._request_summary(), request_time, request_speed_message)
389
763
<reponame>zabrewer/batfish<gh_stars>100-1000 package org.batfish.datamodel.matchers; import java.util.List; import org.batfish.datamodel.AclIpSpace; import org.batfish.datamodel.AclIpSpaceLine; import org.batfish.datamodel.IpSpace; import org.hamcrest.FeatureMatcher; import org.hamcrest.Matcher; public class AclIpSpaceMatchersImpl { static class HasLines extends FeatureMatcher<AclIpSpace, List<AclIpSpaceLine>> { public HasLines(Matcher<? super List<AclIpSpaceLine>> subMatcher) { super(subMatcher, "an AclIpSpace with lines:", "lines"); } @Override protected List<AclIpSpaceLine> featureValueOf(AclIpSpace actual) { return actual.getLines(); } } static class IsAclIpSpaceThat extends IsInstanceThat<IpSpace, AclIpSpace> { IsAclIpSpaceThat(Matcher<? super AclIpSpace> subMatcher) { super(AclIpSpace.class, subMatcher); } } private AclIpSpaceMatchersImpl() {} }
370
7,936
package io.quicktype; public class TopLevel { }
16
1,338
<reponame>Kirishikesan/haiku<gh_stars>1000+ /* * Copyright 2012-2016, <NAME>, <EMAIL>. * Distributed under the terms of the MIT License. */ #include "CliPrintVariableCommand.h" #include <stdio.h> #include <AutoLocker.h> #include "CliContext.h" #include "StackFrame.h" #include "StackTrace.h" #include "Team.h" #include "Type.h" #include "UiUtils.h" #include "UserInterface.h" #include "ValueLocation.h" #include "ValueNode.h" #include "ValueNodeContainer.h" #include "ValueNodeManager.h" CliPrintVariableCommand::CliPrintVariableCommand() : CliCommand("print value(s) of a variable", "%s [--depth n] variable [variable2 ...]\n" "Prints the value and members of the named variable.") { } void CliPrintVariableCommand::Execute(int argc, const char* const* argv, CliContext& context) { if (argc < 2) { PrintUsage(argv[0]); return; } ValueNodeManager* manager = context.GetValueNodeManager(); ValueNodeContainer* container = manager->GetContainer(); AutoLocker<ValueNodeContainer> containerLocker(container); if (container == NULL || container->CountChildren() == 0) { printf("No variables available.\n"); return; } int32 depth = 1; int32 i = 1; for (; i < argc; i++) { if (strcmp(argv[i], "--depth") == 0) { if (i == argc - 1) { printf("Error: An argument must be supplied for depth.\n"); return; } char* endPointer; depth = strtol(argv[i + 1], &endPointer, 0); if (*endPointer != '\0' || depth < 0) { printf("Error: Invalid parameter \"%s\"\n", argv[i + 1]); return; } i++; } else break; } if (i == argc) { printf("Error: At least one variable name must be supplied.\n"); return; } bool found = false; while (i < argc) { // TODO: support variable expressions in addition to just names. const char* variableName = argv[i++]; for (int32 j = 0; ValueNodeChild* child = container->ChildAt(j); j++) { if (child->Name() == variableName) { found = true; containerLocker.Unlock(); _ResolveValueIfNeeded(child->Node(), context, depth); containerLocker.Lock(); BString data; UiUtils::PrintValueNodeGraph(data, child, 1, depth); printf("%s", data.String()); } } if (!found) printf("No such variable: %s\n", variableName); found = false; } } status_t CliPrintVariableCommand::_ResolveValueIfNeeded(ValueNode* node, CliContext& context, int32 maxDepth) { StackFrame* frame = context.GetStackTrace()->FrameAt( context.CurrentStackFrameIndex()); if (frame == NULL) return B_BAD_DATA; status_t result = B_OK; ValueNodeManager* manager = context.GetValueNodeManager(); ValueNodeContainer* container = manager->GetContainer(); AutoLocker<ValueNodeContainer> containerLocker(container); if (node->LocationAndValueResolutionState() == VALUE_NODE_UNRESOLVED) { context.GetUserInterfaceListener()->ValueNodeValueRequested( context.CurrentThread()->GetCpuState(), container, node); while (node->LocationAndValueResolutionState() == VALUE_NODE_UNRESOLVED) { containerLocker.Unlock(); context.WaitForEvents(CliContext::EVENT_VALUE_NODE_CHANGED); containerLocker.Lock(); if (context.IsTerminating()) return B_ERROR; } } if (node->LocationAndValueResolutionState() == B_OK && maxDepth > 0) { for (int32 i = 0; i < node->CountChildren(); i++) { ValueNodeChild* child = node->ChildAt(i); containerLocker.Unlock(); result = manager->AddChildNodes(child); if (result != B_OK) continue; // since in the case of a pointer to a compound we hide // the intervening compound, don't consider the hidden node // a level for the purposes of depth traversal if (node->GetType()->Kind() == TYPE_ADDRESS && child->GetType()->Kind() == TYPE_COMPOUND) { _ResolveValueIfNeeded(child->Node(), context, maxDepth); } else _ResolveValueIfNeeded(child->Node(), context, maxDepth - 1); containerLocker.Lock(); } } return result; }
1,472
5,169
<gh_stars>1000+ { "name": "NABottomsheet", "version": "1.5.0", "summary": "Component which presents a dismissible view from the bottom of the screen. Inspired by https://github.com/hryk224/Bottomsheet", "homepage": "https://github.com/noorulain17/NABottomsheet", "screenshots": "https://github.com/noorulain17/NABottomsheet/wiki/images/sample3.gif", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "hyyk224": "<EMAIL>", "noorulain17": "<EMAIL>" }, "platforms": { "ios": "13.0" }, "source": { "git": "https://github.com/noorulain17/NABottomsheet.git", "tag": "1.5.0" }, "source_files": "Sources/*.{h,swift}", "frameworks": "UIKit", "requires_arc": true, "swift_versions": "5.0", "swift_version": "5.0" }
333
356
/* Print all data in given range in Binary Search Tree */ #include<bits/stdc++.h> using namespace std; typedef struct Node { int data; struct Node *left,*right; }Node; Node* newNode(int data) { Node* node=new Node; node->data=data; node->left=node->right=nullptr; return node; } Node* insert(Node* root,int key) { if(root==nullptr) return newNode(key); else if(key < root->data) root->left = insert(root->left,key); else if(key > root->data) root->right = insert(root->right,key); else return root; } void rangeBST(Node* root,int key1,int key2) { if(root) { rangeBST(root->left,key1,key2); //if the given data lies in the range, print the data if(root->data>=key1 && root->data<=key2){ cout<<root->data<<" "; } rangeBST(root->right,key1,key2); } } int main() { int n,val,key1,key2,minimum=INT_MAX,maximum=INT_MIN; cout<<"Enter the number of elements to be inserted"<<endl; cin>>n; Node* root = nullptr; for(int i=0;i<n;i++) { cin>>val; //insert the values into BST root = insert(root,val); minimum=min(minimum,val); maximum=max(maximum,val); } cout<<"Enter the minimum and maximum range"<<endl; cin>>key1>>key2; if(minimum>key2 || maximum<key1) //If both the given keys are less than the minimum or maximum value of a tree then there will be no elements in that range cout<<"No elements in the given range"; else // inorder function to traverse the entire BST rangeBST(root,key1,key2); return 0; } /* Space Complexity : O(height) as recursion call Time Complexity : O(n) n elements are inserted TESTCASE 1: Enter the number of elements to be inserted 6 1 3 2 6 5 4 Enter the minimum and maximum range 1 4 OUTPUT: 1 2 3 4 TESTCASE 2: Enter the number of elements to be inserted 3 1 2 1 Enter the minimum and maximum range 1 1 OUTPUT: 1 TESTCASE 3: Enter the number of elements to be inserted 5 1 2 3 4 5 Enter the minimum and maximum range 6 7 OUTPUT: No elements in the given range TESTCASE 4: Enter the number of elements to be inserted 5 6 7 8 9 10 Enter the minimum and maximum range 2 5 OUTPUT: No elements in the given range */
925
545
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2021, <NAME> # # 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. from __future__ import absolute_import, print_function, unicode_literals """ Provides integration with `numpy <https://numpy.org/>`_. .. note:: This module requires numpy to be installed, and will raise a warning if this is not available. """ from warnings import warn try: # noinspection PyPackageRequirements from numpy import array except ImportError: warn("The py2neo.integration.numpy module expects numpy to be " "installed but it does not appear to be available.") raise def cursor_to_ndarray(cursor, dtype=None, order='K'): """ Consume and extract the entire result as a `numpy.ndarray <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html>`_. .. note:: This method requires `numpy` to be installed. :param cursor: :param dtype: :param order: :returns: `ndarray <https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html>`__ object. """ return array(list(map(list, cursor)), dtype=dtype, order=order)
536
344
<gh_stars>100-1000 #!/usr/bin/env python __author__ = 'bmiller' import cPickle import sys import pprint sys.path.insert(0,'/home/bnmnetp/webapps/uwsgi_runestone/web2py') with open(sys.argv[1]) as f: trace_data = cPickle.load(f) print(trace_data['traceback']) pprint.pprint(trace_data['snapshot']['locals']) for i in trace_data['snapshot']['frames']: print("============") pprint.pprint(i)
171
1,104
<reponame>yblucky/mdrill /** * 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.lucene.spatial.geometry.shape; /** * Common set of operations available on 2d shapes. * * <p><font color="red"><b>NOTE:</b> This API is still in * flux and might change in incompatible ways in the next * release.</font> */ public interface Geometry2D { /** * Translate according to the vector * @param v */ public void translate(Vector2D v); /** * Does the shape contain the given point * @param p */ public boolean contains(Point2D p); /** * Return the area */ public double area(); /** * Return the centroid */ public Point2D centroid(); /** * Returns information about how this shape intersects the given rectangle * @param r */ public IntersectCase intersect(Rectangle r); }
462
591
{ "name": "glsl-parser", "version": "0.0.5", "description": "transform streamed glsl tokens into an ast", "main": "index.js", "dependencies": { "glsl-tokenizer": "~0.0.2", "through": "~1.1.2" }, "devDependencies": {}, "scripts": { "test": "node test/index.js" }, "repository": { "type": "git", "url": "git://github.com/chrisdickinson/glsl-parser.git" }, "keywords": [ "glsl", "parser", "ast", "through", "stream" ], "author": { "name": "<NAME>", "email": "<EMAIL>" }, "license": "MIT", "readme": "glsl-parser\n===========\n\na through stream that takes tokens from [glsl-tokenizer](https://github.com/chrisdickinson/glsl-tokenizer) and turns them into\nan AST.\n\n```javascript\n\nvar tokenizer = require('glsl-tokenizer')()\n , fs = require('fs')\n , parser = require('./index')\n\nvar num = 0\n\nfs.createReadStream('test.glsl')\n .pipe(tokenizer)\n .pipe(parser())\n .on('data', function(x) {\n console.log('ast of', x.type)\n })\n\n```\n\nsimilar to [JSONStream](https://github.com/dominictarr/JSONStream), you may pass selectors\ninto the constructor to match only AST elements at that level. viable selectors are strings\nand regexen, and they'll be matched against the emitted node's `type`.\n\nnodes\n-----\n\n```\n\nstmtlist\nstmt\nstruct\nfunction\nfunctionargs\ndecl\ndecllist\nforloop\nwhileloop\nif\nexpr\nprecision\ncomment\npreprocessor\nkeyword\nident\nreturn\ncontinue\nbreak\ndiscard\ndo-while\nbinary\nternary\nunary\n\n```\n\nlegal & caveats\n===============\n\nknown bugs\n----------\n\n* because i am not smart enough to write a fully streaming parser, the current parser \"cheats\" a bit when it encounters a `expr` node! it actually waits until it has all the tokens it needs to build a tree for a given expression, then builds it and emits the constituent child nodes in the expected order. the `expr` parsing is heavily influenced by [crockford's tdop article](http://javascript.crockford.com/tdop/tdop.html). the rest of the parser is heavily influenced by fever dreams.\n\n* the parser might hit a state where it's looking at what *could be* an expression, or it could be a declaration --\nthat is, the statement starts with a previously declared `struct`. it'll opt to pretend it's a declaration, but that\nmight not be the case -- it might be a user-defined constructor starting a statement!\n\n* \"unhygenic\" `#if` / `#endif` macros are completely unhandled at the moment, since they're a bit of a pain.\nif you've got unhygenic macros in your code, move the #if / #endifs to statement level, and have them surround\nwholly parseable code. this sucks, and i am sorry.\n\nlicense\n-------\n\nMIT\n", "readmeFilename": "README.md", "bugs": { "url": "https://github.com/chrisdickinson/glsl-parser/issues" }, "homepage": "https://github.com/chrisdickinson/glsl-parser", "_id": "[email protected]", "_from": "glsl-parser@" }
1,038
322
<filename>eagle-core/eagle-app/eagle-app-base/src/main/java/org/apache/eagle/app/messaging/MetricSchemaGenerator.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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.eagle.app.messaging; import backtype.storm.task.OutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichBolt; import backtype.storm.tuple.Tuple; import com.typesafe.config.Config; import org.apache.eagle.log.entity.GenericServiceAPIResponseEntity; import org.apache.eagle.metadata.model.MetricSchemaEntity; import org.apache.eagle.app.environment.builder.MetricDescriptor; import org.apache.eagle.service.client.EagleServiceClientException; import org.apache.eagle.service.client.IEagleServiceClient; import org.apache.eagle.service.client.impl.EagleServiceClientImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; public class MetricSchemaGenerator extends BaseRichBolt { private static final Logger LOG = LoggerFactory.getLogger(MetricSchemaGenerator.class); private static int MAX_CACHE_LENGTH = 1000; public static final String GENERIC_METRIC_VALUE_NAME = "value"; private final HashSet<String> metricNameCache = new HashSet<>(MAX_CACHE_LENGTH); private final MetricDescriptor metricDescriptor; private final Config config; private OutputCollector collector; private IEagleServiceClient client; public MetricSchemaGenerator(MetricDescriptor metricDescriptor, Config config) { this.metricDescriptor = metricDescriptor; this.config = config; } @Override public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) { this.collector = collector; this.client = new EagleServiceClientImpl(config); } @Override public void execute(Tuple input) { try { String metricName = input.getStringByField(MetricStreamPersist.METRIC_NAME_FIELD); synchronized (metricNameCache) { if (!metricNameCache.contains(metricName)) { createMetricSchemaEntity(metricName, (Map) input.getValueByField(MetricStreamPersist.METRIC_EVENT_FIELD),this.metricDescriptor); metricNameCache.add(metricName); } if (metricNameCache.size() > MAX_CACHE_LENGTH) { this.metricNameCache.clear(); } } this.collector.ack(input); } catch (Throwable throwable) { LOG.warn(throwable.getMessage(), throwable); this.collector.reportError(throwable); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public void cleanup() { if (this.client != null) { try { this.client.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } private void createMetricSchemaEntity(String metricName, Map event, MetricDescriptor metricDescriptor) throws IOException, EagleServiceClientException { MetricSchemaEntity schemaEntity = new MetricSchemaEntity(); Map<String, String> schemaTags = new HashMap<>(); schemaEntity.setTags(schemaTags); schemaTags.put(MetricSchemaEntity.METRIC_SITE_TAG, metricDescriptor.getSiteIdSelector().getSiteId(event)); schemaTags.put(MetricSchemaEntity.METRIC_NAME_TAG, metricName); schemaTags.put(MetricSchemaEntity.METRIC_GROUP_TAG, metricDescriptor.getMetricGroupSelector().getMetricGroup(event)); schemaEntity.setGranularityByField(metricDescriptor.getGranularity()); schemaEntity.setDimensionFields(metricDescriptor.getDimensionFields()); schemaEntity.setMetricFields(Collections.singletonList(GENERIC_METRIC_VALUE_NAME)); schemaEntity.setModifiedTimestamp(System.currentTimeMillis()); GenericServiceAPIResponseEntity<String> response = this.client.create(Collections.singletonList(schemaEntity)); if (response.isSuccess()) { if (LOG.isDebugEnabled()) { LOG.debug("Created {}", schemaEntity); } } else { LOG.error("Failed to create {}", schemaEntity, response.getException()); throw new IOException("Service error: " + response.getException()); } } }
1,922
819
<reponame>Asteur/vrhelper<gh_stars>100-1000 /* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef VR_SEURAT_TILER_GEOMETRY_SOLVER_H_ #define VR_SEURAT_TILER_GEOMETRY_SOLVER_H_ #include <vector> #include "absl/types/span.h" #include "seurat/tiler/geometry_model.h" #include "seurat/tiler/point_set.h" namespace seurat { namespace tiler { // An interface for specifying methods for fitting GeometryModels used for // partitioning. // // Both ComputeError() and FitModel() should use the same underlying // error-metric. Both convex and non-convex error metrics may be used. class GeometrySolver { public: // Performs any initialization required for fitting GeometryModels against the // specified PointSet. virtual void Init(const PointSet& point_set) = 0; // Initializes a GeometryModel which fits the point with the specified index // into the PointSet. virtual void InitializeModel(int point_index, GeometryModel* model) const = 0; // Fits a GeometryModel to the specified points. The previously-estimated // |model| geometry is provided as a starting point, and will be modified by // this method. // // Returns true upon success, false if no model could be fit (e.g. because // there are too few points to fit a plane). virtual bool FitModel(absl::Span<const int> point_indices, GeometryModel* model) const = 0; // Computes an error-metric measuring the deviation of the specified point // from the |model|. virtual float ComputeError(int point_index, const GeometryModel& model) const = 0; virtual ~GeometrySolver() = default; }; } // namespace tiler } // namespace seurat #endif // VR_SEURAT_TILER_GEOMETRY_SOLVER_H_
719
1,338
<reponame>Kirishikesan/haiku /* * Copyright 2006, Haiku. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #ifndef WONDERBRUSH_VIEW_H #define WONDERBRUSH_VIEW_H #include <View.h> #include "TranslatorSettings.h" class BMenuField; class WonderBrushView : public BView { public: WonderBrushView(const BRect &frame, const char *name, uint32 resize, uint32 flags, TranslatorSettings *settings); // sets up the view ~WonderBrushView(); // releases the WonderBrushTranslator settings virtual void AttachedToWindow(); virtual void MessageReceived(BMessage *message); virtual void GetPreferredSize(float* width, float* height); enum { MSG_COMPRESSION_CHANGED = 'cmch', }; private: TranslatorSettings *fSettings; // the actual settings for the translator, // shared with the translator }; #endif // WONDERBRUSH_VIEW_H
307
314
<gh_stars>100-1000 // // ZJFourChildView.h // ZJUIKit // // Created by dzj on 2017/12/8. // Copyright © 2017年 kapokcloud. All rights reserved. // /** * ZJKitTool * * GitHub地址:https://github.com/Dzhijian/ZJKitTool * * 本库会不断更新工具类,以及添加一些模块案例,请各位大神们多多指教,支持一下。😆 */ #import <UIKit/UIKit.h> @protocol ZJFourChildViewDelegate <NSObject> /** * 选中后的回调 @param isprom 是否限量优惠 @param isVer 是否实名认证 */ -(void)fourViewBtnSelectedWithIsProm:(BOOL)isprom isVer:(BOOL)isVer; @end @interface ZJFourChildView : UIView @property(nonatomic ,weak) id<ZJFourChildViewDelegate> delegate; @end
352
868
/* * 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.activemq.artemis.tests.integration.amqp.largemessages; import java.net.URI; import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.QueueConfiguration; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.server.impl.AddressInfo; import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils; import org.apache.activemq.artemis.tests.util.Wait; import org.apache.activemq.transport.amqp.client.AmqpClient; import org.apache.activemq.transport.amqp.client.AmqpConnection; import org.apache.activemq.transport.amqp.client.AmqpMessage; import org.apache.activemq.transport.amqp.client.AmqpReceiver; import org.apache.activemq.transport.amqp.client.AmqpSender; import org.apache.activemq.transport.amqp.client.AmqpSession; import org.apache.qpid.proton.amqp.messaging.Data; import org.junit.Assert; import org.junit.Test; public class AmqpReplicatedLargeMessageTest extends AmqpReplicatedTestSupport { private String smallFrameLive = new String("tcp://localhost:" + (AMQP_PORT + 10)); private String smallFrameBackup = new String("tcp://localhost:" + (AMQP_PORT + 10)); @Override protected TransportConfiguration getAcceptorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMAcceptor(live); } @Override protected TransportConfiguration getConnectorTransportConfiguration(final boolean live) { return TransportConfigurationUtils.getInVMConnector(live); } @Override public void setUp() throws Exception { super.setUp(); createReplicatedConfigs(); liveConfig.addAcceptorConfiguration("amqp", smallFrameLive + "?protocols=AMQP;useEpoll=false;maxFrameSize=512"); backupConfig.addAcceptorConfiguration("amqp", smallFrameBackup + "?protocols=AMQP;useEpoll=false;maxFrameSize=512"); liveServer.start(); backupServer.start(); liveServer.getServer().addAddressInfo(new AddressInfo(getQueueName(), RoutingType.ANYCAST)); liveServer.getServer().createQueue(new QueueConfiguration(getQueueName()).setRoutingType(RoutingType.ANYCAST)); waitForRemoteBackupSynchronization(backupServer.getServer()); } public SimpleString getQueueName() { return SimpleString.toSimpleString("replicatedTest"); } @Test(timeout = 60_000) public void testSimpleSend() throws Exception { try { ActiveMQServer server = liveServer.getServer(); boolean crashServer = true; int size = 100 * 1024; AmqpClient client = createAmqpClient(new URI(smallFrameLive)); AmqpConnection connection = client.createConnection(); addConnection(connection); connection.setMaxFrameSize(2 * 1024); connection.connect(); AmqpSession session = connection.createSession(); AmqpSender sender = session.createSender(getQueueName().toString()); Queue queueView = server.locateQueue(getQueueName()); assertNotNull(queueView); assertEquals(0, queueView.getMessageCount()); session.begin(); for (int m = 0; m < 100; m++) { AmqpMessage message = new AmqpMessage(); message.setDurable(true); message.setApplicationProperty("i", "m " + m); byte[] bytes = new byte[size]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) 'z'; } message.setBytes(bytes); sender.send(message); } session.commit(); AMQPLargeMessagesTestUtil.validateAllTemporaryBuffers(server); if (crashServer) { connection.close(); liveServer.crash(); Wait.assertTrue(backupServer::isActive); server = backupServer.getServer(); client = createAmqpClient(new URI(smallFrameBackup)); connection = client.createConnection(); addConnection(connection); connection.setMaxFrameSize(2 * 1024); connection.connect(); session = connection.createSession(); } queueView = server.locateQueue(getQueueName()); Wait.assertEquals(100, queueView::getMessageCount); AmqpReceiver receiver = session.createReceiver(getQueueName().toString()); receiver.flow(100); for (int i = 0; i < 100; i++) { AmqpMessage msgReceived = receiver.receive(10, TimeUnit.SECONDS); Assert.assertNotNull(msgReceived); Data body = (Data)msgReceived.getWrappedMessage().getBody(); byte[] bodyArray = body.getValue().getArray(); for (int bI = 0; bI < size; bI++) { Assert.assertEquals((byte)'z', bodyArray[bI]); } msgReceived.accept(true); } receiver.flow(1); Assert.assertNull(receiver.receiveNoWait()); receiver.close(); connection.close(); Wait.assertEquals(0, queueView::getMessageCount); validateNoFilesOnLargeDir(getLargeMessagesDir(0, true), 0); } catch (Exception e) { e.printStackTrace(); throw e; } } }
2,359
1,305
<gh_stars>1000+ import numpy class BinaryIOCollection(object): def load_binary_file(self, file_name, dimension): fid_lab = open(file_name, 'rb') features = numpy.fromfile(fid_lab, dtype=numpy.float32) fid_lab.close() assert features.size % float(dimension) == 0.0,'specified dimension not compatible with data' features = features[:(dimension * (features.size // dimension))] features = features.reshape((-1, dimension)) return features def array_to_binary_file(self, data, output_file_name): data = numpy.array(data, 'float32') fid = open(output_file_name, 'wb') data.tofile(fid) fid.close() def load_binary_file_frame(self, file_name, dimension): fid_lab = open(file_name, 'rb') features = numpy.fromfile(fid_lab, dtype=numpy.float32) fid_lab.close() assert features.size % float(dimension) == 0.0,'specified dimension not compatible with data' frame_number = features.size // dimension features = features[:(dimension * frame_number)] features = features.reshape((-1, dimension)) return features, frame_number
472
1,909
package info.bitrich.xchangestream.serum.dto; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.knowm.xchange.serum.SerumConfigs.Commitment; import com.knowm.xchange.serum.SerumConfigs.SubscriptionType; public class SerumWsSubscriptionMessage { public final String JSON_RPC = "jsonrpc"; public final String ID = "id"; public final String METHOD = "method"; public final String PARAMS = "params"; public final String ENCODING = "encoding"; public final String COMMITMENT = "commitment"; public final JsonNode msg; public SerumWsSubscriptionMessage( final Commitment commitment, final SubscriptionType subscriptionType, final String publicKey, int reqID) { final ObjectNode param1 = JsonNodeFactory.instance.objectNode(); param1.put(ENCODING, "base64"); param1.put(COMMITMENT, commitment.name()); final ArrayNode params = JsonNodeFactory.instance.arrayNode(); params.add(publicKey); params.add(param1); final ObjectNode msg = JsonNodeFactory.instance.objectNode(); msg.put(JSON_RPC, "2.0"); msg.put(ID, reqID); msg.put(METHOD, subscriptionType.name()); msg.set(PARAMS, params); this.msg = msg; } public String buildMsg() { return msg.toString(); } }
504
7,629
<reponame>rbehjati/oss-fuzz<filename>projects/example/my-api-repo/do_stuff_fuzzer.cpp // Copyright 2017 Google Inc. All Rights Reserved. // Licensed under the Apache License, Version 2.0 (the "License"); #include "my_api.h" #include <string> // Simple fuzz target for DoStuff(). // See http://libfuzzer.info for details. extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { std::string str(reinterpret_cast<const char *>(data), size); DoStuff(str); // Disregard the output. return 0; }
181
5,169
<filename>Specs/AIMNotificationObserver/0.1/AIMNotificationObserver.podspec.json { "name": "AIMNotificationObserver", "version": "0.1", "summary": "Notifications observer used by AIM team", "homepage": "https://github.com/AllinMobile/AIMObservers", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "https://github.com/MaciejGad" }, "social_media_url": "https://twitter.com/maciej_gad", "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/AllinMobile/AIMObservers.git", "tag": "v0.1" }, "source_files": "AIMNotificationObserver.{h,m}", "requires_arc": true }
277
1,031
<filename>cacreader/swig-4.0.2/Examples/test-suite/java/smart_pointer_ignore_runme.java import smart_pointer_ignore.*; public class smart_pointer_ignore_runme { static { try { System.loadLibrary("smart_pointer_ignore"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load. See the chapter on Dynamic Linking Problems in the SWIG Java documentation for help.\n" + e); System.exit(1); } } public static void main(String argv[]) { DerivedPtr d = smart_pointer_ignore.makeDerived(); d.baseMethod(); d.derivedMethod(); } }
218
348
<filename>docs/data/leg-t1/076/07604457.json {"nom":"Moulineaux","circ":"4ème circonscription","dpt":"Seine-Maritime","inscrits":683,"abs":347,"votants":336,"blancs":5,"nuls":2,"exp":329,"res":[{"nuance":"FN","nom":"<NAME>","voix":82},{"nuance":"REM","nom":"Mme <NAME>","voix":71},{"nuance":"SOC","nom":"<NAME>","voix":70},{"nuance":"COM","nom":"M. <NAME>","voix":44},{"nuance":"FI","nom":"Mme <NAME>","voix":33},{"nuance":"LR","nom":"Mme <NAME>","voix":14},{"nuance":"ECO","nom":"Mme <NAME>","voix":6},{"nuance":"ECO","nom":"M. <NAME>","voix":4},{"nuance":"DIV","nom":"M. <NAME>","voix":4},{"nuance":"EXG","nom":"M. <NAME>","voix":1},{"nuance":"DLF","nom":"Mme <NAME>","voix":0},{"nuance":"EXD","nom":"M. <NAME>","voix":0},{"nuance":"ECO","nom":"M. <NAME>","voix":0}]}
318
1,066
<gh_stars>1000+ // This file is compiled to check whether Direct2D and DirectWrite headers are available. #include <d2d1.h> #include <dwrite.h>
47
364
// File doc/quickbook/oglplus/quickref/enums/buffer_indexed_target.hpp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/buffer_indexed_target.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2019 <NAME>. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // //[oglplus_enums_buffer_indexed_target enum class BufferIndexedTarget : GLenum { AtomicCounter = GL_ATOMIC_COUNTER_BUFFER, ShaderStorage = GL_SHADER_STORAGE_BUFFER, TransformFeedback = GL_TRANSFORM_FEEDBACK_BUFFER, Uniform = GL_UNIFORM_BUFFER }; template <> __Range<BufferIndexedTarget> __EnumValueRange<BufferIndexedTarget>(); __StrCRef __EnumValueName(BufferIndexedTarget); //]
306
61,676
<reponame>Lord-Elrond/django import math from decimal import Decimal from django.db.models.functions import Log from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class LogTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_log_small=Log('small', 'normal'), null_log_normal=Log('normal', 'big'), null_log_big=Log('big', 'normal'), ).first() self.assertIsNone(obj.null_log_small) self.assertIsNone(obj.null_log_normal) self.assertIsNone(obj.null_log_big) def test_decimal(self): DecimalModel.objects.create(n1=Decimal('12.9'), n2=Decimal('3.6')) obj = DecimalModel.objects.annotate(n_log=Log('n1', 'n2')).first() self.assertIsInstance(obj.n_log, Decimal) self.assertAlmostEqual(obj.n_log, Decimal(math.log(obj.n2, obj.n1))) def test_float(self): FloatModel.objects.create(f1=2.0, f2=4.0) obj = FloatModel.objects.annotate(f_log=Log('f1', 'f2')).first() self.assertIsInstance(obj.f_log, float) self.assertAlmostEqual(obj.f_log, math.log(obj.f2, obj.f1)) def test_integer(self): IntegerModel.objects.create(small=4, normal=8, big=2) obj = IntegerModel.objects.annotate( small_log=Log('small', 'big'), normal_log=Log('normal', 'big'), big_log=Log('big', 'big'), ).first() self.assertIsInstance(obj.small_log, float) self.assertIsInstance(obj.normal_log, float) self.assertIsInstance(obj.big_log, float) self.assertAlmostEqual(obj.small_log, math.log(obj.big, obj.small)) self.assertAlmostEqual(obj.normal_log, math.log(obj.big, obj.normal)) self.assertAlmostEqual(obj.big_log, math.log(obj.big, obj.big))
848
419
/* Even Faster Duursma-Lee char 2 Tate pairing based on eta_T pairing */ /* cl /O2 /GX dl2.cpp ec2.cpp gf2m4x.cpp gf2m.cpp big.cpp miracl.lib */ /* Half sized loop so nearly twice as fast! */ /* 14th March 2005 */ #include <iostream> #include <ctime> #include "gf2m.h" #include "gf2m4x.h" #include "ec2.h" // set TYPE = 1 if B=0 && (M=1 or 7 mod 8), else TYPE = 2 // set TYPE = 1 if B=1 && (M=3 or 5 mod 8), else TYPE = 2 // some example curves to play with //#define M 283 //#define T 249 //#define U 219 //#define V 27 //#define B 1 //#define TYPE 1 //#define CF 1 //#define M 367 //#define T 21 //#define U 0 //#define V 0 //#define B 1 //#define TYPE 2 //#define CF 1 //#define M 379 //#define T 317 //#define U 315 //#define V 283 //#define B 1 //#define TYPE 1 //#define CF 1 #define M 1223 #define T 255 #define U 0 #define V 0 #define B 0 #define TYPE 1 #define CF 5 //#define M 271 //#define T 207 //#define U 175 //#define V 111 //#define B 0 //#define TYPE 1 //#define CF 487805 //#define M 353 //#define B 1 //#define T 215 //#define U 0 //#define V 0 //#define TYPE 2 //#define CF 1 //#define M 271 //#define U 0 //#define V 0 //#define T 201 //#define B 0 //#define TYPE 1 //#define CF 487805 #define IMOD4 ((M+1)/2)%4 //#define XX (IMOD4%2) //#define YY (IMOD4/2) //#define NXX (1-XX) using namespace std; Miracl precision(40,0); // // Extract ECn point in internal GF2m format // void extract(EC2& A,GF2m& x,GF2m& y) { x=(A.get_point())->X; y=(A.get_point())->Y; } // // Tate Pairing - note miller -> miller variable // Loop unrolled x2 for speed // GF2m4x tate(EC2& P,EC2& Q) { GF2m xp,yp,xq,yq,t; GF2m4x miller,w,u,u0,u1,v,f,res; int i,m=M; normalise(P); normalise(Q); extract(P,xp,yp); extract(Q,xq,yq); // first calculate the contribution of adding P or -P to 2^[(m+1)/2].P // // Note that 2^[(m+1)/2].Point(x,y) = Point(x^2+1,x^2+y^2) or something similar.... // Line slope is x or x+1 (thanks Steven!) // // Then the truncated loop, four flavours... #if IMOD4 == 1 // (X=1) // (Y=0) t=xp; // 0 (X+1) f.set(t*(xp+xq+1)+yq+yp+B,t+xq+1,t+xq,0); // 0 (Y) miller=1; for (i=0;i<(m-3)/2;i+=2) { t=xp+1; xp=sqrt(xp); yp=sqrt(yp); // 1 (X) u0.set(t*(xp+xq+1)+yp+yq,t+xq+1,t+xq,0); // 1 0 (X) ((X+1)*(xp+1)+Y) xq*=xq; yq*=yq; t=xp+1; xp=sqrt(xp); yp=sqrt(yp); u1.set(t*(xp+xq+1)+yp+yq,t+xq+1,t+xq,0); xq*=xq; yq*=yq; u=mul(u0,u1); miller*=u; } // final step t=xp+1; xp=sqrt(xp); yp=sqrt(yp); u.set(t*(xp+xq+1)+yp+yq,t+xq+1,t+xq,0); miller*=u; #endif #if IMOD4 == 0 // (X=0) // (Y=0) t=xp+1; // 1 (X+1) f.set(t*(xq+xp+1)+yq+yp+B,t+xq+1,t+xq,0); // 0 (Y) miller=1; for (i=0;i<(m-1)/2;i+=2) { // loop is unrolled x 2 t=xp; xp=sqrt(xp); yp=sqrt(yp); // 0 (X) u0.set(t*(xp+xq)+yp+yq+xp+1,t+xq+1,t+xq,0); // 0 xp+1 (X) ((X+1)*(xp+1)+Y xq*=xq; yq*=yq; t=xp; xp=sqrt(xp); yp=sqrt(yp); u1.set(t*(xp+xq)+yp+yq+xp+1,t+xq+1,t+xq,0); xq*=xq; yq*=yq; u=mul(u0,u1); miller*=u; } #endif #if IMOD4 == 2 // (X=0) // (Y=1) t=xp+1; // 1 (X+1) f.set(t*(xq+xp+1)+yq+yp+B+1,t+xq+1,t+xq,0); // 1 (Y) miller=1; for (i=0;i<(m-1)/2;i+=2) { t=xp; xp=sqrt(xp); yp=sqrt(yp); // 0 (X) u0.set(t*(xp+xq)+yp+yq+xp,t+xq+1,t+xq,0); // 0 xp+0 (X) ((X+1)*(xp+1)+Y) xq*=xq; yq*=yq; t=xp; xp=sqrt(xp); yp=sqrt(yp); u1.set(t*(xp+xq)+yp+yq+xp,t+xq+1,t+xq,0); xq*=xq; yq*=yq; u=mul(u0,u1); miller*=u; } #endif #if IMOD4 == 3 // (X=1) // (Y=1) t=xp; // 0 (X+1) f.set(t*(xq+xp+1)+yq+yp+B+1,t+xq+1,t+xq,0); // 1 (Y) miller=1; for (i=0;i<(m-3)/2;i+=2) { t=xp+1; xp=sqrt(xp); yp=sqrt(yp); // 1 (X) u0.set(t*(xp+xq+1)+yp+yq+1,t+xq+1,t+xq,0); // 1 1 (X) ((X+1)*(xp+1)+Y) xq*=xq; yq*=yq; t=xp+1; xp=sqrt(xp); yp=sqrt(yp); u1.set(t*(xp+xq+1)+yp+yq+1,t+xq+1,t+xq,0); xq*=xq; yq*=yq; u=mul(u0,u1); miller*=u; } // final step t=xp+1; xp=sqrt(xp); yp=sqrt(yp); u.set(t*(xp+xq+1)+yp+yq+1,t+xq+1,t+xq,0); miller*=u; #endif miller*=f; // raising to the power (2^m-2^[m+1)/2]+1)(2^[(m+1)/2]+1)(2^(2m)-1) (TYPE 2) // or (2^m+2^[(m+1)/2]+1)(2^[(m+1)/2]-1)(2^(2m)-1) (TYPE 1) // 6 Frobenius, 4 big field muls... u=v=w=miller; for (i=0;i<(m+1)/2;i++) u*=u; #if TYPE == 1 u.powq(); w.powq(); v=w; w.powq(); res=w; w.powq(); w*=u; w*=miller; res*=v; u.powq(); u.powq(); res*=u; #else u.powq(); v.powq(); w=u*v; v.powq(); w*=v; v.powq(); u.powq(); u.powq(); res=v*u; res*=miller; #endif res/=w; return res; } int main() { EC2 P,Q,W; Big bx,s,r,x,y,order; GF2m4x res; time_t seed; int i; miracl *mip=&precision; time(&seed); irand((long)seed); if (!ecurve2(-M,T,U,V,(Big)1,(Big)B,TRUE,MR_PROJECTIVE)) // -M indicates Super-Singular { cout << "Problem with the curve" << endl; return 0; } // Curve order = 2^M+2^[(M+1)/2]+1 or 2^M-2^[(M+1)/2]+1 is nearly prime cout << "IMOD4= " << IMOD4 << endl; cout << "M%8= " << M%8 << endl; forever { bx=rand(M,2); if (P.set(bx,bx)) break; } forever { bx=rand(M,2); if (Q.set(bx,bx)) break; } /* for (int i=0;i<10000;i++) */ P*=CF; // cofactor multiplication Q*=CF; // order=pow((Big)2,M)-pow((Big)2,(M+1)/2)+1; // P*=order; // cout << "P= " << P << endl; // exit(0); /* mip->IOBASE=16; cout << "P= " << P << endl; cout << "Q= " << Q << endl; Big ddd=pow((Big)2,32); Big sx,sy; P.get(x,y); sx=x; sy=y; while (x>0) { cout << "0x" << hex << x%ddd << ","; x/=ddd; } cout << endl; while (y>0) { cout << "0x" << hex << y%ddd << ","; y/=ddd; } cout << endl; ddd=256; x=sx; y=sy; while (x>0) { cout << "0x" << hex << x%ddd << ","; x/=ddd; } cout << endl; while (y>0) { cout << "0x" << hex << y%ddd << ","; y/=ddd; } cout << endl; Q.get(x,y); sx=x; sy=y; ddd=pow((Big)2,32); while (x>0) { cout << "0x" << hex << x%ddd << ","; x/=ddd; } cout << endl; while (y>0) { cout << "0x" << hex << y%ddd << ","; y/=ddd; } cout << endl; ddd=256; x=sx; y=sy; while (x>0) { cout << "0x" << hex << x%ddd << ","; x/=ddd; } cout << endl; while (y>0) { cout << "0x" << hex << y%ddd << ","; y/=ddd; } cout << endl; exit(0); */ //for (i=0;i<1000;i++) res=tate(P,Q); s=rand(256,2); r=rand(256,2); res=pow(res,s); res=pow(res,r); //mip->IOBASE=16; cout << "e(P,Q)^sr= " << res << endl; P*=s; Q*=r; res=tate(Q,P); cout << "e(sP,rQ)= " << res << endl; //Big q=pow((Big)2,M)-pow((Big)2,(M+1)/2)+1; //cout << pow(res,q) << endl; return 0; }
5,153
990
from dataclasses import dataclass, field @dataclass class ClubMember: name: str guests: list = field(default_factory=list)
46
535
/* * 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. */ #include <os/mynewt.h> #include <trng/trng.h> #include "trng_sw_test.h" TEST_CASE_SELF(trng_sw_test_read) { struct trng_dev *dev; int rc; uint32_t val1, val2, val3; int i; uint8_t data[32]; dev = (struct trng_dev *)os_dev_lookup("trng"); TEST_ASSERT_FATAL(dev != NULL); val1 = trng_get_u32(dev); val2 = trng_get_u32(dev); TEST_ASSERT(val1 != val2); rc = trng_read(dev, &val3, sizeof(val3)); TEST_ASSERT(rc == sizeof(val3)); TEST_ASSERT(val1 != val2); TEST_ASSERT(val1 != val3); TEST_ASSERT(val2 != val3); rc = trng_read(dev, &val2, sizeof(val2)); TEST_ASSERT(rc == sizeof(val2)); TEST_ASSERT(val3 != val2); for (i = 1; i < sizeof(data); i++) { rc = trng_read(dev, data, i); TEST_ASSERT(rc == i); } }
600
922
import json import os import tempfile import unittest import pytest from calamari_ocr.ocr.dataset.datareader.generated_line_dataset import ( TextGeneratorParams, LineGeneratorParams, ) from calamari_ocr.ocr.dataset.datareader.generated_line_dataset.params import ( GeneratedLineDatasetParams, ) from calamari_ocr.scripts.train import main from calamari_ocr.test.calamari_test_scenario import CalamariTestScenario this_dir = os.path.dirname(os.path.realpath(__file__)) def default_trainer_params(): p = CalamariTestScenario.default_trainer_params() with open(os.path.join(this_dir, "data", "line_generation_config", "text_gen_params.json")) as f: text_gen_params = TextGeneratorParams.from_dict(json.load(f)) with open(os.path.join(this_dir, "data", "line_generation_config", "line_gen_params.json")) as f: line_gen_params = LineGeneratorParams.from_dict(json.load(f)) p.codec.include_files = os.path.join(this_dir, "data", "line_generation_config", "whilelist.txt") p.codec.auto_compute = False p.gen.train = GeneratedLineDatasetParams( lines_per_epoch=10, preload=False, text_generator=text_gen_params, line_generator=line_gen_params, ) p.gen.val = GeneratedLineDatasetParams( lines_per_epoch=10, preload=False, text_generator=text_gen_params, line_generator=line_gen_params, ) p.gen.setup.val.batch_size = 1 p.gen.setup.val.num_processes = 1 p.gen.setup.train.batch_size = 1 p.gen.setup.train.num_processes = 1 p.epochs = 1 p.scenario.data.pre_proc.run_parallel = False p.gen.__post_init__() p.scenario.data.__post_init__() p.scenario.__post_init__() p.__post_init__() return p @pytest.mark.skipif(os.name != "posix", reason="Do not run on windows due to missing font.") class TestTrainGenerated(unittest.TestCase): def test_train(self): trainer_params = default_trainer_params() with tempfile.TemporaryDirectory() as d: trainer_params.output_dir = d main(trainer_params)
878
984
// // UILabel+Theming.h // DynamicThemesExample // // Created by <NAME> on 3/11/15. // Copyright (c) 2015 <NAME>. All rights reserved. // @import UIKit; NS_ASSUME_NONNULL_BEGIN @class MTFThemeClass; @interface UILabel (Theming) + (NSDictionary *)mtf_textAttributesForThemeClass:(MTFThemeClass *)themeClass; @end NS_ASSUME_NONNULL_END
135
1,253
<gh_stars>1000+ /* * Copyright (c) 2008 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package nu.validator.xml; import org.xml.sax.Attributes; public final class PermutingAttributesWrapper implements Attributes { private final Attributes delegate; private final int[] permutation; public PermutingAttributesWrapper(Attributes delegate) { this.delegate = delegate; this.permutation = new int[delegate.getLength()]; for (int i = 0; i < permutation.length; i++) { permutation[i] = i; } } private int findIndex(int index) { if (index < 0) { return -1; } for (int i = 0; i < permutation.length; i++) { if (permutation[i] == index) { return i; } } throw new IllegalArgumentException("Index not in range."); } public void pullUp(String uri, String localName) { int index = getIndex(uri, localName); if (index <= 0) { return; } int temp = permutation[index]; System.arraycopy(permutation, 0, permutation, 1, index); permutation[0] = temp; } public void pushDown(String uri, String localName) { int index = getIndex(uri, localName); if (index < 0 || index == permutation.length - 1) { return; } int temp = permutation[index]; System.arraycopy(permutation, index + 1, permutation, index, permutation.length - 1 - index); permutation[permutation.length - 1] = temp; } /** * @param uri * @param localName * @return * @see org.xml.sax.Attributes#getIndex(java.lang.String, java.lang.String) */ @Override public int getIndex(String uri, String localName) { return findIndex(delegate.getIndex(uri, localName)); } /** * @param qName * @return * @see org.xml.sax.Attributes#getIndex(java.lang.String) */ @Override public int getIndex(String qName) { return findIndex(delegate.getIndex(qName)); } /** * @return * @see org.xml.sax.Attributes#getLength() */ @Override public int getLength() { return permutation.length; } /** * @param index * @return * @see org.xml.sax.Attributes#getLocalName(int) */ @Override public String getLocalName(int index) { if (index < 0 && index >= permutation.length) { return null; } return delegate.getLocalName(permutation[index]); } /** * @param index * @return * @see org.xml.sax.Attributes#getQName(int) */ @Override public String getQName(int index) { if (index < 0 && index >= permutation.length) { return null; } return delegate.getQName(permutation[index]); } /** * @param index * @return * @see org.xml.sax.Attributes#getType(int) */ @Override public String getType(int index) { if (index < 0 && index >= permutation.length) { return null; } return delegate.getType(permutation[index]); } /** * @param uri * @param localName * @return * @see org.xml.sax.Attributes#getType(java.lang.String, java.lang.String) */ @Override public String getType(String uri, String localName) { return delegate.getType(uri, localName); } /** * @param qName * @return * @see org.xml.sax.Attributes#getType(java.lang.String) */ @Override public String getType(String qName) { return delegate.getType(qName); } /** * @param index * @return * @see org.xml.sax.Attributes#getURI(int) */ @Override public String getURI(int index) { if (index < 0 && index >= permutation.length) { return null; } return delegate.getURI(permutation[index]); } /** * @param index * @return * @see org.xml.sax.Attributes#getValue(int) */ @Override public String getValue(int index) { if (index < 0 && index >= permutation.length) { return null; } return delegate.getValue(permutation[index]); } /** * @param uri * @param localName * @return * @see org.xml.sax.Attributes#getValue(java.lang.String, java.lang.String) */ @Override public String getValue(String uri, String localName) { return delegate.getValue(uri, localName); } /** * @param qName * @return * @see org.xml.sax.Attributes#getValue(java.lang.String) */ @Override public String getValue(String qName) { return delegate.getValue(qName); } }
2,402
429
/* * (C) Copyright 2018-2021 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ package io.daos.dfs; import java.io.File; import java.io.IOException; import java.net.URI; import io.daos.*; import io.daos.dfs.uns.*; /** * A wrapper class of DAOS Unified Namespace. There are four DAOS UNS methods, * {@link #resolvePath(String)} and {@link #parseAttribute(String)}, wrapped in this class. * * <p> * Due to complexity of DAOS UNS attribute, duns_attr_t, protobuf and c plugin, protobuf-c, are introduced to * pass parameters accurately and efficiently. check DunsAttribute.proto and its auto-generated classes under * package io.daos.dfs.uns. * * <p> * The typical usage is to resolve path * <code> * DunsAttribute attribute = DaosUns.resolvePath(file.getAbsolutePath()); * </code> * * <p> * 3, check DaosUnsIT for more complex usage */ public class DaosUns { private DaosUnsBuilder builder; private DunsAttribute attribute; private DaosUns() { } /** * extract and parse extended attributes from given <code>path</code>. * * @param path OS file path * @return UNS attribute * @throws IOException * {@link DaosIOException} */ public static DunsAttribute resolvePath(String path) throws IOException { byte[] bytes = DaosFsClient.dunsResolvePath(path); if (bytes == null) { return null; } return DunsAttribute.parseFrom(bytes); } /** * set application info to <code>attrName</code> on <code>path</code>. * If <code>value</code> is empty, the <code>attrName</code> will be removed from the path. * * @param path OS file path * @param attrName attribute name. Its length should not exceed {@value Constants#UNS_ATTR_NAME_MAX_LEN}. * @param value attribute value, Its length should not exceed {@value Constants#UNS_ATTR_VALUE_MAX_LEN}. * @throws IOException * {@link DaosIOException} */ public static void setAppInfo(String path, String attrName, String value) throws IOException { if (DaosUtils.isBlankStr(attrName)) { throw new IllegalArgumentException("attribute name cannot be empty"); } if (!attrName.startsWith("user.")) { throw new IllegalArgumentException("attribute name should start with \"user.\", " + attrName); } if (attrName.length() > Constants.UNS_ATTR_NAME_MAX_LEN) { throw new IllegalArgumentException("attribute name " + attrName + ", length should not exceed " + Constants.UNS_ATTR_NAME_MAX_LEN); } if (value != null && value.length() > Constants.UNS_ATTR_VALUE_MAX_LEN) { throw new IllegalArgumentException("attribute value length should not exceed " + Constants.UNS_ATTR_VALUE_MAX_LEN); } DaosFsClient.dunsSetAppInfo(path, attrName, value); } /** * get application info stored in <code>attrName</code> from <code>path</code>. * * @param path OS file path * @param attrName attribute name. Its length should not exceed {@value Constants#UNS_ATTR_NAME_MAX_LEN}. * @param maxValueLen maximum attribute length. It should not exceed {@value Constants#UNS_ATTR_VALUE_MAX_LEN}. * @return attribute value * @throws IOException * {@link DaosIOException} */ public static String getAppInfo(String path, String attrName, int maxValueLen) throws IOException { if (DaosUtils.isBlankStr(attrName)) { throw new IllegalArgumentException("attribute name cannot be empty"); } if (!attrName.startsWith("user.")) { throw new IllegalArgumentException("attribute name should start with \"user.\", " + attrName); } if (attrName.length() > Constants.UNS_ATTR_NAME_MAX_LEN) { throw new IllegalArgumentException("attribute name " + attrName + ", length should not exceed " + Constants.UNS_ATTR_NAME_MAX_LEN); } if (maxValueLen > Constants.UNS_ATTR_VALUE_MAX_LEN) { throw new IllegalArgumentException("maximum value length should not exceed " + Constants.UNS_ATTR_VALUE_MAX_LEN); } return DaosFsClient.dunsGetAppInfo(path, attrName, maxValueLen); } /** * parse input string to UNS attribute. * * @param input attribute string * @return UNS attribute * @throws IOException * {@link DaosIOException} */ public static DunsAttribute parseAttribute(String input) throws IOException { byte[] bytes = DaosFsClient.dunsParseAttribute(input); return DunsAttribute.parseFrom(bytes); } /** * get information from extended attributes of UNS path. * Some info gets from DAOS extended attribute. * The Rest gets from app extended attributes. A exception will be thrown if user expect app info and no * info gets. * * @param uri URI starts with daos:// * @return information hold in {@link DunsInfo} * @throws IOException * {@link DaosIOException} */ public static DunsInfo getAccessInfo(URI uri) throws IOException { String fullPath = uri.toString(); String path = fullPath; boolean direct = true; if (uri.getAuthority() == null || uri.getAuthority().startsWith(Constants.UNS_ID_PREFIX)) { path = uri.getPath(); // make sure path exists File f = new File(path); while (f != null && !f.exists()) { f = f.getParentFile(); } if (f == null) { return null; } path = f.getAbsolutePath(); direct = false; } DunsAttribute attribute = DaosUns.resolvePath(path); if (attribute == null) { throw new IOException("no UNS attribute get from " + fullPath); } String poolId = attribute.getPoolId(); String contId = attribute.getContId(); Layout layout = attribute.getLayoutType(); String relPath = attribute.getRelPath(); String prefix; // is direct path ? if (direct) { if (!uri.getAuthority().equals(poolId)) { throw new IOException("authority " + uri.getAuthority() + ", should be equal to poolId: " + poolId); } prefix = "/" + contId; if (layout == Layout.UNKNOWN) { layout = Layout.POSIX; // default to posix } } else { int idx = path.indexOf(relPath); if (idx < 0) { throw new IOException("path: " + path + ", should contain real path: " + relPath); } prefix = idx > 0 ? path.substring(0, idx) : path; } return new DunsInfo(poolId, contId, layout.name(), prefix); } protected DunsAttribute getAttribute() { return attribute; } public String getPath() { return builder.path; } public String getPoolUuid() { return builder.poolUuid; } public String getContUuid() { return builder.contUuid; } public Layout getLayout() { return builder.layout; } public DaosObjectType getObjectType() { return builder.objectType; } public long getChunkSize() { return builder.chunkSize; } public boolean isOnLustre() { return builder.onLustre; } /** * A builder class to build {@link DaosUns} instance. Most of methods are same as ones * in {@link io.daos.dfs.DaosFsClient.DaosFsClientBuilder}, like * {@link #serverGroup(String)}, {@link #poolFlags(int)}. * */ public static class DaosUnsBuilder implements Cloneable { private String path; private String poolUuid; private String contUuid; private Layout layout = Layout.POSIX; private DaosObjectType objectType = DaosObjectType.OC_SX; private long chunkSize = Constants.FILE_DEFAULT_CHUNK_SIZE; private boolean onLustre; private String serverGroup = Constants.POOL_DEFAULT_SERVER_GROUP; private int poolFlags = Constants.ACCESS_FLAG_POOL_READWRITE; /** * file denoted by <code>path</code> should not exist. * * @param path OS file path extended attributes associated with * @return this object */ public DaosUnsBuilder path(String path) { this.path = path; return this; } /** * set pool UUID. * * @param poolUuid * pool uuid * @return this object */ public DaosUnsBuilder poolId(String poolUuid) { this.poolUuid = poolUuid; return this; } /** * set container UUID. * * @param contUuid * container uuid * @return this object */ public DaosUnsBuilder containerId(String contUuid) { this.contUuid = contUuid; return this; } /** * set layout. * * @param layout * posix or hdf5 layout * @return this object */ public DaosUnsBuilder layout(Layout layout) { this.layout = layout; return this; } /** * set object type. * * @param objectType * object type * @return this object */ public DaosUnsBuilder objectType(DaosObjectType objectType) { this.objectType = objectType; return this; } /** * set chunk size. * * @param chunkSize * chunk size * @return this object */ public DaosUnsBuilder chunkSize(long chunkSize) { if (chunkSize < 0) { throw new IllegalArgumentException("chunk size should be positive integer"); } this.chunkSize = chunkSize; return this; } /** * set if it's on lustre FS. * * @param onLustre * true for on lustre, false otherwise. * @return this object */ public DaosUnsBuilder onLustre(boolean onLustre) { this.onLustre = onLustre; return this; } public DaosUnsBuilder serverGroup(String serverGroup) { this.serverGroup = serverGroup; return this; } public DaosUnsBuilder poolFlags(int poolFlags) { this.poolFlags = poolFlags; return this; } @Override public DaosUnsBuilder clone() throws CloneNotSupportedException { return (DaosUnsBuilder) super.clone(); } /** * verify and map parameters to UNS attribute objects whose classes are auto-generated by protobuf-c. * Then, create {@link DaosUns} object with the UNS attribute, which is to be serialized when interact * with native code. * * @return {@link DaosUns} object */ public DaosUns build() { if (path == null) { throw new IllegalArgumentException("need path"); } if (poolUuid == null) { throw new IllegalArgumentException("need pool UUID"); } if (layout == Layout.UNKNOWN || layout == Layout.UNRECOGNIZED) { throw new IllegalArgumentException("layout should be posix or HDF5"); } DaosUns duns = new DaosUns(); try { duns.builder = clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("clone not supported.", e); } buildAttribute(duns); return duns; } private void buildAttribute(DaosUns duns) { DunsAttribute.Builder builder = DunsAttribute.newBuilder(); builder.setPoolId(poolUuid); if (contUuid != null) { builder.setContId(contUuid); } builder.setLayoutType(layout); builder.setObjectType(objectType.nameWithoutOc()); builder.setChunkSize(chunkSize); builder.setOnLustre(onLustre); duns.attribute = builder.build(); } } }
4,244
4,535
<reponame>redoclag/plaidml #include "base/util/perf_counter.h" #include <iostream> #include <mutex> #include <thread> #include "base/util/error.h" namespace vertexai { namespace { std::mutex& GetMutex() { static std::mutex mu; return mu; } std::map<std::string, std::shared_ptr<std::atomic<int64_t>>>& GetTable() { static std::map<std::string, std::shared_ptr<std::atomic<int64_t>>> table; return table; } } // namespace PerfCounter::PerfCounter(const std::string& name) { std::lock_guard<std::mutex> lock(GetMutex()); auto& table = GetTable(); if (table.count(name)) { value_ = table[name]; } else { value_ = std::make_shared<std::atomic<int64_t>>(); table[name] = value_; } } int64_t GetPerfCounter(const std::string& name) { std::lock_guard<std::mutex> lock(GetMutex()); auto& table = GetTable(); auto it = table.find(name); if (it == table.end()) { throw error::NotFound(std::string("Unknown performance counter: ") + name); } return *(it->second); } void SetPerfCounter(const std::string& name, int64_t value) { std::lock_guard<std::mutex> lock(GetMutex()); auto& table = GetTable(); auto it = table.find(name); if (it == table.end()) { throw error::NotFound(std::string("Unknown performance counter: ") + name); } *(it->second) = value; } } // namespace vertexai
511
4,303
<reponame>OAID/Halide #include "Halide.h" #include <stdio.h> using namespace Halide; using namespace Halide::Internal; int main(int argc, char **argv) { if (!get_jit_target_from_environment().has_gpu_feature()) { printf("[SKIP] No GPU target enabled.\n"); return 0; } Func f("f"), g("g"); Var x("x"), y("y"); Param<int> slices; RDom r(0, 3 * slices + 1); slices.set_range(1, 256); f(x, y) = x + y; g(x, y) = sum(f(x, r)) + slices; Var xi("xi"), yi("yi"); g.compute_root().gpu_tile(x, y, xi, yi, 16, 16); f.compute_at(g, xi); slices.set(32); g.realize({1024, 1024}); printf("Success!\n"); return 0; }
327
412
#include <assert.h> struct inner_struct { char *GUARDp; }; struct outer_struct { char GUARD; struct inner_struct inner; }; void foo(struct inner_struct *inner) { assert(*(inner->GUARDp) != 1); } int main() { struct outer_struct outer; outer.GUARD = 2; outer.inner.GUARDp = &outer.GUARD; foo(&outer.inner); }
128
418
import time import pytest @pytest.mark.parametrize("index", range(7)) def test_cat(index): """Perform several tests with the same execution times.""" time.sleep(0.4) assert True
68
852
#include "Calibration/EcalTBTools/interface/TB06Reco.h" /* */ // FIXME ClassImp (TB06Reco) void TB06Reco::reset() { run = 0; event = 0; tableIsMoving = 0; S6ADC = 0; MEXTLindex = 0; MEXTLeta = 0; MEXTLphi = 0; MEXTLenergy = 0.; beamEnergy = 0.; for (int eta = 0; eta < 7; ++eta) for (int phi = 0; phi < 7; ++phi) localMap[eta][phi] = 0.; xECAL = 0.; yECAL = 0.; zECAL = 0.; xHodo = 0.; yHodo = 0.; zHodo = 0.; xSlopeHodo = 0.; ySlopeHodo = 0.; xQualityHodo = 0.; yQualityHodo = 0.; convFactor = 0.; }
273
1,109
<filename>gryphon/data_service/consts.py EXCHANGE = 'trades_exchange' EXCHANGE_TYPE = 'topic' TRADES_QUEUE = 'trades_durable' TRADES_BINDING_KEY = '*.trades.tinker' ORDERBOOK_QUEUE = 'orderbook_durable' ORDERBOOK_BINDING_KEY = '*.orderbook.tinker' EXCHANGE_VOLUME_QUEUE = 'exchange_volume_durable' EXCHANGE_VOLUME_BINDING_KEY = '*.exchange_volume.tinker' TRADES_QUEUE_OLD = 'trades' ORDERBOOK_QUEUE_OLD = 'orderbook' EXCHANGE_VOLUME_QUEUE_OLD = 'exchange_volume'
205
10,225
<gh_stars>1000+ package io.quarkus.security.jpa; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that this field or property should be used as a source of user name for security. Only * supports the {@link String} type. */ @Target({ ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Username { }
160
3,542
<filename>ignite/src/test/java/site/ycsb/db/ignite/IgniteClientTest.java /** * Copyright (c) 2018 YCSB contributors All rights reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. See accompanying * LICENSE file. */ package site.ycsb.db.ignite; import site.ycsb.ByteIterator; import site.ycsb.Status; import site.ycsb.StringByteIterator; import site.ycsb.measurements.Measurements; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.logger.log4j2.Log4J2Logger; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; /** * Integration tests for the Ignite client */ public class IgniteClientTest extends IgniteClientTestBase { private final static String HOST = "127.0.0.1"; private final static String PORTS = "47500..47509"; private final static String SERVER_NODE_NAME = "YCSB Server Node"; private static TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); @BeforeClass public static void beforeTest() throws IgniteCheckedException { IgniteConfiguration igcfg = new IgniteConfiguration(); igcfg.setIgniteInstanceName(SERVER_NODE_NAME); igcfg.setClientMode(false); TcpDiscoverySpi disco = new TcpDiscoverySpi(); Collection<String> adders = new LinkedHashSet<>(); adders.add(HOST + ":" + PORTS); ((TcpDiscoveryVmIpFinder) ipFinder).setAddresses(adders); disco.setIpFinder(ipFinder); igcfg.setDiscoverySpi(disco); igcfg.setNetworkTimeout(2000); CacheConfiguration ccfg = new CacheConfiguration().setName(DEFAULT_CACHE_NAME); igcfg.setCacheConfiguration(ccfg); Log4J2Logger logger = new Log4J2Logger(IgniteClientTest.class.getClassLoader().getResource("log4j2.xml")); igcfg.setGridLogger(logger); cluster = Ignition.start(igcfg); cluster.active(); } @Before public void setUp() throws Exception { Properties p = new Properties(); p.setProperty("hosts", HOST); p.setProperty("ports", PORTS); Measurements.setProperties(p); client = new IgniteClient(); client.setProperties(p); client.init(); } @Test public void testInsert() throws Exception { cluster.cache(DEFAULT_CACHE_NAME).clear(); final String key = "key"; final Map<String, String> input = new HashMap<>(); input.put("field0", "value1"); input.put("field1", "value2"); final Status status = client.insert(DEFAULT_CACHE_NAME, key, StringByteIterator.getByteIteratorMap(input)); assertThat(status, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(1)); } @Test public void testDelete() throws Exception { cluster.cache(DEFAULT_CACHE_NAME).clear(); final String key1 = "key1"; final Map<String, String> input1 = new HashMap<>(); input1.put("field0", "value1"); input1.put("field1", "value2"); final Status status1 = client.insert(DEFAULT_CACHE_NAME, key1, StringByteIterator.getByteIteratorMap(input1)); assertThat(status1, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(1)); final String key2 = "key2"; final Map<String, String> input2 = new HashMap<>(); input2.put("field0", "value1"); input2.put("field1", "value2"); final Status status2 = client.insert(DEFAULT_CACHE_NAME, key2, StringByteIterator.getByteIteratorMap(input2)); assertThat(status2, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(2)); final Status status3 = client.delete(DEFAULT_CACHE_NAME, key2); assertThat(status3, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(1)); } @Test public void testRead() throws Exception { cluster.cache(DEFAULT_CACHE_NAME).clear(); final String key = "key"; final Map<String, String> input = new HashMap<>(); input.put("field0", "value1"); input.put("field1", "value2A"); input.put("field3", null); final Status sPut = client.insert(DEFAULT_CACHE_NAME, key, StringByteIterator.getByteIteratorMap(input)); assertThat(sPut, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(1)); final Set<String> fld = new TreeSet<>(); fld.add("field0"); fld.add("field1"); fld.add("field3"); final HashMap<String, ByteIterator> result = new HashMap<>(); final Status sGet = client.read(DEFAULT_CACHE_NAME, key, fld, result); assertThat(sGet, is(Status.OK)); final HashMap<String, String> strResult = new HashMap<String, String>(); for (final Map.Entry<String, ByteIterator> e : result.entrySet()) { if (e.getValue() != null) { strResult.put(e.getKey(), e.getValue().toString()); } } assertThat(strResult, hasEntry("field0", "value1")); assertThat(strResult, hasEntry("field1", "value2A")); } @Test public void testReadAllFields() throws Exception { cluster.cache(DEFAULT_CACHE_NAME).clear(); final String key = "key"; final Map<String, String> input = new HashMap<>(); input.put("field0", "value1"); input.put("field1", "value2A"); input.put("field3", null); final Status sPut = client.insert(DEFAULT_CACHE_NAME, key, StringByteIterator.getByteIteratorMap(input)); assertThat(sPut, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(1)); final Set<String> fld = new TreeSet<>(); final HashMap<String, ByteIterator> result1 = new HashMap<>(); final Status sGet = client.read(DEFAULT_CACHE_NAME, key, fld, result1); assertThat(sGet, is(Status.OK)); final HashMap<String, String> strResult = new HashMap<String, String>(); for (final Map.Entry<String, ByteIterator> e : result1.entrySet()) { if (e.getValue() != null) { strResult.put(e.getKey(), e.getValue().toString()); } } assertThat(strResult, hasEntry("field0", "value1")); assertThat(strResult, hasEntry("field1", "value2A")); } @Test public void testReadNotPresent() throws Exception { cluster.cache(DEFAULT_CACHE_NAME).clear(); final String key = "key"; final Map<String, String> input = new HashMap<>(); input.put("field0", "value1"); input.put("field1", "value2A"); input.put("field3", null); final Status sPut = client.insert(DEFAULT_CACHE_NAME, key, StringByteIterator.getByteIteratorMap(input)); assertThat(sPut, is(Status.OK)); assertThat(cluster.cache(DEFAULT_CACHE_NAME).size(), is(1)); final Set<String> fld = new TreeSet<>(); final String newKey = "newKey"; final HashMap<String, ByteIterator> result1 = new HashMap<>(); final Status sGet = client.read(DEFAULT_CACHE_NAME, newKey, fld, result1); assertThat(sGet, is(Status.NOT_FOUND)); } }
2,791
8,629
<gh_stars>1000+ #pragma once #include <functional> #include <memory> #include <unordered_map> #include <base/types.h> #include <boost/core/noncopyable.hpp> namespace DB { class IRemoteFileMetadata { public: virtual ~IRemoteFileMetadata() = default; virtual String getName() const = 0; //class name // deserialize virtual bool fromString(const String & buf) = 0; // serialize virtual String toString() const = 0; // Used for comparing two file metadatas are the same or not. virtual String getVersion() const = 0; String remote_path; size_t file_size = 0; UInt64 last_modification_timestamp = 0; }; using IRemoteFileMetadataPtr = std::shared_ptr<IRemoteFileMetadata>; }
256
587
<gh_stars>100-1000 { "edges": { "BasicEdge": { "source": "vertex.string", "destination": "vertex.string", "directed": "directed.either", "properties": { "columnQualifier": "colQualProperty", "property1": "simpleProperty" }, "groupBy": [ "columnQualifier" ] } }, "types": { "vertex.string": { "class": "java.lang.String" }, "directed.either": { "class": "java.lang.Boolean" }, "simpleProperty": { "class": "java.lang.Integer", "aggregateFunction": { "class": "uk.gov.gchq.koryphe.impl.binaryoperator.Sum" }, "serialiser": { "class": "uk.gov.gchq.gaffer.serialisation.implementation.raw.CompactRawIntegerSerialiser" } }, "colQualProperty": { "class": "java.lang.Integer", "aggregateFunction": { "class": "uk.gov.gchq.koryphe.impl.binaryoperator.Sum" }, "serialiser": { "class": "uk.gov.gchq.gaffer.serialisation.implementation.raw.RawIntegerSerialiser" } } } }
507
2,542
<reponame>AnthonyM/service-fabric // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Reliability { namespace FailoverManagerComponent { class ServiceCache::UpdateServiceTypesAsyncOperation : public Common::AsyncOperation { DENY_COPY(UpdateServiceTypesAsyncOperation); public: UpdateServiceTypesAsyncOperation( ServiceCache & serviceCache, std::vector<ServiceModel::ServiceTypeIdentifier> && serviceTypeIds, uint64 sequenceNumber, Federation::NodeId const& nodeId, ServiceTypeUpdateKind::Enum serviceTypeUpdateEvent, Common::AsyncCallback const& callback, Common::AsyncOperationSPtr const& parent); ~UpdateServiceTypesAsyncOperation(); static Common::ErrorCode End(Common::AsyncOperationSPtr const& operation); protected: void OnStart(Common::AsyncOperationSPtr const& thisSPtr) override; private: void OnUpdateServiceTypeCompleted( Common::AsyncOperationSPtr const& operation, Common::ErrorCode error); ServiceCache & serviceCache_; std::vector<ServiceModel::ServiceTypeIdentifier> serviceTypeIds_; uint64 sequenceNumber_; Federation::NodeId nodeId_; ServiceTypeUpdateKind::Enum serviceTypeUpdateEvent_; Common::atomic_uint64 pendingCount_; Common::FirstErrorTracker errorTracker_; }; } }
689
381
<gh_stars>100-1000 import math import os import questionary import urllib.error import pycountry import pycountry_convert as pcc import requests.exceptions from fuzzywuzzy import fuzz from pyquery import PyQuery from hdx.data.dataset import Dataset from hdx.data.organization import Organization from hdx.hdx_configuration import Configuration from time import sleep CONTINENTS = [ {'code': 'af', 'name': 'Africa', 'geofabrik': 'africa'}, {'code': 'an', 'name': 'Antarctica', 'geofabrik': 'antarctica'}, {'code': 'as', 'name': 'Asia', 'geofabrik': 'asia'}, {'code': 'na', 'name': 'Central America', 'geofabrik': 'central-america'}, {'code': 'eu', 'name': 'Europe', 'geofabrik': 'europe'}, {'code': 'na', 'name': 'North America', 'geofabrik': 'north-america'}, {'code': 'oc', 'name': 'Oceania', 'geofabrik': 'australia-oceania'}, {'code': 'sa', 'name': 'South America', 'geofabrik': 'south-america'} ] def select_local_country(directory): continents = os.listdir(directory) continent_names = list(map(lambda c: pcc.convert_continent_code_to_continent_name(c.upper()), continents)) continent = questionary.select('Which continent are you interested in?', choices=continent_names).ask() continent = continents[continent_names.index(continent)] continent_path = f'{directory}/{continent}' countries = os.listdir(continent_path) country_names = list(map(lambda c: pcc.map_country_alpha3_to_country_name()[c.upper()] or c, countries)) country = questionary.select('Which country are you interested in?', choices=country_names).ask() country = countries[country_names.index(country)] return f'{continent_path}/{country}' def select_local_osm_file(directory): country_path = select_local_country(directory) if os.path.isdir(country_path + '/osm-parquetizer'): return country_path regions = os.listdir(country_path) region = questionary.select('Which region are you interested in?', choices=regions).ask() if region: return f'{country_path}/{region}' def select_osm_file(): base_url = 'https://download.geofabrik.de' file_suffix = '-latest.osm.pbf' def pick_region(url: str): d = None sleep_time = 1 max_sleep_time = math.pow(2, 4) while not d: try: d = PyQuery(url=url) except urllib.error.HTTPError as e: if e.code == 404: return dict(url=f'{url}{file_suffix}', all=True) except urllib.error.URLError as e: if sleep_time <= max_sleep_time: sleep(sleep_time) sleep_time *= 2 else: raise ConnectionRefusedError() except requests.exceptions.SSLError as e: if sleep_time <= max_sleep_time: sleep(sleep_time) sleep_time *= 2 else: raise ConnectionRefusedError() regions = d.find(f"a[href$='{file_suffix}']") regions = list(map(lambda rf: rf.text.split(file_suffix)[0], filter(lambda r: r.text, regions))) regions.insert(0, 'all') selected_region = questionary.select('Which region are you interested in?', choices=regions).ask() if selected_region == 'all': return dict(url=f'{url}{file_suffix}', all=True) return dict(url=f'{url}/{selected_region}', all=False) continent_names = list(map((lambda c: c['name']), CONTINENTS)) continent = questionary.select('Which continent are you interested in?', choices=continent_names).ask() continent = CONTINENTS[continent_names.index(continent)] continent_geofabrik = continent['geofabrik'] continent = continent['code'] country = pick_region(f'{base_url}/{continent_geofabrik}') file = dict(url=None, continent=continent, country=None, country_region=None) if country: country_parts = country['url'].split(continent_geofabrik + '/') # Entire continent selected if len(country_parts) < 2: file['url'] = country['url'] return file region = pick_region(country['url']) try: file['country'] = pycountry.countries.search_fuzzy(country_parts[1])[0].alpha_3.lower() except LookupError: countries = pycountry.countries.objects countries = list(map( lambda c: dict( code=c.alpha_3.lower(), distance=fuzz.token_set_ratio(c.name.lower(), country_parts[1])) , countries)) country = max(countries, key=lambda c: c['distance']) if country['distance'] > 80: # TODO: Consider exceptions like 'malaysia-singapore-brunei' file['country'] = country['code'] else: file['country'] = country_parts[1] if region['all']: file['url'] = region['url'] return file file['url'] = region['url'] + file_suffix file['country_region'] = region['url'].split(country_parts[1] + '/')[1].lower() return file return None def get_countries_with_population_data(return_country_code=False): Configuration.create(hdx_site='prod', user_agent='Kuwala', hdx_read_only=True) # The identifier is for Facebook. This shouldn't change from HDX's side in the future since it's an id. datasets = Organization.read_from_hdx(identifier='74ad0574-923d-430b-8d52-ad80256c4461').get_datasets( query='Population') datasets = sorted( filter( lambda d: 'population' in d['title'].lower() and 'csv' in d['file_types'], map( lambda d: dict(id=d.get('id'), title=d.get('title'), location=d.get_location_names(), country_code=d.get_location_iso3s(), file_types=d.get_filetypes(), updated_date=d.get('last_modified')[:10]), datasets ) ), key=lambda d: d['location'][0]) countries = list(map(lambda d: d['location'][0] if not return_country_code else d['country_code'][0], datasets)) return datasets, countries def select_population_file(country_code=None): datasets, countries = get_countries_with_population_data() if not country_code: country = questionary \ .select('For which country do you want to download the population data?', choices=countries) \ .ask() dataset = datasets[countries.index(country)] else: dataset = next((d for d in datasets if d['country_code'][0].lower() == country_code), None) country = dataset['country_code'][0].upper() country_alpha_2 = pcc.country_alpha3_to_country_alpha2(country) continent = pcc.country_alpha2_to_continent_code(country_alpha_2) dataset['country'] = country.lower() dataset['continent'] = continent.lower() del dataset['country_code'] return dataset def select_demographic_groups(d: Dataset): resources = d.get_resources() def get_type(name: str): name = name.lower() if ('women' in name) and ('reproductive' not in name): return 'women' if ('men' in name) and ('women' not in name): return 'men' if 'children' in name: return 'children_under_five' if 'youth' in name: return 'youth_15_24' if 'elderly' in name: return 'elderly_60_plus' if 'reproductive' in name: return 'women_of_reproductive_age_15_49' return 'total' resources = list(filter( lambda resource: resource['format'].lower() == 'csv', map( lambda resource: dict( id=resource.get('id'), format=resource.get('format'), type=get_type(resource.get('name')), date=resource.get('last_modified')[:10], ), resources ) )) resources = list(map(lambda r: dict(id=r['id'], type=r['type'], updated=r['date']), resources)) resource_names = list(map(lambda r: r['type'], resources)) selected_resources = questionary \ .checkbox('Which demographic groups do you want to include?', choices=resource_names) \ .ask() return list(filter(lambda resource: resource['type'] in selected_resources, resources))
3,602
1,217
<reponame>lishaojiang/GameEngineFromScratch #pragma once #include "BaseApplication.hpp"
30
2,151
// 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. #include "third_party/blink/renderer/core/editing/iterators/simplified_backwards_text_iterator.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/core/editing/selection_template.h" #include "third_party/blink/renderer/core/editing/testing/editing_test_base.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { namespace simplified_backwards_text_iterator_test { TextIteratorBehavior EmitsSmallXForTextSecurityBehavior() { return TextIteratorBehavior::Builder() .SetEmitsSmallXForTextSecurity(true) .Build(); } class SimplifiedBackwardsTextIteratorTest : public EditingTestBase { protected: std::string ExtractStringInRange( const std::string selection_text, const TextIteratorBehavior& behavior = TextIteratorBehavior()) { const SelectionInDOMTree selection = SetSelectionTextToBody(selection_text); StringBuilder builder; bool is_first = true; for (SimplifiedBackwardsTextIterator iterator(selection.ComputeRange(), behavior); !iterator.AtEnd(); iterator.Advance()) { BackwardsTextBuffer buffer; iterator.CopyTextTo(&buffer); if (!is_first) builder.Append(", ", 2); is_first = false; builder.Append(buffer.Data(), buffer.Size()); } CString utf8 = builder.ToString().Utf8(); return std::string(utf8.data(), utf8.length()); } }; template <typename Strategy> static String ExtractString(const Element& element) { const EphemeralRangeTemplate<Strategy> range = EphemeralRangeTemplate<Strategy>::RangeOfContents(element); BackwardsTextBuffer buffer; for (SimplifiedBackwardsTextIteratorAlgorithm<Strategy> it(range); !it.AtEnd(); it.Advance()) { it.CopyTextTo(&buffer); } return String(buffer.Data(), buffer.Size()); } TEST_F(SimplifiedBackwardsTextIteratorTest, CopyTextToWithFirstLetterPart) { InsertStyleElement("p::first-letter {font-size: 200%}"); // TODO(editing-dev): |SimplifiedBackwardsTextIterator| should not account // collapsed whitespace (http://crbug.com/760428) // Simulate PreviousBoundary() EXPECT_EQ(" , \n", ExtractStringInRange("^<p> |[(3)]678</p>")); EXPECT_EQ(" [, \n", ExtractStringInRange("^<p> [|(3)]678</p>")); EXPECT_EQ(" [(, \n", ExtractStringInRange("^<p> [(|3)]678</p>")); EXPECT_EQ(" [(3, \n", ExtractStringInRange("^<p> [(3|)]678</p>")); EXPECT_EQ(" [(3), \n", ExtractStringInRange("^<p> [(3)|]678</p>")); EXPECT_EQ(" [(3)], \n", ExtractStringInRange("^<p> [(3)]|678</p>")); EXPECT_EQ("6, [(3)], \n, ab", ExtractStringInRange("^ab<p> [(3)]6|78</p>")) << "From remaining part to outside"; EXPECT_EQ("(3)", ExtractStringInRange("<p> [^(3)|]678</p>")) << "Iterate in first-letter part"; EXPECT_EQ("67, (3)]", ExtractStringInRange("<p> [^(3)]67|8</p>")) << "From remaining part to first-letter part"; EXPECT_EQ("789", ExtractStringInRange("<p> [(3)]6^789|a</p>")) << "Iterate in remaining part"; EXPECT_EQ("9, \n, 78", ExtractStringInRange("<p> [(3)]6^78</p>9|a")) << "Enter into remaining part and stop in remaining part"; EXPECT_EQ("9, \n, 678, (3)]", ExtractStringInRange("<p> [^(3)]678</p>9|a")) << "Enter into remaining part and stop in first-letter part"; } TEST_F(SimplifiedBackwardsTextIteratorTest, Basic) { SetBodyContent("<p> [(3)]678</p>"); const Element* const sample = GetDocument().QuerySelector("p"); SimplifiedBackwardsTextIterator iterator(EphemeralRange( Position(sample->firstChild(), 0), Position(sample->firstChild(), 9))); // TODO(editing-dev): |SimplifiedBackwardsTextIterator| should not account // collapsed whitespace (http://crbug.com/760428) EXPECT_EQ(9, iterator.length()) << "We should have 8 as ignoring collapsed whitespace."; EXPECT_EQ(Position(sample->firstChild(), 0), iterator.StartPosition()); EXPECT_EQ(Position(sample->firstChild(), 9), iterator.EndPosition()); EXPECT_EQ(sample->firstChild(), iterator.StartContainer()); EXPECT_EQ(9, iterator.EndOffset()); EXPECT_EQ(sample->firstChild(), iterator.GetNode()); EXPECT_EQ('8', iterator.CharacterAt(0)); EXPECT_EQ('7', iterator.CharacterAt(1)); EXPECT_EQ('6', iterator.CharacterAt(2)); EXPECT_EQ(']', iterator.CharacterAt(3)); EXPECT_EQ(')', iterator.CharacterAt(4)); EXPECT_EQ('3', iterator.CharacterAt(5)); EXPECT_EQ('(', iterator.CharacterAt(6)); EXPECT_EQ('[', iterator.CharacterAt(7)); EXPECT_EQ(' ', iterator.CharacterAt(8)); EXPECT_FALSE(iterator.AtEnd()); iterator.Advance(); EXPECT_TRUE(iterator.AtEnd()); } TEST_F(SimplifiedBackwardsTextIteratorTest, FirstLetter) { SetBodyContent( "<style>p::first-letter {font-size: 200%}</style>" "<p> [(3)]678</p>"); const Element* const sample = GetDocument().QuerySelector("p"); SimplifiedBackwardsTextIterator iterator(EphemeralRange( Position(sample->firstChild(), 0), Position(sample->firstChild(), 9))); EXPECT_EQ(3, iterator.length()); EXPECT_EQ(Position(sample->firstChild(), 6), iterator.StartPosition()); EXPECT_EQ(Position(sample->firstChild(), 9), iterator.EndPosition()); EXPECT_EQ(sample->firstChild(), iterator.StartContainer()); EXPECT_EQ(9, iterator.EndOffset()); EXPECT_EQ(sample->firstChild(), iterator.GetNode()); EXPECT_EQ('8', iterator.CharacterAt(0)); EXPECT_EQ('7', iterator.CharacterAt(1)); EXPECT_EQ('6', iterator.CharacterAt(2)); iterator.Advance(); // TODO(editing-dev): |SimplifiedBackwardsTextIterator| should not account // collapsed whitespace (http://crbug.com/760428) EXPECT_EQ(6, iterator.length()) << "We should have 5 as ignoring collapsed whitespace."; EXPECT_EQ(Position(sample->firstChild(), 0), iterator.StartPosition()); EXPECT_EQ(Position(sample->firstChild(), 6), iterator.EndPosition()); EXPECT_EQ(sample->firstChild(), iterator.StartContainer()); EXPECT_EQ(6, iterator.EndOffset()); EXPECT_EQ(sample->firstChild(), iterator.GetNode()); EXPECT_EQ(']', iterator.CharacterAt(0)); EXPECT_EQ(')', iterator.CharacterAt(1)); EXPECT_EQ('3', iterator.CharacterAt(2)); EXPECT_EQ('(', iterator.CharacterAt(3)); EXPECT_EQ('[', iterator.CharacterAt(4)); EXPECT_EQ(' ', iterator.CharacterAt(5)); EXPECT_FALSE(iterator.AtEnd()); iterator.Advance(); EXPECT_TRUE(iterator.AtEnd()); } TEST_F(SimplifiedBackwardsTextIteratorTest, SubrangeWithReplacedElements) { static const char* body_content = "<a id=host><b id=one>one</b> not appeared <b id=two>two</b></a>"; const char* shadow_content = "three <content select=#two></content> <content select=#one></content> " "zero"; SetBodyContent(body_content); SetShadowContent(shadow_content, "host"); Element* host = GetDocument().getElementById("host"); // We should not apply DOM tree version to containing shadow tree in // general. To record current behavior, we have this test. even if it // isn't intuitive. EXPECT_EQ("onetwo", ExtractString<EditingStrategy>(*host)); EXPECT_EQ("three two one zero", ExtractString<EditingInFlatTreeStrategy>(*host)); } TEST_F(SimplifiedBackwardsTextIteratorTest, characterAt) { const char* body_content = "<a id=host><b id=one>one</b> not appeared <b id=two>two</b></a>"; const char* shadow_content = "three <content select=#two></content> <content select=#one></content> " "zero"; SetBodyContent(body_content); SetShadowContent(shadow_content, "host"); Element* host = GetDocument().getElementById("host"); EphemeralRangeTemplate<EditingStrategy> range1( EphemeralRangeTemplate<EditingStrategy>::RangeOfContents(*host)); SimplifiedBackwardsTextIteratorAlgorithm<EditingStrategy> back_iter1(range1); const char* message1 = "|backIter1| should emit 'one' and 'two' in reverse order."; EXPECT_EQ('o', back_iter1.CharacterAt(0)) << message1; EXPECT_EQ('w', back_iter1.CharacterAt(1)) << message1; EXPECT_EQ('t', back_iter1.CharacterAt(2)) << message1; back_iter1.Advance(); EXPECT_EQ('e', back_iter1.CharacterAt(0)) << message1; EXPECT_EQ('n', back_iter1.CharacterAt(1)) << message1; EXPECT_EQ('o', back_iter1.CharacterAt(2)) << message1; EphemeralRangeTemplate<EditingInFlatTreeStrategy> range2( EphemeralRangeTemplate<EditingInFlatTreeStrategy>::RangeOfContents( *host)); SimplifiedBackwardsTextIteratorAlgorithm<EditingInFlatTreeStrategy> back_iter2(range2); const char* message2 = "|backIter2| should emit 'three ', 'two', ' ', 'one' and ' zero' in " "reverse order."; EXPECT_EQ('o', back_iter2.CharacterAt(0)) << message2; EXPECT_EQ('r', back_iter2.CharacterAt(1)) << message2; EXPECT_EQ('e', back_iter2.CharacterAt(2)) << message2; EXPECT_EQ('z', back_iter2.CharacterAt(3)) << message2; EXPECT_EQ(' ', back_iter2.CharacterAt(4)) << message2; back_iter2.Advance(); EXPECT_EQ('e', back_iter2.CharacterAt(0)) << message2; EXPECT_EQ('n', back_iter2.CharacterAt(1)) << message2; EXPECT_EQ('o', back_iter2.CharacterAt(2)) << message2; back_iter2.Advance(); EXPECT_EQ(' ', back_iter2.CharacterAt(0)) << message2; back_iter2.Advance(); EXPECT_EQ('o', back_iter2.CharacterAt(0)) << message2; EXPECT_EQ('w', back_iter2.CharacterAt(1)) << message2; EXPECT_EQ('t', back_iter2.CharacterAt(2)) << message2; back_iter2.Advance(); EXPECT_EQ(' ', back_iter2.CharacterAt(0)) << message2; EXPECT_EQ('e', back_iter2.CharacterAt(1)) << message2; EXPECT_EQ('e', back_iter2.CharacterAt(2)) << message2; EXPECT_EQ('r', back_iter2.CharacterAt(3)) << message2; EXPECT_EQ('h', back_iter2.CharacterAt(4)) << message2; EXPECT_EQ('t', back_iter2.CharacterAt(5)) << message2; } TEST_F(SimplifiedBackwardsTextIteratorTest, copyTextTo) { const char* body_content = "<a id=host><b id=one>one</b> not appeared <b id=two>two</b></a>"; const char* shadow_content = "three <content select=#two></content> <content select=#one></content> " "zero"; SetBodyContent(body_content); SetShadowContent(shadow_content, "host"); Element* host = GetDocument().getElementById("host"); const char* message = "|backIter%d| should have emitted '%s' in reverse order."; EphemeralRangeTemplate<EditingStrategy> range1( EphemeralRangeTemplate<EditingStrategy>::RangeOfContents(*host)); SimplifiedBackwardsTextIteratorAlgorithm<EditingStrategy> back_iter1(range1); BackwardsTextBuffer output1; back_iter1.CopyTextTo(&output1, 0, 2); EXPECT_EQ("wo", String(output1.Data(), output1.Size())) << String::Format(message, 1, "wo").Utf8().data(); back_iter1.CopyTextTo(&output1, 2, 1); EXPECT_EQ("two", String(output1.Data(), output1.Size())) << String::Format(message, 1, "two").Utf8().data(); back_iter1.Advance(); back_iter1.CopyTextTo(&output1, 0, 1); EXPECT_EQ("etwo", String(output1.Data(), output1.Size())) << String::Format(message, 1, "etwo").Utf8().data(); back_iter1.CopyTextTo(&output1, 1, 2); EXPECT_EQ("onetwo", String(output1.Data(), output1.Size())) << String::Format(message, 1, "onetwo").Utf8().data(); EphemeralRangeTemplate<EditingInFlatTreeStrategy> range2( EphemeralRangeTemplate<EditingInFlatTreeStrategy>::RangeOfContents( *host)); SimplifiedBackwardsTextIteratorAlgorithm<EditingInFlatTreeStrategy> back_iter2(range2); BackwardsTextBuffer output2; back_iter2.CopyTextTo(&output2, 0, 2); EXPECT_EQ("ro", String(output2.Data(), output2.Size())) << String::Format(message, 2, "ro").Utf8().data(); back_iter2.CopyTextTo(&output2, 2, 3); EXPECT_EQ(" zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, " zero").Utf8().data(); back_iter2.Advance(); back_iter2.CopyTextTo(&output2, 0, 1); EXPECT_EQ("e zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, "e zero").Utf8().data(); back_iter2.CopyTextTo(&output2, 1, 2); EXPECT_EQ("one zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, "one zero").Utf8().data(); back_iter2.Advance(); back_iter2.CopyTextTo(&output2, 0, 1); EXPECT_EQ(" one zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, " one zero").Utf8().data(); back_iter2.Advance(); back_iter2.CopyTextTo(&output2, 0, 2); EXPECT_EQ("wo one zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, "wo one zero").Utf8().data(); back_iter2.CopyTextTo(&output2, 2, 1); EXPECT_EQ("two one zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, "two one zero").Utf8().data(); back_iter2.Advance(); back_iter2.CopyTextTo(&output2, 0, 3); EXPECT_EQ("ee two one zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, "ee two one zero").Utf8().data(); back_iter2.CopyTextTo(&output2, 3, 3); EXPECT_EQ("three two one zero", String(output2.Data(), output2.Size())) << String::Format(message, 2, "three two one zero").Utf8().data(); } TEST_F(SimplifiedBackwardsTextIteratorTest, CopyWholeCodePoints) { const char* body_content = "&#x13000;&#x13001;&#x13002; &#x13140;&#x13141;."; SetBodyContent(body_content); const UChar kExpected[] = {0xD80C, 0xDC00, 0xD80C, 0xDC01, 0xD80C, 0xDC02, ' ', 0xD80C, 0xDD40, 0xD80C, 0xDD41, '.'}; EphemeralRange range(EphemeralRange::RangeOfContents(GetDocument())); SimplifiedBackwardsTextIterator iter(range); BackwardsTextBuffer buffer; EXPECT_EQ(1, iter.CopyTextTo(&buffer, 0, 1)) << "Should emit 1 UChar for '.'."; EXPECT_EQ(2, iter.CopyTextTo(&buffer, 1, 1)) << "Should emit 2 UChars for 'U+13141'."; EXPECT_EQ(2, iter.CopyTextTo(&buffer, 3, 2)) << "Should emit 2 UChars for 'U+13140'."; EXPECT_EQ(5, iter.CopyTextTo(&buffer, 5, 4)) << "Should emit 5 UChars for 'U+13001U+13002 '."; EXPECT_EQ(2, iter.CopyTextTo(&buffer, 10, 2)) << "Should emit 2 UChars for 'U+13000'."; for (int i = 0; i < 12; i++) EXPECT_EQ(kExpected[i], buffer[i]); } TEST_F(SimplifiedBackwardsTextIteratorTest, TextSecurity) { InsertStyleElement("s {-webkit-text-security:disc;}"); EXPECT_EQ("baz, xxx, abc", ExtractStringInRange("^abc<s>foo</s>baz|", EmitsSmallXForTextSecurityBehavior())); // E2 80 A2 is U+2022 BULLET EXPECT_EQ("baz, \xE2\x80\xA2\xE2\x80\xA2\xE2\x80\xA2, abc", ExtractStringInRange("^abc<s>foo</s>baz|", TextIteratorBehavior())); } } // namespace simplified_backwards_text_iterator_test } // namespace blink
5,687
18,965
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.fresco.samples.showcase.postprocessor; import android.graphics.Bitmap; import com.facebook.imagepipeline.request.BasePostprocessor; /** * Applies a grey-scale effect on the bitmap using the slow {@link Bitmap#setPixel(int, int, int)} * method. */ public class SlowGreyScalePostprocessor extends BasePostprocessor { static int getGreyColor(int color) { final int r = (color >> 16) & 0xFF; final int g = (color >> 8) & 0xFF; final int b = color & 0xFF; // see: https://en.wikipedia.org/wiki/Relative_luminance final int luminance = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b); return 0xFF000000 | luminance << 16 | luminance << 8 | luminance; } @Override public void process(Bitmap bitmap) { final int w = bitmap.getWidth(); final int h = bitmap.getHeight(); for (int x = 0; x < w; x++) { for (int y = 0; y < h; y++) { /* * Using {@link Bitmap#getPixel} when iterating about an entire bitmap is inefficient as it * causes many JNI calls. This is only done here to provide a comparison to * {@link FasterGreyScalePostprocessor}. */ final int color = bitmap.getPixel(x, y); bitmap.setPixel(x, y, SlowGreyScalePostprocessor.getGreyColor(color)); } } } }
541
5,169
{ "name": "WeakCollection", "version": "1.0.0", "summary": "Weak reference Array", "description": "Swift Arrays Holding Elements With Weak References", "homepage": "https://github.com/gsabatie/WeakCollection", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "gsabatie": "<EMAIL>" }, "source": { "git": "https://github.com/gsabatie/WeakCollection.git", "tag": "1.0.0" }, "platforms": { "ios": "10.0" }, "source_files": "WeakCollection/Classes/**/*", "swift_versions": "4.2", "swift_version": "4.2" }
237
454
<filename>implementation/src/test/java/io/smallrye/mutiny/infrastructure/InfrastructureHelper.java package io.smallrye.mutiny.infrastructure; import java.lang.reflect.Field; import java.util.*; public class InfrastructureHelper { private static final Field uni_interceptors; private static final Field multi_interceptors; private static final Field callback_decorators; static { try { uni_interceptors = Infrastructure.class.getDeclaredField("UNI_INTERCEPTORS"); multi_interceptors = Infrastructure.class.getDeclaredField("MULTI_INTERCEPTORS"); callback_decorators = Infrastructure.class.getDeclaredField("CALLBACK_DECORATORS"); uni_interceptors.setAccessible(true); multi_interceptors.setAccessible(true); callback_decorators.setAccessible(true); } catch (NoSuchFieldException e) { throw new IllegalStateException(e); } } public static void registerUniInterceptor(UniInterceptor itcp) { try { UniInterceptor[] array = (UniInterceptor[]) uni_interceptors.get(null); List<UniInterceptor> list = new ArrayList<>(Arrays.asList(array)); list.add(itcp); list.sort(Comparator.comparingInt(MutinyInterceptor::ordinal)); uni_interceptors.set(null, list.toArray(new UniInterceptor[0])); } catch (Exception e) { throw new IllegalStateException(e); } } public static void registerCallbackDecorator(CallbackDecorator cd) { try { CallbackDecorator[] array = (CallbackDecorator[]) callback_decorators.get(null); List<CallbackDecorator> list = new ArrayList<>(Arrays.asList(array)); list.add(cd); list.sort(Comparator.comparingInt(MutinyInterceptor::ordinal)); callback_decorators.set(null, list.toArray(new CallbackDecorator[0])); } catch (Exception e) { throw new IllegalStateException(e); } } public static List<UniInterceptor> getUniInterceptors() { try { UniInterceptor[] itcp = (UniInterceptor[]) uni_interceptors.get(null); return Arrays.asList(itcp); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } }
975
334
<filename>tests/handlers/asgi/test_handle_asgi.py from starlette.status import HTTP_200_OK from starlette.types import Receive, Scope, Send from starlite import Controller, MediaType, Response, asgi, create_test_client def test_handle_asgi() -> None: @asgi(path="/") async def root_asgi_handler(scope: Scope, receive: Receive, send: Send) -> None: assert scope["type"] == "http" assert scope["method"] == "GET" response = Response("Hello World", media_type=MediaType.TEXT, status_code=HTTP_200_OK) await response(scope, receive, send) class MyController(Controller): path = "/asgi" @asgi() async def root_asgi_handler(self, scope: Scope, receive: Receive, send: Send) -> None: assert scope["type"] == "http" assert scope["method"] == "GET" response = Response("Hello World", media_type=MediaType.TEXT, status_code=HTTP_200_OK) await response(scope, receive, send) with create_test_client([root_asgi_handler, MyController]) as client: response = client.get("/") assert response.status_code == HTTP_200_OK assert response.text == "Hello World" response = client.get("/asgi") assert response.status_code == HTTP_200_OK assert response.text == "Hello World"
508
528
<gh_stars>100-1000 #include <stdint.h> #include <string.h> #include "callibri.h" #include "timestamp.h" #ifdef _WIN32 #include <windows.h> #else #include <unistd.h> #endif ////////////////////////////////////////// // Implementation for Windows and APPLE // ////////////////////////////////////////// #if defined _WIN32 || defined __APPLE__ Callibri::Callibri (int board_id, struct BrainFlowInputParams params) : NeuromdBoard (board_id, params) { is_streaming = false; keep_alive = false; initialized = false; signal_channel = NULL; counter = 0; } Callibri::~Callibri () { skip_logs = true; release_session (); } int Callibri::prepare_session () { if (initialized) { safe_logger (spdlog::level::info, "Session is already prepared"); return (int)BrainFlowExitCodes::STATUS_OK; } // init all function pointers int res = NeuromdBoard::prepare_session (); if (res != (int)BrainFlowExitCodes::STATUS_OK) { return res; } // try to find device res = find_device (); if (res != (int)BrainFlowExitCodes::STATUS_OK) { free_device (); return res; } // try to connect to device res = connect_device (); if (res != (int)BrainFlowExitCodes::STATUS_OK) { free_device (); return res; } // apply settings for EEG/ECG/EMG res = apply_initial_settings (); if (res != (int)BrainFlowExitCodes::STATUS_OK) { free_device (); return res; } ChannelInfoArray device_channels; int exit_code = device_available_channels (device, &device_channels); if (exit_code != SDK_NO_ERROR) { char error_msg[1024]; sdk_last_error_msg (error_msg, 1024); safe_logger (spdlog::level::err, "get channels error {}", error_msg); free_device (); return (int)BrainFlowExitCodes::GENERAL_ERROR; } for (size_t i = 0; i < device_channels.info_count; ++i) { if (device_channels.info_array[i].type == ChannelTypeSignal) { signal_channel = create_SignalDoubleChannel_info (device, device_channels.info_array[i]); } } free_ChannelInfoArray (device_channels); initialized = true; counter = 0; return (int)BrainFlowExitCodes::STATUS_OK; } int Callibri::config_board (std::string config, std::string &response) { if (device == NULL) { return (int)BrainFlowExitCodes::BOARD_NOT_CREATED_ERROR; } if (config.empty ()) { return (int)BrainFlowExitCodes::INVALID_ARGUMENTS_ERROR; } Command cmd = CommandStartSignal; bool parsed = false; if (strcmp (config.c_str (), "CommandStartSignal") == 0) { parsed = true; cmd = CommandStartSignal; } if (strcmp (config.c_str (), "CommandStopSignal") == 0) { parsed = true; cmd = CommandStopSignal; } if (!parsed) { safe_logger (spdlog::level::err, "Invalid value for config, Supported values: CommandStartSignal, CommandStopSignal"); return (int)BrainFlowExitCodes::INVALID_ARGUMENTS_ERROR; } int ec = device_execute (device, cmd); if (ec != SDK_NO_ERROR) { char error_msg[1024]; sdk_last_error_msg (error_msg, 1024); safe_logger (spdlog::level::err, error_msg); return (int)BrainFlowExitCodes::GENERAL_ERROR; } return (int)BrainFlowExitCodes::STATUS_OK; } int Callibri::start_stream (int buffer_size, const char *streamer_params) { if (is_streaming) { safe_logger (spdlog::level::err, "Streaming thread already running"); return (int)BrainFlowExitCodes::STREAM_ALREADY_RUN_ERROR; } int res = prepare_for_acquisition (buffer_size, streamer_params); if (res != (int)BrainFlowExitCodes::STATUS_OK) { return res; } std::string command_start = "CommandStartSignal"; std::string tmp = ""; res = config_board (command_start, tmp); if (res != (int)BrainFlowExitCodes::STATUS_OK) { return res; } keep_alive = true; streaming_thread = std::thread ([this] { this->read_thread (); }); is_streaming = true; return (int)BrainFlowExitCodes::STATUS_OK; } int Callibri::stop_stream () { if (is_streaming) { keep_alive = false; is_streaming = false; streaming_thread.join (); std::string command_stop = "CommandStopSignal"; std::string tmp = ""; int res = config_board (command_stop, tmp); return res; } else { return (int)BrainFlowExitCodes::STREAM_THREAD_IS_NOT_RUNNING; } } int Callibri::release_session () { if (initialized) { if (is_streaming) { stop_stream (); } free_packages (); initialized = false; free_channels (); } return NeuromdBoard::release_session (); } void Callibri::read_thread () { int num_rows = board_descr["num_rows"]; double *package = new double[num_rows]; for (int i = 0; i < num_rows; i++) { package[i] = 0.0; } while (keep_alive) { size_t length = 0; do { AnyChannel_get_total_length ((AnyChannel *)signal_channel, &length); } while ((keep_alive) && (length < (counter + 1))); // check that inner loop ended not because of stop_stream invocation if (!keep_alive) { break; } double timestamp = get_timestamp (); size_t stub = 0; double data = 0; int sdk_ec = SDK_NO_ERROR; sdk_ec = DoubleChannel_read_data ((DoubleChannel *)signal_channel, counter, 1, &data, 1, &stub); if (sdk_ec != SDK_NO_ERROR) { continue; } counter++; package[board_descr["package_num_channel"].get<int> ()] = (double)counter; package[1] = data * 1e6; // hardcode channel num here because there are 3 different types package[board_descr["timestamp_channel"].get<int> ()] = timestamp; push_package (package); } } void Callibri::free_channels () { if (signal_channel) { AnyChannel_delete ((AnyChannel *)signal_channel); signal_channel = NULL; } } //////////////////// // Stub for Linux // //////////////////// #else Callibri::Callibri (int board_id, struct BrainFlowInputParams params) : NeuromdBoard (board_id, params) { } Callibri::~Callibri () { } int Callibri::prepare_session () { safe_logger (spdlog::level::err, "Callibri doesnt support Linux."); return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR; } int Callibri::config_board (std::string config, std::string &response) { safe_logger (spdlog::level::err, "Callibri doesnt support Linux."); return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR; } int Callibri::release_session () { safe_logger (spdlog::level::err, "Callibri doesnt support Linux."); return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR; } int Callibri::stop_stream () { safe_logger (spdlog::level::err, "Callibri doesnt support Linux."); return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR; } int Callibri::start_stream (int buffer_size, const char *streamer_params) { safe_logger (spdlog::level::err, "Callibri doesnt support Linux."); return (int)BrainFlowExitCodes::UNSUPPORTED_BOARD_ERROR; } #endif
3,204
45,293
package test; import java.util.*; public class CustomProjectionKind { public List<Number> foo() { throw new UnsupportedOperationException(); } }
55
2,453
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12). // // Copyright (C) 1997-2019 <NAME>. // #import <DVTSourceControl/DVTSourceControlVisualLogItem.h> @interface DVTSourceControlVisualLogItem (IDEKit) - (id)pasteboardPropertyListForType:(id)arg1; - (id)writableTypesForPasteboard:(id)arg1; @end
127
956
/* SPDX-License-Identifier: BSD-3-Clause * Copyright (c) 2020 Arm Limited */ #ifndef _RTE_RCU_QSBR_PVT_H_ #define _RTE_RCU_QSBR_PVT_H_ /** * This file is private to the RCU library. It should not be included * by the user of this library. */ #ifdef __cplusplus extern "C" { #endif #include <rte_ring.h> #include <rte_ring_elem.h> #include "rte_rcu_qsbr.h" /* Defer queue structure. * This structure holds the defer queue. The defer queue is used to * hold the deleted entries from the data structure that are not * yet freed. */ struct rte_rcu_qsbr_dq { struct rte_rcu_qsbr *v; /**< RCU QSBR variable used by this queue.*/ struct rte_ring *r; /**< RCU QSBR defer queue. */ uint32_t size; /**< Number of elements in the defer queue */ uint32_t esize; /**< Size (in bytes) of data, including the token, stored on the * defer queue. */ uint32_t trigger_reclaim_limit; /**< Trigger automatic reclamation after the defer queue * has at least these many resources waiting. */ uint32_t max_reclaim_size; /**< Reclaim at the max these many resources during auto * reclamation. */ rte_rcu_qsbr_free_resource_t free_fn; /**< Function to call to free the resource. */ void *p; /**< Pointer passed to the free function. Typically, this is the * pointer to the data structure to which the resource to free * belongs. */ }; /* Internal structure to represent the element on the defer queue. * Use alias as a character array is type casted to a variable * of this structure type. */ typedef struct { uint64_t token; /**< Token */ uint8_t elem[0]; /**< Pointer to user element */ } __attribute__((__may_alias__)) __rte_rcu_qsbr_dq_elem_t; #ifdef __cplusplus } #endif #endif /* _RTE_RCU_QSBR_PVT_H_ */
633
370
/* ========================================================================== */ /* === umfpack_qsymbolic ==================================================== */ /* ========================================================================== */ /* -------------------------------------------------------------------------- */ /* Copyright (c) 2005-2012 by <NAME>, http://www.suitesparse.com. */ /* All Rights Reserved. See ../Doc/License.txt for License. */ /* -------------------------------------------------------------------------- */ int umfpack_di_qsymbolic ( int n_row, int n_col, const int Ap [ ], const int Ai [ ], const double Ax [ ], const int Qinit [ ], void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; SuiteSparse_long umfpack_dl_qsymbolic ( SuiteSparse_long n_row, SuiteSparse_long n_col, const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], const double Ax [ ], const SuiteSparse_long Qinit [ ], void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; int umfpack_zi_qsymbolic ( int n_row, int n_col, const int Ap [ ], const int Ai [ ], const double Ax [ ], const double Az [ ], const int Qinit [ ], void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; SuiteSparse_long umfpack_zl_qsymbolic ( SuiteSparse_long n_row, SuiteSparse_long n_col, const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], const double Ax [ ], const double Az [ ], const SuiteSparse_long Qinit [ ], void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; int umfpack_di_fsymbolic ( int n_row, int n_col, const int Ap [ ], const int Ai [ ], const double Ax [ ], int (*user_ordering) ( int, int, int, int *, int *, int *, void *, double *), void *user_params, void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; SuiteSparse_long umfpack_dl_fsymbolic ( SuiteSparse_long n_row, SuiteSparse_long n_col, const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], const double Ax [ ], int (*user_ordering) (SuiteSparse_long, SuiteSparse_long, SuiteSparse_long, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, void *, double *), void *user_params, void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; int umfpack_zi_fsymbolic ( int n_row, int n_col, const int Ap [ ], const int Ai [ ], const double Ax [ ], const double Az [ ], int (*user_ordering) (int, int, int, int *, int *, int *, void *, double *), void *user_params, void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; SuiteSparse_long umfpack_zl_fsymbolic ( SuiteSparse_long n_row, SuiteSparse_long n_col, const SuiteSparse_long Ap [ ], const SuiteSparse_long Ai [ ], const double Ax [ ], const double Az [ ], int (*user_ordering) (SuiteSparse_long, SuiteSparse_long, SuiteSparse_long, SuiteSparse_long *, SuiteSparse_long *, SuiteSparse_long *, void *, double *), void *user_params, void **Symbolic, const double Control [UMFPACK_CONTROL], double Info [UMFPACK_INFO] ) ; /* double int Syntax: #include "umfpack.h" void *Symbolic ; int n_row, n_col, *Ap, *Ai, *Qinit, status ; double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], *Ax ; status = umfpack_di_qsymbolic (n_row, n_col, Ap, Ai, Ax, Qinit, &Symbolic, Control, Info) ; double SuiteSparse_long Syntax: #include "umfpack.h" void *Symbolic ; SuiteSparse_long n_row, n_col, *Ap, *Ai, *Qinit, status ; double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], *Ax ; status = umfpack_dl_qsymbolic (n_row, n_col, Ap, Ai, Ax, Qinit, &Symbolic, Control, Info) ; complex int Syntax: #include "umfpack.h" void *Symbolic ; int n_row, n_col, *Ap, *Ai, *Qinit, status ; double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], *Ax, *Az ; status = umfpack_zi_qsymbolic (n_row, n_col, Ap, Ai, Ax, Az, Qinit, &Symbolic, Control, Info) ; complex SuiteSparse_long Syntax: #include "umfpack.h" void *Symbolic ; SuiteSparse_long n_row, n_col, *Ap, *Ai, *Qinit, status ; double Control [UMFPACK_CONTROL], Info [UMFPACK_INFO], *Ax, *Az ; status = umfpack_zl_qsymbolic (n_row, n_col, Ap, Ai, Ax, Az, Qinit, &Symbolic, Control, Info) ; packed complex Syntax: Same as above, except Az is NULL. Purpose: Given the nonzero pattern of a sparse matrix A in column-oriented form, and a sparsity preserving column pre-ordering Qinit, umfpack_*_qsymbolic performs the symbolic factorization of A*Qinit (or A (:,Qinit) in MATLAB notation). This is identical to umfpack_*_symbolic, except that neither COLAMD nor AMD are called and the user input column order Qinit is used instead. Note that in general, the Qinit passed to umfpack_*_qsymbolic can differ from the final Q found in umfpack_*_numeric. The unsymmetric strategy will perform a column etree postordering done in umfpack_*_qsymbolic and sparsity-preserving modifications are made within each frontal matrix during umfpack_*_numeric. The symmetric strategy will preserve Qinit, unless the matrix is structurally singular. See umfpack_*_symbolic for more information. Note that Ax and Ax are optional. The may be NULL. *** WARNING *** A poor choice of Qinit can easily cause umfpack_*_numeric to use a huge amount of memory and do a lot of work. The "default" symbolic analysis method is umfpack_*_symbolic, not this routine. If you use this routine, the performance of UMFPACK is your responsibility; UMFPACK will not try to second-guess a poor choice of Qinit. Returns: The value of Info [UMFPACK_STATUS]; see umfpack_*_symbolic. Also returns UMFPACK_ERROR_invalid_permuation if Qinit is not a valid permutation vector. Arguments: All arguments are the same as umfpack_*_symbolic, except for the following: Int Qinit [n_col] ; Input argument, not modified. The user's fill-reducing initial column pre-ordering. This must be a permutation of 0..n_col-1. If Qinit [k] = j, then column j is the kth column of the matrix A (:,Qinit) to be factorized. If Qinit is an (Int *) NULL pointer, then COLAMD or AMD are called instead. double Control [UMFPACK_CONTROL] ; Input argument, not modified. If Qinit is not NULL, then only two strategies are recognized: the unsymmetric strategy and the symmetric strategy. If Control [UMFPACK_STRATEGY] is UMFPACK_STRATEGY_SYMMETRIC, then the symmetric strategy is used. Otherwise the unsymmetric strategy is used. The umfpack_*_fsymbolic functions are identical to their umfpack_*_qsymbolic functions, except that Qinit is replaced with a pointer to an ordering function (user_ordering), and a pointer to an extra input that is passed to the user_ordering (user_params). The arguments have the following syntax: int (*user_ordering) // TRUE if OK, FALSE otherwise ( // inputs, not modified on output int, // nrow int, // ncol int, // sym: if TRUE and nrow==ncol do A+A', else do A'A int *, // Ap, size ncol+1 int *, // Ai, size nz // output int *, // size ncol, fill-reducing permutation // input/output void *, // user_params (ignored by UMFPACK) double * // user_info[0..2], optional output for symmetric case. // user_info[0]: max column count for L=chol(A+A') // user_info[1]: nnz (L) // user_info[2]: flop count for chol(A+A'), if A real ), void *user_params, // passed to user_ordering function */
3,122
1,125
// Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <xnnpack/packx.h> void xnn_x32_packx_ukernel_2x__scalar( size_t m, size_t k, const uint32_t* restrict x, size_t x_stride, uint32_t* restrict y) { assert(m != 0); assert(k != 0); const float* x0 = (const float*) x; const float* x1 = (const float*) ((uintptr_t) x0 + x_stride); if (m != 2) { x1 = x0; } float*restrict y_f32 = (float*) y; do { const float vx0 = *x0++; const float vx1 = *x1++; y_f32[0] = vx0; y_f32[1] = vx1; y_f32 += 2; } while (--k != 0); }
322
881
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. """ from django.test import TestCase from pipeline_web.plugin_management.models import DeprecatedPlugin class DeprecatedPluginTestCase(TestCase): def setUpClass(): DeprecatedPlugin.objects.create( code="bk_notify", version="legacy", type=DeprecatedPlugin.PLUGIN_TYPE_COMPONENT, phase=DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, ) DeprecatedPlugin.objects.create( code="bk_notify", version="v1.0", type=DeprecatedPlugin.PLUGIN_TYPE_COMPONENT, phase=DeprecatedPlugin.PLUGIN_PHASE_WILL_BE_DEPRECATED, ) DeprecatedPlugin.objects.create( code="bk_job", version="legacy", type=DeprecatedPlugin.PLUGIN_TYPE_COMPONENT, phase=DeprecatedPlugin.PLUGIN_PHASE_WILL_BE_DEPRECATED, ) DeprecatedPlugin.objects.create( code="ip", version="legacy", type=DeprecatedPlugin.PLUGIN_TYPE_VARIABLE, phase=DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, ) DeprecatedPlugin.objects.create( code="ip", version="v1.0", type=DeprecatedPlugin.PLUGIN_TYPE_VARIABLE, phase=DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, ) DeprecatedPlugin.objects.create( code="ip_selector", version="v1.0", type=DeprecatedPlugin.PLUGIN_TYPE_VARIABLE, phase=DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, ) def tearDownClass(): DeprecatedPlugin.objects.all().delete() def test_get_components_phase_dict(self): phase_dict = DeprecatedPlugin.objects.get_components_phase_dict() self.assertEqual( phase_dict, { "bk_notify": { "legacy": DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, "v1.0": DeprecatedPlugin.PLUGIN_PHASE_WILL_BE_DEPRECATED, }, "bk_job": {"legacy": DeprecatedPlugin.PLUGIN_PHASE_WILL_BE_DEPRECATED}, }, ) def test_get_variables_phase_dict(self): phase_dict = DeprecatedPlugin.objects.get_variables_phase_dict() self.assertEqual( phase_dict, { "ip": { "legacy": DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, "v1.0": DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED, }, "ip_selector": {"v1.0": DeprecatedPlugin.PLUGIN_PHASE_DEPRECATED}, }, )
1,553
325
<filename>feincms/urls.py # flake8: noqa from __future__ import absolute_import from feincms.views import Handler try: from django.urls import re_path except ImportError: from django.conf.urls import url as re_path handler = Handler.as_view() urlpatterns = [ re_path(r"^$", handler, name="feincms_home"), re_path(r"^(.*)/$", handler, name="feincms_handler"), ]
148