code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
package org.elsys.InternetProgramming; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class ServerHandler { private Socket socket; public ServerHandler(String serverHost, int serverPort) { try { this.socket = new Socket(serverHost, serverPort); } catch (IOException e) { e.printStackTrace(); } } public void sendDateToServer(String date) { try { final OutputStream outputStream = this.socket.getOutputStream(); final PrintWriter out = new PrintWriter(outputStream); out.println(date); out.flush(); } catch (IOException e) { e.printStackTrace(); } } public int getCountFromServer() { try { final InputStream inputStream = this.socket.getInputStream(); final InputStreamReader inputStreamReader = new InputStreamReader(inputStream); final BufferedReader reader = new BufferedReader(inputStreamReader); final String line = reader.readLine(); final int result = Integer.parseInt(line); return result; } catch (IOException e) { e.printStackTrace(); } return 0; } public void closeConnection() { try { this.socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
edudev/internet_programming
Homework2/workspace/DateFormatterClient/src/org/elsys/InternetProgramming/ServerHandler.java
Java
gpl-3.0
1,328
import sys, math from test import goertzel import wave import pyaudio import Queue import numpy as np if len(sys.argv) < 2: print "Usage: %s <filename> " % sys.argv[0] sys.exit(1) filename = sys.argv[1] w = wave.open(filename) fs = w.getframerate() width = w.getsampwidth() chunkDuration = .2 #.2 second chunks chunk = int(chunkDuration*fs) window = np.blackman(chunk) p = pyaudio.PyAudio() stream = p.open(format = p.get_format_from_width(w.getsampwidth()), channels = w.getnchannels(),rate = fs, output=True) #read .2 second chunk data = w.readframes(chunk) chunk_data = [] #find the frequencies of each chunk print "Running calculations on wav file" num = 0 while data != '': print "Calculating Chunk " + str(num) stream.write(data) indata = np.array(wave.struct.unpack("%dh"%(len(data)/width),\ data)) freqs , results = goertzel(indata,fs, (1036,1058), (1567,1569), (2082,2104)) chunk_data.append((freqs,results)) data = w.readframes(chunk) num+=.2 stream.close() p.terminate() #finished getting data from chunks, now to parse the data hi = [] lo = [] mid = [] #average first second of audio to get frequency baselines for i in range (5): a = chunk_data[i][0] b = chunk_data[i][1] for j in range(len(a)): if a[j] > 1700: hi.append(b[j]) elif a[j] < 1300: lo.append(b[j]) else: mid.append(b[j]) hi_average = sum(hi)/float(len(hi)) lo_average = sum(lo)/float(len(lo)) mid_average = sum(mid)/float(len(mid)) """ Determine the frequency in each .2 second chunk that has the highest amplitude increase from its average, then determine the frequency of that second of data by the median frequency of its 5 chunks """ #looks for start signal in last 3 seconds of audio def signal_found(arr): lst = arr[-15:] first = 0 second = 0 third = 0 for i in range(0,5): if lst[i]=="mid": first += 1 for i in range(5,10): if lst[i]=="mid": second += 1 for i in range(10,15): if lst[i]=="mid": third += 1 if first >= 5 and second >= 5 and third >= 5: return True else: return False #gets freq of 1 second of audio def get_freq(arr): lo_count = 0 hi_count = 0 mid_count = 0 for i in arr: if i=="lo": lo_count+=1 if i=="hi": hi_count+=1 if i=="mid": mid_count+=1 if mid_count > hi_count and mid_count > lo_count: return 2 if lo_count>hi_count: return 0 else: return 1 start = False freq_list = [] offset = 0 bits = [] for i in range(5,len(chunk_data)): a = chunk_data[i][0] b = chunk_data[i][1] hi_amp = [] lo_amp = [] mid_amp = [] #get averages for each freq for j in range(len(a)): if a[j] > 1700: hi_amp.append(b[j]) elif a[j] < 1300: lo_amp.append(b[j]) else: mid_amp.append(b[j]) hi_av = sum(hi_amp)/float(len(hi_amp)) lo_av = sum(lo_amp)/float(len(lo_amp)) mid_av = sum(mid_amp)/float(len(mid_amp)) #get freq of this chunk diff = [lo_av-lo_average,mid_av-mid_average,hi_av-hi_average] index = diff.index(max(diff)) if(index==0): freq_list.append("lo") if(index==1): freq_list.append("mid") if(index==2): freq_list.append("hi") print(freq_list[len(freq_list)-1]) if len(freq_list) > 5: if start: if len(freq_list)%5 == offset: bit = get_freq(freq_list[-5:]) if bit != 2: bits.append(bit) else: print "Stop Signal Detected" break elif len(freq_list) >= 15: if signal_found(freq_list): print "signal found" start = True offset = len(freq_list)%5 print bits
jloloew/AirBridge
parse.py
Python
gpl-3.0
3,509
// Decompiled with JetBrains decompiler // Type: StartupSceneAnimDriver // Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // MVID: 19851F1B-4780-4223-BA01-2C20F2CD781E // Assembly location: C:\Users\CGA Computer\Desktop\LEGO Universe Stuff\LOCO Server\Unity Web Player Extractor\Saved Files\LOCO Server.unity3d_unpacked\Assembly-CSharp.dll using System.Collections; using System.Diagnostics; using UnityEngine; public class StartupSceneAnimDriver : MonoBehaviour { public WBSpriteText LoadingString; public StartupSceneAnimDriver() { base.\u002Ector(); } [DebuggerHidden] private IEnumerator Start() { // ISSUE: object of a compiler-generated type is created return (IEnumerator) new StartupSceneAnimDriver.\u003CStart\u003Ec__Iterator95() { \u003C\u003Ef__this = this }; } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/Assembly-CSharp/StartupSceneAnimDriver.cs
C#
gpl-3.0
859
using System; using System.Collections.Generic; using System.Linq; using Minedrink_UWP.View; using Windows.ApplicationModel; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Navigation; using System.Diagnostics; using Windows.ApplicationModel.Core; using Windows.Networking; using Minedrink_UWP.Model; using Windows.Networking.Connectivity; using Windows.Networking.Sockets; using System.IO; using Windows.Storage.Streams; using System.Threading.Tasks; // https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x804 上介绍了“空白页”项模板 namespace Minedrink_UWP { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { public Rect TogglePaneButtonRect { get; private set; } private bool isPaddingAdd = false; private List<NavMenuItem> navlist = new List<NavMenuItem>( new[] { new NavMenuItem() { Symbol = Symbol.Globe, Label = "总览", DestPage = typeof(OverviewPage), }, new NavMenuItem() { Symbol = Symbol.Admin, Label = "配置", DestPage = typeof(ConfigPage), }, new NavMenuItem() { Symbol = Symbol.PhoneBook, Label = "监控", DestPage = typeof(MonitorPage), } }); public static MainPage Current = null; public MainPage() { this.InitializeComponent(); this.Loaded += (sender, args) => { Current = this; this.CheckTogglePaneButtonSizeChanged(); var titleBar = Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().TitleBar; titleBar.IsVisibleChanged += TitleBar_IsVisibleChanged; }; this.RootSplitView.RegisterPropertyChangedCallback(SplitView.DisplayModeProperty, (s, a) => { //确保当SplitView的显示模式改变时,更新TogglePaneButton的尺寸 this.CheckTogglePaneButtonSizeChanged(); }); SystemNavigationManager.GetForCurrentView().BackRequested += SyatemNavigationMaganger_BackRequested; SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; NavMenuList.ItemsSource = navlist; } private void SyatemNavigationMaganger_BackRequested(object sender, BackRequestedEventArgs e) { bool handle = e.Handled; this.BackRequested(ref handle); e.Handled = handle; } /// <summary> /// 处理返回按键 /// </summary> /// <param name="handle"></param> private void BackRequested(ref bool handle) { if (this.AppFrame == null) { return; } if (this.AppFrame.CanGoBack && !handle) { handle = true; this.AppFrame.GoBack(); } } /// <summary> /// 当窗口标题栏可见性改变时调用,例如Loading完成或进入平板模式, /// 确保标题栏和App内容间的top padding正确 /// Invoked when window title bar visibility changes, such as after loading or in tablet mode /// Ensures correct padding at window top, between title bar and app content /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void TitleBar_IsVisibleChanged(Windows.ApplicationModel.Core.CoreApplicationViewTitleBar sender, object args) { if (!this.isPaddingAdd && sender.IsVisible) { //在标题和内容间增加额外的Padding double extraPadding = (Double)App.Current.Resources["DesktopWindowTopPadding"]; this.isPaddingAdd = true; Thickness margin = NavMenuList.Margin; NavMenuList.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); margin = AppFrame.Margin; //AppFrame.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); margin = TogglePaneButton.Margin; TogglePaneButton.Margin = new Thickness(margin.Left, margin.Top + extraPadding, margin.Right, margin.Bottom); } } /// <summary> /// Check for the conditions where the navigation pane does not occupy the space under the floating /// hamburger button and trigger the event. /// </summary> private void CheckTogglePaneButtonSizeChanged() { if (RootSplitView.DisplayMode == SplitViewDisplayMode.Inline || RootSplitView.DisplayMode == SplitViewDisplayMode.Overlay) { var transform = this.TogglePaneButton.TransformToVisual(this); var rect = transform.TransformBounds(new Rect(0, 0, this.TogglePaneButton.ActualWidth, this.TogglePaneButton.ActualHeight)); this.TogglePaneButtonRect = rect; } else { this.TogglePaneButtonRect = new Rect(); } var handler = this.TogglePaneButtonRectChanged; if (handler != null) { // handler(this, this.TogglePaneButtonRect); handler.DynamicInvoke(this, this.TogglePaneButtonRect); } } //private void MainPage_Loaded(object sender, RoutedEventArgs e) //{ // throw new NotImplementedException(); //} public Frame AppFrame { get { return this.frame; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainPage_KeyDown(object sender, KeyRoutedEventArgs e) { FocusNavigationDirection direction = FocusNavigationDirection.None; switch (e.Key) { case Windows.System.VirtualKey.Left: case Windows.System.VirtualKey.GamepadDPadLeft: case Windows.System.VirtualKey.GamepadLeftThumbstickLeft: case Windows.System.VirtualKey.NavigationLeft: direction = FocusNavigationDirection.Left; break; case Windows.System.VirtualKey.Right: case Windows.System.VirtualKey.GamepadDPadRight: case Windows.System.VirtualKey.GamepadLeftThumbstickRight: case Windows.System.VirtualKey.NavigationRight: direction = FocusNavigationDirection.Right; break; case Windows.System.VirtualKey.Up: case Windows.System.VirtualKey.GamepadDPadUp: case Windows.System.VirtualKey.GamepadLeftThumbstickUp: case Windows.System.VirtualKey.NavigationUp: direction = FocusNavigationDirection.Up; break; case Windows.System.VirtualKey.Down: case Windows.System.VirtualKey.GamepadDPadDown: case Windows.System.VirtualKey.GamepadLeftThumbstickDown: case Windows.System.VirtualKey.NavigationDown: direction = FocusNavigationDirection.Down; break; } if (direction != FocusNavigationDirection.None) { var contorl = FocusManager.FindNextFocusableElement(direction) as Control; if (contorl != null) { contorl.Focus(FocusState.Keyboard); e.Handled = true; } } } /// <summary> /// Hides divider when nav pane is closed. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void RootSplitView_PaneClosed(SplitView sender, object args) { NavPaneDivider.Visibility = Visibility.Collapsed; // Prevent focus from moving to elements when they're not visible on screen FeedbackNavPaneButton.IsTabStop = false; SettingsNavPaneButton.IsTabStop = false; } /// <summary> ///通过使用每个项目的关联标签在每个容器上设置AutomationProperties.Name来启用每个导航菜单项上的辅助功能。 /// Enable accessibility on each nav menu item by setting the AutomationProperties.Name on each container /// using the associated Label of each item. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void NavMenuList_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args) { if (!args.InRecycleQueue && args.Item != null && args.Item is NavMenuItem) { args.ItemContainer.SetValue(AutomationProperties.NameProperty, ((NavMenuItem)args.Item).Label); } else { args.ItemContainer.ClearValue(AutomationProperties.NameProperty); } } /// <summary> /// 选中导航按钮项后调用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NavMenuList_ItemInvoked(object sender, ListViewItem e) { foreach (var i in navlist) { i.IsSelected = false; } var item = (NavMenuItem)((NavMenuListView)sender).ItemFromContainer(e); if (item != null) { item.IsSelected = true; if (item.DestPage != null && item.DestPage != this.AppFrame.CurrentSourcePageType) { this.AppFrame.Navigate(item.DestPage, item.Arguments); } } } public void NavMenuList_Init() { navlist.First().IsSelected = true; } /// <summary> /// Ensures the nav menu reflects reality when navigation is triggered outside of /// the nav menu buttons.确保导航菜单在导航按钮之外触发正确 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void frame_Navigating(object sender, NavigatingCancelEventArgs e) { //处理返回逻辑 if (e.NavigationMode == NavigationMode.Back) { var item = (from p in this.navlist where p.DestPage == e.SourcePageType select p).SingleOrDefault(); if (item == null && this.AppFrame.BackStackDepth > 0) { // 在页面进入到子页面的情况下,我们将返回到BackStack中最近的一级导航菜单项 // In cases where a page drills into sub-pages then we'll highlight the most recent // navigation menu item that appears in the BackStack foreach (var entry in this.AppFrame.BackStack.Reverse()) { item = (from p in this.navlist where p.DestPage == entry.SourcePageType select p).SingleOrDefault(); if (item != null) { break; } } } foreach (var i in navlist) { i.IsSelected = false; } if (item != null) { item.IsSelected = true; } var container = (ListViewItem)NavMenuList.ContainerFromItem(item); //当更新项目的选择状态时,它阻止它进行键盘焦点。 如果用户正在通过键盘调用后退按钮,导致所选择的导航菜单项目改变,则焦点将保留在后退按钮上。 //While updating the selection state of the item prevent it from taking keyboard focus. //If a user is invoking the back button via the keyboard causing the selected nav menu item to change then focus will remain on the back button. if (container != null) { container.IsTabStop = false; } NavMenuList.SetSelectedItem(container); if (container != null) { container.IsTabStop = true; } } } private void TogglePaneButton_Unchecked(object sender, RoutedEventArgs e) { this.CheckTogglePaneButtonSizeChanged(); } private void TogglePaneButton_Checked(object sender, RoutedEventArgs e) { NavPaneDivider.Visibility = Visibility.Visible; this.CheckTogglePaneButtonSizeChanged(); FeedbackNavPaneButton.IsTabStop = true; SettingsNavPaneButton.IsTabStop = true; } //private async void StartListener() //{ // //覆盖这里的监听器是安全的,因为它将被删除,一旦它的所有引用都消失了。 // //然而,在许多情况下,这是一个危险的模式,半随机地覆盖数据(每次用户点击按钮), // //所以我们在这里阻止它。 // if (CoreApplication.Properties.ContainsKey("listener")) // { // Debug.WriteLine("监听器已存在"); // return; // } // CoreApplication.Properties.Remove("serverAddress"); // CoreApplication.Properties.Remove("adapter"); // //LocalHostItem selectedLocalHost = null; // //selectedLocalHost = new LocalHostItem(NetworkInformation.GetHostNames().First()); // //Debug.WriteLine("建立地址:" + selectedLocalHost); // //用户选择了一个地址。 为演示目的,我们确保连接将使用相同的地址。 // //CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); // StreamSocketListener listener = new StreamSocketListener(); // listener.ConnectionReceived += Listener_ConnectionReceived; // //如果需要,调整监听器的控制选项,然后再进行绑定操作。这些选项将被自动应用到连接的StreamSockets, // //这些连接是由传入的连接引起的(即作为ConnectionReceived事件处理程序的参数传递的)。 // //参考StreamSocketListenerControl类'MSDN 有关控制选项的完整列表的文档。 // listener.Control.KeepAlive = false; // //保存Socket,以便随后使用 // CoreApplication.Properties.Add("listener", listener); // //开始监听操作 // try // { // await listener.BindServiceNameAsync("8080"); // Debug.WriteLine("Listening......"); // } // catch (Exception) // { // throw; // } //} //private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) //{ // //DataReader reader = new DataReader(args.Socket.InputStream); // //try // //{ // // while (true) // // { // // // Read first 4 bytes (length of the subsequent string). // // uint sizeFieldCount = await reader.LoadAsync(sizeof(uint)); // // if (sizeFieldCount != sizeof(uint)) // // { // // // The underlying socket was closed before we were able to read the whole data. // // return; // // } // // // Read the string. // // uint stringLength = reader.ReadUInt32(); // // uint actualStringLength = await reader.LoadAsync(stringLength); // // if (stringLength != actualStringLength) // // { // // // The underlying socket was closed before we were able to read the whole data. // // return; // // } // // } // //} // //catch (Exception exception) // //{ // //} // //从远程客户端读取信息 // Stream inStream = args.Socket.InputStream.AsStreamForRead(); // StreamReader reader = new StreamReader(inStream); // //将信息送回 // Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); // StreamWriter writer = new StreamWriter(outStream); // while (true) // { // string inStr = await reader.ReadLineAsync(); // string outStr = null; // Debug.WriteLine("IN:" + inStr); // if (inStr.StartsWith("#")) // { // string codeStr = inStr.Substring(0, 8); // CommCode code = CommHandle.StringConvertToEnum(codeStr); // switch (code) // { // case CommCode.TCPCONN: // outStr = TCPCOMMHandle(); // break; // case CommCode.AS: // break; // case CommCode.ERROR: // Debug.WriteLine("错误的指令:" + codeStr); // break; // default: // break; // } // } // //TODO:断开连接后会引发System.NullReferenceException // if (outStr != null) // { // await writer.WriteLineAsync(inStr); // await writer.FlushAsync(); // } // //await Task.Delay(100); // } //} /// <summary> /// An event to notify listeners when the hamburger button may occlude other content in the app. /// The custom "PageHeader" user control is using this. /// </summary> public event TypedEventHandler<MainPage, Rect> TogglePaneButtonRectChanged; /// <summary> /// Public method to allow pages to open SplitView's pane. /// Used for custom app shortcuts like navigating left from page's left-most item /// </summary> public void OpenNavePane() { TogglePaneButton.IsChecked = true; NavPaneDivider.Visibility = Visibility.Visible; } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // Save application state and stop any background activity deferral.Complete(); } private string TCPCOMMHandle() { string result = "#TCPOK**"; return result; } } public enum NotifyType { StatusMessage, ErrorMessage }; //private void UpdateStatus(string strMessage, NotifyType type) //{ // switch (type) // { // case NotifyType.StatusMessage: // StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green); // break; // case NotifyType.ErrorMessage: // StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red); // break; // } // StatusBlock.Text = strMessage; // // Collapse the StatusBlock if it has no text to conserve real estate. // StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed; // if (StatusBlock.Text != String.Empty) // { // StatusBorder.Visibility = Visibility.Visible; // StatusPanel.Visibility = Visibility.Visible; // } // else // { // StatusBorder.Visibility = Visibility.Collapsed; // StatusPanel.Visibility = Visibility.Collapsed; // } //} }
SongOfSaya/Minedrink
Minedrink_UWP/Minedrink_UWP/MainPage.xaml.cs
C#
gpl-3.0
21,385
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for C++ expressions. // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/TemplateDeduction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/TypeLoc.h" #include "clang/Basic/PartialDiagnostic.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/STLExtras.h" using namespace clang; using namespace sema; ParsedType Sema::getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectTypePtr, bool EnteringContext) { // Determine where to perform name lookup. // FIXME: This area of the standard is very messy, and the current // wording is rather unclear about which scopes we search for the // destructor name; see core issues 399 and 555. Issue 399 in // particular shows where the current description of destructor name // lookup is completely out of line with existing practice, e.g., // this appears to be ill-formed: // // namespace N { // template <typename T> struct S { // ~S(); // }; // } // // void f(N::S<int>* s) { // s->N::S<int>::~S(); // } // // See also PR6358 and PR6359. // For this reason, we're currently only doing the C++03 version of this // code; the C++0x version has to wait until we get a proper spec. QualType SearchType; DeclContext *LookupCtx = 0; bool isDependent = false; bool LookInScope = false; // If we have an object type, it's because we are in a // pseudo-destructor-expression or a member access expression, and // we know what type we're looking for. if (ObjectTypePtr) SearchType = GetTypeFromParser(ObjectTypePtr); if (SS.isSet()) { NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); bool AlreadySearched = false; bool LookAtPrefix = true; // C++ [basic.lookup.qual]p6: // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, // the type-names are looked up as types in the scope designated by the // nested-name-specifier. In a qualified-id of the form: // // ::[opt] nested-name-specifier ̃ class-name // // where the nested-name-specifier designates a namespace scope, and in // a qualified-id of the form: // // ::opt nested-name-specifier class-name :: ̃ class-name // // the class-names are looked up as types in the scope designated by // the nested-name-specifier. // // Here, we check the first case (completely) and determine whether the // code below is permitted to look at the prefix of the // nested-name-specifier. DeclContext *DC = computeDeclContext(SS, EnteringContext); if (DC && DC->isFileContext()) { AlreadySearched = true; LookupCtx = DC; isDependent = false; } else if (DC && isa<CXXRecordDecl>(DC)) LookAtPrefix = false; // The second case from the C++03 rules quoted further above. NestedNameSpecifier *Prefix = 0; if (AlreadySearched) { // Nothing left to do. } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { CXXScopeSpec PrefixSS; PrefixSS.setScopeRep(Prefix); LookupCtx = computeDeclContext(PrefixSS, EnteringContext); isDependent = isDependentScopeSpecifier(PrefixSS); } else if (ObjectTypePtr) { LookupCtx = computeDeclContext(SearchType); isDependent = SearchType->isDependentType(); } else { LookupCtx = computeDeclContext(SS, EnteringContext); isDependent = LookupCtx && LookupCtx->isDependentContext(); } LookInScope = false; } else if (ObjectTypePtr) { // C++ [basic.lookup.classref]p3: // If the unqualified-id is ~type-name, the type-name is looked up // in the context of the entire postfix-expression. If the type T // of the object expression is of a class type C, the type-name is // also looked up in the scope of class C. At least one of the // lookups shall find a name that refers to (possibly // cv-qualified) T. LookupCtx = computeDeclContext(SearchType); isDependent = SearchType->isDependentType(); assert((isDependent || !SearchType->isIncompleteType()) && "Caller should have completed object type"); LookInScope = true; } else { // Perform lookup into the current scope (only). LookInScope = true; } LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); for (unsigned Step = 0; Step != 2; ++Step) { // Look for the name first in the computed lookup context (if we // have one) and, if that fails to find a match, in the sope (if // we're allowed to look there). Found.clear(); if (Step == 0 && LookupCtx) LookupQualifiedName(Found, LookupCtx); else if (Step == 1 && LookInScope && S) LookupName(Found, S); else continue; // FIXME: Should we be suppressing ambiguities here? if (Found.isAmbiguous()) return ParsedType(); if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { QualType T = Context.getTypeDeclType(Type); if (SearchType.isNull() || SearchType->isDependentType() || Context.hasSameUnqualifiedType(T, SearchType)) { // We found our type! return ParsedType::make(T); } } // If the name that we found is a class template name, and it is // the same name as the template name in the last part of the // nested-name-specifier (if present) or the object type, then // this is the destructor for that class. // FIXME: This is a workaround until we get real drafting for core // issue 399, for which there isn't even an obvious direction. if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { QualType MemberOfType; if (SS.isSet()) { if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { // Figure out the type of the context, if it has one. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) MemberOfType = Context.getTypeDeclType(Record); } } if (MemberOfType.isNull()) MemberOfType = SearchType; if (MemberOfType.isNull()) continue; // We're referring into a class template specialization. If the // class template we found is the same as the template being // specialized, we found what we are looking for. if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { if (Spec->getSpecializedTemplate()->getCanonicalDecl() == Template->getCanonicalDecl()) return ParsedType::make(MemberOfType); } continue; } // We're referring to an unresolved class template // specialization. Determine whether we class template we found // is the same as the template being specialized or, if we don't // know which template is being specialized, that it at least // has the same name. if (const TemplateSpecializationType *SpecType = MemberOfType->getAs<TemplateSpecializationType>()) { TemplateName SpecName = SpecType->getTemplateName(); // The class template we found is the same template being // specialized. if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) return ParsedType::make(MemberOfType); continue; } // The class template we found has the same name as the // (dependent) template name being specialized. if (DependentTemplateName *DepTemplate = SpecName.getAsDependentTemplateName()) { if (DepTemplate->isIdentifier() && DepTemplate->getIdentifier() == Template->getIdentifier()) return ParsedType::make(MemberOfType); continue; } } } } if (isDependent) { // We didn't find our type, but that's okay: it's dependent // anyway. NestedNameSpecifier *NNS = 0; SourceRange Range; if (SS.isSet()) { NNS = (NestedNameSpecifier *)SS.getScopeRep(); Range = SourceRange(SS.getRange().getBegin(), NameLoc); } else { NNS = NestedNameSpecifier::Create(Context, &II); Range = SourceRange(NameLoc); } QualType T = CheckTypenameType(ETK_None, NNS, II, SourceLocation(), Range, NameLoc); return ParsedType::make(T); } if (ObjectTypePtr) Diag(NameLoc, diag::err_ident_in_pseudo_dtor_not_a_type) << &II; else Diag(NameLoc, diag::err_destructor_class_name); return ParsedType(); } /// \brief Build a C++ typeid expression with a type operand. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc) { // C++ [expr.typeid]p4: // The top-level cv-qualifiers of the lvalue expression or the type-id // that is the operand of typeid are always ignored. // If the type of the type-id is a class type or a reference to a class // type, the class shall be completely-defined. Qualifiers Quals; QualType T = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), Quals); if (T->getAs<RecordType>() && RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) return ExprError(); return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, SourceRange(TypeidLoc, RParenLoc))); } /// \brief Build a C++ typeid expression with an expression operand. ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *E, SourceLocation RParenLoc) { bool isUnevaluatedOperand = true; if (E && !E->isTypeDependent()) { QualType T = E->getType(); if (const RecordType *RecordT = T->getAs<RecordType>()) { CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); // C++ [expr.typeid]p3: // [...] If the type of the expression is a class type, the class // shall be completely-defined. if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) return ExprError(); // C++ [expr.typeid]p3: // When typeid is applied to an expression other than an glvalue of a // polymorphic class type [...] [the] expression is an unevaluated // operand. [...] if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) { isUnevaluatedOperand = false; // We require a vtable to query the type at run time. MarkVTableUsed(TypeidLoc, RecordD); } } // C++ [expr.typeid]p4: // [...] If the type of the type-id is a reference to a possibly // cv-qualified type, the result of the typeid expression refers to a // std::type_info object representing the cv-unqualified referenced // type. Qualifiers Quals; QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); if (!Context.hasSameType(T, UnqualT)) { T = UnqualT; ImpCastExprToType(E, UnqualT, CK_NoOp, CastCategory(E)); } } // If this is an unevaluated operand, clear out the set of // declaration references we have been computing and eliminate any // temporaries introduced in its computation. if (isUnevaluatedOperand) ExprEvalContexts.back().Context = Unevaluated; return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, SourceRange(TypeidLoc, RParenLoc))); } /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); ExprResult Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc) { // Find the std::type_info type. if (!StdNamespace) return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); LookupQualifiedName(R, getStdNamespace()); RecordDecl *TypeInfoRecordDecl = R.getAsSingle<RecordDecl>(); if (!TypeInfoRecordDecl) return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl); if (isType) { // The operand is a type; handle it as such. TypeSourceInfo *TInfo = 0; QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), &TInfo); if (T.isNull()) return ExprError(); if (!TInfo) TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); } // The operand is an expression. return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); } /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { assert((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"); return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc)); } /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); } /// ActOnCXXThrow - Parse throw expressions. ExprResult Sema::ActOnCXXThrow(SourceLocation OpLoc, Expr *Ex) { if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex)) return ExprError(); return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc)); } /// CheckCXXThrowOperand - Validate the operand of a throw. bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) { // C++ [except.throw]p3: // A throw-expression initializes a temporary object, called the exception // object, the type of which is determined by removing any top-level // cv-qualifiers from the static type of the operand of throw and adjusting // the type from "array of T" or "function returning T" to "pointer to T" // or "pointer to function returning T", [...] if (E->getType().hasQualifiers()) ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp, CastCategory(E)); DefaultFunctionArrayConversion(E); // If the type of the exception would be an incomplete type or a pointer // to an incomplete type other than (cv) void the program is ill-formed. QualType Ty = E->getType(); bool isPointer = false; if (const PointerType* Ptr = Ty->getAs<PointerType>()) { Ty = Ptr->getPointeeType(); isPointer = true; } if (!isPointer || !Ty->isVoidType()) { if (RequireCompleteType(ThrowLoc, Ty, PDiag(isPointer ? diag::err_throw_incomplete_ptr : diag::err_throw_incomplete) << E->getSourceRange())) return true; if (RequireNonAbstractType(ThrowLoc, E->getType(), PDiag(diag::err_throw_abstract_type) << E->getSourceRange())) return true; } // Initialize the exception result. This implicitly weeds out // abstract types or types with inaccessible copy constructors. // FIXME: Determine whether we can elide this copy per C++0x [class.copy]p34. InitializedEntity Entity = InitializedEntity::InitializeException(ThrowLoc, E->getType(), /*NRVO=*/false); ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(), Owned(E)); if (Res.isInvalid()) return true; E = Res.takeAs<Expr>(); // If the exception has class type, we need additional handling. const RecordType *RecordTy = Ty->getAs<RecordType>(); if (!RecordTy) return false; CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); // If we are throwing a polymorphic class type or pointer thereof, // exception handling will make use of the vtable. MarkVTableUsed(ThrowLoc, RD); // If the class has a non-trivial destructor, we must be able to call it. if (RD->hasTrivialDestructor()) return false; CXXDestructorDecl *Destructor = const_cast<CXXDestructorDecl*>(LookupDestructor(RD)); if (!Destructor) return false; MarkDeclarationReferenced(E->getExprLoc(), Destructor); CheckDestructorAccess(E->getExprLoc(), Destructor, PDiag(diag::err_access_dtor_exception) << Ty); return false; } ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) { /// C++ 9.3.2: In the body of a non-static member function, the keyword this /// is a non-lvalue expression whose value is the address of the object for /// which the function is called. DeclContext *DC = getFunctionLevelDeclContext(); if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) if (MD->isInstance()) return Owned(new (Context) CXXThisExpr(ThisLoc, MD->getThisType(Context), /*isImplicit=*/false)); return ExprError(Diag(ThisLoc, diag::err_invalid_this_use)); } /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, ParsedType TypeRep, SourceLocation LParenLoc, MultiExprArg exprs, SourceLocation *CommaLocs, SourceLocation RParenLoc) { if (!TypeRep) return ExprError(); TypeSourceInfo *TInfo; QualType Ty = GetTypeFromParser(TypeRep, &TInfo); if (!TInfo) TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); unsigned NumExprs = exprs.size(); Expr **Exprs = (Expr**)exprs.get(); SourceLocation TyBeginLoc = TypeRange.getBegin(); SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc); if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) { exprs.release(); return Owned(CXXUnresolvedConstructExpr::Create(Context, TypeRange.getBegin(), Ty, LParenLoc, Exprs, NumExprs, RParenLoc)); } if (Ty->isArrayType()) return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange); if (!Ty->isVoidType() && RequireCompleteType(TyBeginLoc, Ty, PDiag(diag::err_invalid_incomplete_type_use) << FullRange)) return ExprError(); if (RequireNonAbstractType(TyBeginLoc, Ty, diag::err_allocation_of_abstract_type)) return ExprError(); // C++ [expr.type.conv]p1: // If the expression list is a single expression, the type conversion // expression is equivalent (in definedness, and if defined in meaning) to the // corresponding cast expression. // if (NumExprs == 1) { CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, BasePath, /*FunctionalStyle=*/true)) return ExprError(); exprs.release(); return Owned(CXXFunctionalCastExpr::Create(Context, Ty.getNonLValueExprType(Context), TInfo, TyBeginLoc, Kind, Exprs[0], &BasePath, RParenLoc)); } if (Ty->isRecordType()) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty); InitializationKind Kind = NumExprs ? InitializationKind::CreateDirect(TypeRange.getBegin(), LParenLoc, RParenLoc) : InitializationKind::CreateValue(TypeRange.getBegin(), LParenLoc, RParenLoc); InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs); ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs)); // FIXME: Improve AST representation? return move(Result); } // C++ [expr.type.conv]p1: // If the expression list specifies more than a single value, the type shall // be a class with a suitably declared constructor. // if (NumExprs > 1) return ExprError(Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg) << FullRange); assert(NumExprs == 0 && "Expected 0 expressions"); // C++ [expr.type.conv]p2: // The expression T(), where T is a simple-type-specifier for a non-array // complete object type or the (possibly cv-qualified) void type, creates an // rvalue of the specified type, which is value-initialized. // exprs.release(); return Owned(new (Context) CXXScalarValueInitExpr(Ty, TyBeginLoc, RParenLoc)); } /// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.: /// @code new (memory) int[size][4] @endcode /// or /// @code ::new Foo(23, "hello") @endcode /// For the interpretation of this heap of arguments, consult the base version. ExprResult Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { Expr *ArraySize = 0; // If the specified type is an array, unwrap it and save the expression. if (D.getNumTypeObjects() > 0 && D.getTypeObject(0).Kind == DeclaratorChunk::Array) { DeclaratorChunk &Chunk = D.getTypeObject(0); if (Chunk.Arr.hasStatic) return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) << D.getSourceRange()); if (!Chunk.Arr.NumElts) return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) << D.getSourceRange()); ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); D.DropFirstTypeObject(); } // Every dimension shall be of constant size. if (ArraySize) { for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) break; DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; if (Expr *NumElts = (Expr *)Array.NumElts) { if (!NumElts->isTypeDependent() && !NumElts->isValueDependent() && !NumElts->isIntegerConstantExpr(Context)) { Diag(D.getTypeObject(I).Loc, diag::err_new_array_nonconst) << NumElts->getSourceRange(); return ExprError(); } } } } //FIXME: Store TypeSourceInfo in CXXNew expression. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0); QualType AllocType = TInfo->getType(); if (D.isInvalidType()) return ExprError(); SourceRange R = TInfo->getTypeLoc().getSourceRange(); return BuildCXXNew(StartLoc, UseGlobal, PlacementLParen, move(PlacementArgs), PlacementRParen, TypeIdParens, AllocType, D.getSourceRange().getBegin(), R, ArraySize, ConstructorLParen, move(ConstructorArgs), ConstructorRParen); } ExprResult Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, SourceLocation TypeLoc, SourceRange TypeRange, Expr *ArraySize, SourceLocation ConstructorLParen, MultiExprArg ConstructorArgs, SourceLocation ConstructorRParen) { if (CheckAllocatedType(AllocType, TypeLoc, TypeRange)) return ExprError(); // Per C++0x [expr.new]p5, the type being constructed may be a // typedef of an array type. if (!ArraySize) { if (const ConstantArrayType *Array = Context.getAsConstantArrayType(AllocType)) { ArraySize = IntegerLiteral::Create(Context, Array->getSize(), Context.getSizeType(), TypeRange.getEnd()); AllocType = Array->getElementType(); } } QualType ResultType = Context.getPointerType(AllocType); // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral // or enumeration type with a non-negative value." if (ArraySize && !ArraySize->isTypeDependent()) { QualType SizeType = ArraySize->getType(); ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, PDiag(diag::err_array_size_not_integral), PDiag(diag::err_array_size_incomplete_type) << ArraySize->getSourceRange(), PDiag(diag::err_array_size_explicit_conversion), PDiag(diag::note_array_size_conversion), PDiag(diag::err_array_size_ambiguous_conversion), PDiag(diag::note_array_size_conversion), PDiag(getLangOptions().CPlusPlus0x? 0 : diag::ext_array_size_conversion)); if (ConvertedSize.isInvalid()) return ExprError(); ArraySize = ConvertedSize.take(); SizeType = ArraySize->getType(); if (!SizeType->isIntegralOrEnumerationType()) return ExprError(); // Let's see if this is a constant < 0. If so, we reject it out of hand. // We don't care about special rules, so we tell the machinery it's not // evaluated - it gives us a result in more cases. if (!ArraySize->isValueDependent()) { llvm::APSInt Value; if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) { if (Value < llvm::APSInt( llvm::APInt::getNullValue(Value.getBitWidth()), Value.isUnsigned())) return ExprError(Diag(ArraySize->getSourceRange().getBegin(), diag::err_typecheck_negative_array_size) << ArraySize->getSourceRange()); if (!AllocType->isDependentType()) { unsigned ActiveSizeBits = ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { Diag(ArraySize->getSourceRange().getBegin(), diag::err_array_too_large) << Value.toString(10) << ArraySize->getSourceRange(); return ExprError(); } } } else if (TypeIdParens.isValid()) { // Can't have dynamic array size when the type-id is in parentheses. Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst) << ArraySize->getSourceRange() << FixItHint::CreateRemoval(TypeIdParens.getBegin()) << FixItHint::CreateRemoval(TypeIdParens.getEnd()); TypeIdParens = SourceRange(); } } ImpCastExprToType(ArraySize, Context.getSizeType(), CK_IntegralCast); } FunctionDecl *OperatorNew = 0; FunctionDecl *OperatorDelete = 0; Expr **PlaceArgs = (Expr**)PlacementArgs.get(); unsigned NumPlaceArgs = PlacementArgs.size(); if (!AllocType->isDependentType() && !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) && FindAllocationFunctions(StartLoc, SourceRange(PlacementLParen, PlacementRParen), UseGlobal, AllocType, ArraySize, PlaceArgs, NumPlaceArgs, OperatorNew, OperatorDelete)) return ExprError(); llvm::SmallVector<Expr *, 8> AllPlaceArgs; if (OperatorNew) { // Add default arguments, if any. const FunctionProtoType *Proto = OperatorNew->getType()->getAs<FunctionProtoType>(); VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply; if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1, PlaceArgs, NumPlaceArgs, AllPlaceArgs, CallType)) return ExprError(); NumPlaceArgs = AllPlaceArgs.size(); if (NumPlaceArgs > 0) PlaceArgs = &AllPlaceArgs[0]; } bool Init = ConstructorLParen.isValid(); // --- Choosing a constructor --- CXXConstructorDecl *Constructor = 0; Expr **ConsArgs = (Expr**)ConstructorArgs.get(); unsigned NumConsArgs = ConstructorArgs.size(); ASTOwningVector<Expr*> ConvertedConstructorArgs(*this); // Array 'new' can't have any initializers. if (NumConsArgs && (ResultType->isArrayType() || ArraySize)) { SourceRange InitRange(ConsArgs[0]->getLocStart(), ConsArgs[NumConsArgs - 1]->getLocEnd()); Diag(StartLoc, diag::err_new_array_init_args) << InitRange; return ExprError(); } if (!AllocType->isDependentType() && !Expr::hasAnyTypeDependentArguments(ConsArgs, NumConsArgs)) { // C++0x [expr.new]p15: // A new-expression that creates an object of type T initializes that // object as follows: InitializationKind Kind // - If the new-initializer is omitted, the object is default- // initialized (8.5); if no initialization is performed, // the object has indeterminate value = !Init? InitializationKind::CreateDefault(TypeLoc) // - Otherwise, the new-initializer is interpreted according to the // initialization rules of 8.5 for direct-initialization. : InitializationKind::CreateDirect(TypeLoc, ConstructorLParen, ConstructorRParen); InitializedEntity Entity = InitializedEntity::InitializeNew(StartLoc, AllocType); InitializationSequence InitSeq(*this, Entity, Kind, ConsArgs, NumConsArgs); ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, move(ConstructorArgs)); if (FullInit.isInvalid()) return ExprError(); // FullInit is our initializer; walk through it to determine if it's a // constructor call, which CXXNewExpr handles directly. if (Expr *FullInitExpr = (Expr *)FullInit.get()) { if (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(FullInitExpr)) FullInitExpr = Binder->getSubExpr(); if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(FullInitExpr)) { Constructor = Construct->getConstructor(); for (CXXConstructExpr::arg_iterator A = Construct->arg_begin(), AEnd = Construct->arg_end(); A != AEnd; ++A) ConvertedConstructorArgs.push_back(A->Retain()); } else { // Take the converted initializer. ConvertedConstructorArgs.push_back(FullInit.release()); } } else { // No initialization required. } // Take the converted arguments and use them for the new expression. NumConsArgs = ConvertedConstructorArgs.size(); ConsArgs = (Expr **)ConvertedConstructorArgs.take(); } // Mark the new and delete operators as referenced. if (OperatorNew) MarkDeclarationReferenced(StartLoc, OperatorNew); if (OperatorDelete) MarkDeclarationReferenced(StartLoc, OperatorDelete); // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16) PlacementArgs.release(); ConstructorArgs.release(); // FIXME: The TypeSourceInfo should also be included in CXXNewExpr. return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs, TypeIdParens, ArraySize, Constructor, Init, ConsArgs, NumConsArgs, OperatorDelete, ResultType, StartLoc, Init ? ConstructorRParen : TypeRange.getEnd())); } /// CheckAllocatedType - Checks that a type is suitable as the allocated type /// in a new-expression. /// dimension off and stores the size expression in ArraySize. bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R) { // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an // abstract class type or array thereof. if (AllocType->isFunctionType()) return Diag(Loc, diag::err_bad_new_type) << AllocType << 0 << R; else if (AllocType->isReferenceType()) return Diag(Loc, diag::err_bad_new_type) << AllocType << 1 << R; else if (!AllocType->isDependentType() && RequireCompleteType(Loc, AllocType, PDiag(diag::err_new_incomplete_type) << R)) return true; else if (RequireNonAbstractType(Loc, AllocType, diag::err_allocation_of_abstract_type)) return true; return false; } /// \brief Determine whether the given function is a non-placement /// deallocation function. static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) { if (FD->isInvalidDecl()) return false; if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) return Method->isUsualDeallocationFunction(); return ((FD->getOverloadedOperator() == OO_Delete || FD->getOverloadedOperator() == OO_Array_Delete) && FD->getNumParams() == 1); } /// FindAllocationFunctions - Finds the overloads of operator new and delete /// that are appropriate for the allocation. bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, bool UseGlobal, QualType AllocType, bool IsArray, Expr **PlaceArgs, unsigned NumPlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete) { // --- Choosing an allocation function --- // C++ 5.3.4p8 - 14 & 18 // 1) If UseGlobal is true, only look in the global scope. Else, also look // in the scope of the allocated class. // 2) If an array size is given, look for operator new[], else look for // operator new. // 3) The first argument is always size_t. Append the arguments from the // placement form. llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs); // We don't care about the actual value of this argument. // FIXME: Should the Sema create the expression and embed it in the syntax // tree? Or should the consumer just recalculate the value? IntegerLiteral Size(Context, llvm::APInt::getNullValue( Context.Target.getPointerWidth(0)), Context.getSizeType(), SourceLocation()); AllocArgs[0] = &Size; std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1); // C++ [expr.new]p8: // If the allocated type is a non-array type, the allocation // function’s name is operator new and the deallocation function’s // name is operator delete. If the allocated type is an array // type, the allocation function’s name is operator new[] and the // deallocation function’s name is operator delete[]. DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_New : OO_New); DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( IsArray ? OO_Array_Delete : OO_Delete); QualType AllocElemType = Context.getBaseElementType(AllocType); if (AllocElemType->isRecordType() && !UseGlobal) { CXXRecordDecl *Record = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), Record, /*AllowMissing=*/true, OperatorNew)) return true; } if (!OperatorNew) { // Didn't find a member overload. Look for a global one. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0], AllocArgs.size(), TUDecl, /*AllowMissing=*/false, OperatorNew)) return true; } // We don't need an operator delete if we're running under // -fno-exceptions. if (!getLangOptions().Exceptions) { OperatorDelete = 0; return false; } // FindAllocationOverload can change the passed in arguments, so we need to // copy them back. if (NumPlaceArgs > 0) std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs); // C++ [expr.new]p19: // // If the new-expression begins with a unary :: operator, the // deallocation function’s name is looked up in the global // scope. Otherwise, if the allocated type is a class type T or an // array thereof, the deallocation function’s name is looked up in // the scope of T. If this lookup fails to find the name, or if // the allocated type is not a class type or array thereof, the // deallocation function’s name is looked up in the global scope. LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); if (AllocElemType->isRecordType() && !UseGlobal) { CXXRecordDecl *RD = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl()); LookupQualifiedName(FoundDelete, RD); } if (FoundDelete.isAmbiguous()) return true; // FIXME: clean up expressions? if (FoundDelete.empty()) { DeclareGlobalNewDelete(); LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); } FoundDelete.suppressDiagnostics(); llvm::SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; if (NumPlaceArgs > 0) { // C++ [expr.new]p20: // A declaration of a placement deallocation function matches the // declaration of a placement allocation function if it has the // same number of parameters and, after parameter transformations // (8.3.5), all parameter types except the first are // identical. [...] // // To perform this comparison, we compute the function type that // the deallocation function should have, and use that type both // for template argument deduction and for comparison purposes. QualType ExpectedFunctionType; { const FunctionProtoType *Proto = OperatorNew->getType()->getAs<FunctionProtoType>(); llvm::SmallVector<QualType, 4> ArgTypes; ArgTypes.push_back(Context.VoidPtrTy); for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I) ArgTypes.push_back(Proto->getArgType(I)); ExpectedFunctionType = Context.getFunctionType(Context.VoidTy, ArgTypes.data(), ArgTypes.size(), Proto->isVariadic(), 0, false, false, 0, 0, FunctionType::ExtInfo()); } for (LookupResult::iterator D = FoundDelete.begin(), DEnd = FoundDelete.end(); D != DEnd; ++D) { FunctionDecl *Fn = 0; if (FunctionTemplateDecl *FnTmpl = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { // Perform template argument deduction to try to match the // expected function type. TemplateDeductionInfo Info(Context, StartLoc); if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info)) continue; } else Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); if (Context.hasSameType(Fn->getType(), ExpectedFunctionType)) Matches.push_back(std::make_pair(D.getPair(), Fn)); } } else { // C++ [expr.new]p20: // [...] Any non-placement deallocation function matches a // non-placement allocation function. [...] for (LookupResult::iterator D = FoundDelete.begin(), DEnd = FoundDelete.end(); D != DEnd; ++D) { if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl())) if (isNonPlacementDeallocationFunction(Fn)) Matches.push_back(std::make_pair(D.getPair(), Fn)); } } // C++ [expr.new]p20: // [...] If the lookup finds a single matching deallocation // function, that function will be called; otherwise, no // deallocation function will be called. if (Matches.size() == 1) { OperatorDelete = Matches[0].second; // C++0x [expr.new]p20: // If the lookup finds the two-parameter form of a usual // deallocation function (3.7.4.2) and that function, considered // as a placement deallocation function, would have been // selected as a match for the allocation function, the program // is ill-formed. if (NumPlaceArgs && getLangOptions().CPlusPlus0x && isNonPlacementDeallocationFunction(OperatorDelete)) { Diag(StartLoc, diag::err_placement_new_non_placement_delete) << SourceRange(PlaceArgs[0]->getLocStart(), PlaceArgs[NumPlaceArgs - 1]->getLocEnd()); Diag(OperatorDelete->getLocation(), diag::note_previous_decl) << DeleteName; } else { CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), Matches[0].first); } } return false; } /// FindAllocationOverload - Find an fitting overload for the allocation /// function in the specified scope. bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, DeclarationName Name, Expr** Args, unsigned NumArgs, DeclContext *Ctx, bool AllowMissing, FunctionDecl *&Operator) { LookupResult R(*this, Name, StartLoc, LookupOrdinaryName); LookupQualifiedName(R, Ctx); if (R.empty()) { if (AllowMissing) return false; return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; } if (R.isAmbiguous()) return true; R.suppressDiagnostics(); OverloadCandidateSet Candidates(StartLoc); for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); Alloc != AllocEnd; ++Alloc) { // Even member operator new/delete are implicitly treated as // static, so don't use AddMemberCandidate. NamedDecl *D = (*Alloc)->getUnderlyingDecl(); if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), /*ExplicitTemplateArgs=*/0, Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); continue; } FunctionDecl *Fn = cast<FunctionDecl>(D); AddOverloadCandidate(Fn, Alloc.getPair(), Args, NumArgs, Candidates, /*SuppressUserConversions=*/false); } // Do the resolution. OverloadCandidateSet::iterator Best; switch (Candidates.BestViableFunction(*this, StartLoc, Best)) { case OR_Success: { // Got one! FunctionDecl *FnDecl = Best->Function; // The first argument is size_t, and the first parameter must be size_t, // too. This is checked on declaration and can be assumed. (It can't be // asserted on, though, since invalid decls are left in there.) // Watch out for variadic allocator function. unsigned NumArgsInFnDecl = FnDecl->getNumParams(); for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) { ExprResult Result = PerformCopyInitialization(InitializedEntity::InitializeParameter( FnDecl->getParamDecl(i)), SourceLocation(), Owned(Args[i]->Retain())); if (Result.isInvalid()) return true; Args[i] = Result.takeAs<Expr>(); } Operator = FnDecl; CheckAllocationAccess(StartLoc, Range, R.getNamingClass(), Best->FoundDecl); return false; } case OR_No_Viable_Function: Diag(StartLoc, diag::err_ovl_no_viable_function_in_call) << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; case OR_Ambiguous: Diag(StartLoc, diag::err_ovl_ambiguous_call) << Name << Range; Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs); return true; case OR_Deleted: Diag(StartLoc, diag::err_ovl_deleted_call) << Best->Function->isDeleted() << Name << Range; Candidates.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs); return true; } assert(false && "Unreachable, bad result from BestViableFunction"); return true; } /// DeclareGlobalNewDelete - Declare the global forms of operator new and /// delete. These are: /// @code /// void* operator new(std::size_t) throw(std::bad_alloc); /// void* operator new[](std::size_t) throw(std::bad_alloc); /// void operator delete(void *) throw(); /// void operator delete[](void *) throw(); /// @endcode /// Note that the placement and nothrow forms of new are *not* implicitly /// declared. Their use requires including \<new\>. void Sema::DeclareGlobalNewDelete() { if (GlobalNewDeleteDeclared) return; // C++ [basic.std.dynamic]p2: // [...] The following allocation and deallocation functions (18.4) are // implicitly declared in global scope in each translation unit of a // program // // void* operator new(std::size_t) throw(std::bad_alloc); // void* operator new[](std::size_t) throw(std::bad_alloc); // void operator delete(void*) throw(); // void operator delete[](void*) throw(); // // These implicit declarations introduce only the function names operator // new, operator new[], operator delete, operator delete[]. // // Here, we need to refer to std::bad_alloc, so we will implicitly declare // "std" or "bad_alloc" as necessary to form the exception specification. // However, we do not make these implicit declarations visible to name // lookup. if (!StdBadAlloc) { // The "std::bad_alloc" class has not yet been declared, so build it // implicitly. StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, getOrCreateStdNamespace(), SourceLocation(), &PP.getIdentifierTable().get("bad_alloc"), SourceLocation(), 0); getStdBadAlloc()->setImplicit(true); } GlobalNewDeleteDeclared = true; QualType VoidPtr = Context.getPointerType(Context.VoidTy); QualType SizeT = Context.getSizeType(); bool AssumeSaneOperatorNew = getLangOptions().AssumeSaneOperatorNew; DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_New), VoidPtr, SizeT, AssumeSaneOperatorNew); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_New), VoidPtr, SizeT, AssumeSaneOperatorNew); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Delete), Context.VoidTy, VoidPtr); DeclareGlobalAllocationFunction( Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete), Context.VoidTy, VoidPtr); } /// DeclareGlobalAllocationFunction - Declares a single implicit global /// allocation function if it doesn't already exist. void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, QualType Argument, bool AddMallocAttr) { DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); // Check if this function is already declared. { DeclContext::lookup_iterator Alloc, AllocEnd; for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name); Alloc != AllocEnd; ++Alloc) { // Only look at non-template functions, as it is the predefined, // non-templated allocation function we are trying to declare here. if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { QualType InitialParamType = Context.getCanonicalType( Func->getParamDecl(0)->getType().getUnqualifiedType()); // FIXME: Do we need to check for default arguments here? if (Func->getNumParams() == 1 && InitialParamType == Argument) { if(AddMallocAttr && !Func->hasAttr<MallocAttr>()) Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); return; } } } } QualType BadAllocType; bool HasBadAllocExceptionSpec = (Name.getCXXOverloadedOperator() == OO_New || Name.getCXXOverloadedOperator() == OO_Array_New); if (HasBadAllocExceptionSpec) { assert(StdBadAlloc && "Must have std::bad_alloc declared"); BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); } QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0, true, false, HasBadAllocExceptionSpec? 1 : 0, &BadAllocType, FunctionType::ExtInfo()); FunctionDecl *Alloc = FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name, FnType, /*TInfo=*/0, SC_None, SC_None, false, true); Alloc->setImplicit(); if (AddMallocAttr) Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context)); ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(), 0, Argument, /*TInfo=*/0, SC_None, SC_None, 0); Alloc->setParams(&Param, 1); // FIXME: Also add this declaration to the IdentifierResolver, but // make sure it is at the end of the chain to coincide with the // global scope. Context.getTranslationUnitDecl()->addDecl(Alloc); } bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator) { LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); // Try to find operator delete/operator delete[] in class scope. LookupQualifiedName(Found, RD); if (Found.isAmbiguous()) return true; Found.suppressDiagnostics(); llvm::SmallVector<DeclAccessPair,4> Matches; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) { NamedDecl *ND = (*F)->getUnderlyingDecl(); // Ignore template operator delete members from the check for a usual // deallocation function. if (isa<FunctionTemplateDecl>(ND)) continue; if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction()) Matches.push_back(F.getPair()); } // There's exactly one suitable operator; pick it. if (Matches.size() == 1) { Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl()); CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), Matches[0]); return false; // We found multiple suitable operators; complain about the ambiguity. } else if (!Matches.empty()) { Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) << Name << RD; for (llvm::SmallVectorImpl<DeclAccessPair>::iterator F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::note_member_declared_here) << Name; return true; } // We did find operator delete/operator delete[] declarations, but // none of them were suitable. if (!Found.empty()) { Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) << Name << RD; for (LookupResult::iterator F = Found.begin(), FEnd = Found.end(); F != FEnd; ++F) Diag((*F)->getUnderlyingDecl()->getLocation(), diag::note_member_declared_here) << Name; return true; } // Look for a global declaration. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation()); Expr* DeallocArgs[1]; DeallocArgs[0] = &Null; if (FindAllocationOverload(StartLoc, SourceRange(), Name, DeallocArgs, 1, TUDecl, /*AllowMissing=*/false, Operator)) return true; assert(Operator && "Did not find a deallocation function!"); return false; } /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: /// @code ::delete ptr; @endcode /// or /// @code delete [] ptr; @endcode ExprResult Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Ex) { // C++ [expr.delete]p1: // The operand shall have a pointer type, or a class type having a single // conversion function to a pointer type. The result has type void. // // DR599 amends "pointer type" to "pointer to object type" in both cases. FunctionDecl *OperatorDelete = 0; if (!Ex->isTypeDependent()) { QualType Type = Ex->getType(); if (const RecordType *Record = Type->getAs<RecordType>()) { if (RequireCompleteType(StartLoc, Type, PDiag(diag::err_delete_incomplete_class_type))) return ExprError(); llvm::SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions; CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions(); for (UnresolvedSetImpl::iterator I = Conversions->begin(), E = Conversions->end(); I != E; ++I) { NamedDecl *D = I.getDecl(); if (isa<UsingShadowDecl>(D)) D = cast<UsingShadowDecl>(D)->getTargetDecl(); // Skip over templated conversion functions; they aren't considered. if (isa<FunctionTemplateDecl>(D)) continue; CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); QualType ConvType = Conv->getConversionType().getNonReferenceType(); if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) ObjectPtrConversions.push_back(Conv); } if (ObjectPtrConversions.size() == 1) { // We have a single conversion to a pointer-to-object type. Perform // that conversion. // TODO: don't redo the conversion calculation. if (!PerformImplicitConversion(Ex, ObjectPtrConversions.front()->getConversionType(), AA_Converting)) { Type = Ex->getType(); } } else if (ObjectPtrConversions.size() > 1) { Diag(StartLoc, diag::err_ambiguous_delete_operand) << Type << Ex->getSourceRange(); for (unsigned i= 0; i < ObjectPtrConversions.size(); i++) NoteOverloadCandidate(ObjectPtrConversions[i]); return ExprError(); } } if (!Type->isPointerType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); QualType Pointee = Type->getAs<PointerType>()->getPointeeType(); if (Pointee->isVoidType() && !isSFINAEContext()) { // The C++ standard bans deleting a pointer to a non-object type, which // effectively bans deletion of "void*". However, most compilers support // this, so we treat it as a warning unless we're in a SFINAE context. Diag(StartLoc, diag::ext_delete_void_ptr_operand) << Type << Ex->getSourceRange(); } else if (Pointee->isFunctionType() || Pointee->isVoidType()) return ExprError(Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange()); else if (!Pointee->isDependentType() && RequireCompleteType(StartLoc, Pointee, PDiag(diag::warn_delete_incomplete) << Ex->getSourceRange())) return ExprError(); // C++ [expr.delete]p2: // [Note: a pointer to a const type can be the operand of a // delete-expression; it is not necessary to cast away the constness // (5.2.11) of the pointer expression before it is used as the operand // of the delete-expression. ] ImpCastExprToType(Ex, Context.getPointerType(Context.VoidTy), CK_NoOp); DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( ArrayForm ? OO_Array_Delete : OO_Delete); QualType PointeeElem = Context.getBaseElementType(Pointee); if (const RecordType *RT = PointeeElem->getAs<RecordType>()) { CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); if (!UseGlobal && FindDeallocationFunction(StartLoc, RD, DeleteName, OperatorDelete)) return ExprError(); if (!RD->hasTrivialDestructor()) if (const CXXDestructorDecl *Dtor = LookupDestructor(RD)) MarkDeclarationReferenced(StartLoc, const_cast<CXXDestructorDecl*>(Dtor)); } if (!OperatorDelete) { // Look for a global declaration. DeclareGlobalNewDelete(); DeclContext *TUDecl = Context.getTranslationUnitDecl(); if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName, &Ex, 1, TUDecl, /*AllowMissing=*/false, OperatorDelete)) return ExprError(); } MarkDeclarationReferenced(StartLoc, OperatorDelete); // FIXME: Check access and ambiguity of operator delete and destructor. } return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, OperatorDelete, Ex, StartLoc)); } /// \brief Check the use of the given variable as a C++ condition in an if, /// while, do-while, or switch statement. ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, bool ConvertToBoolean) { QualType T = ConditionVar->getType(); // C++ [stmt.select]p2: // The declarator shall not specify a function or an array. if (T->isFunctionType()) return ExprError(Diag(ConditionVar->getLocation(), diag::err_invalid_use_of_function_type) << ConditionVar->getSourceRange()); else if (T->isArrayType()) return ExprError(Diag(ConditionVar->getLocation(), diag::err_invalid_use_of_array_type) << ConditionVar->getSourceRange()); Expr *Condition = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, ConditionVar->getLocation(), ConditionVar->getType().getNonReferenceType()); if (ConvertToBoolean && CheckBooleanCondition(Condition, StmtLoc)) return ExprError(); return Owned(Condition); } /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) { // C++ 6.4p4: // The value of a condition that is an initialized declaration in a statement // other than a switch statement is the value of the declared variable // implicitly converted to type bool. If that conversion is ill-formed, the // program is ill-formed. // The value of a condition that is an expression is the value of the // expression, implicitly converted to bool. // return PerformContextuallyConvertToBool(CondExpr); } /// Helper function to determine whether this is the (deprecated) C++ /// conversion from a string literal to a pointer to non-const char or /// non-const wchar_t (for narrow and wide string literals, /// respectively). bool Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { // Look inside the implicit cast, if it exists. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) From = Cast->getSubExpr(); // A string literal (2.13.4) that is not a wide string literal can // be converted to an rvalue of type "pointer to char"; a wide // string literal can be converted to an rvalue of type "pointer // to wchar_t" (C++ 4.2p2). if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) if (const BuiltinType *ToPointeeType = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { // This conversion is considered only when there is an // explicit appropriate pointer target type (C++ 4.2p2). if (!ToPtrType->getPointeeType().hasQualifiers() && ((StrLit->isWide() && ToPointeeType->isWideCharType()) || (!StrLit->isWide() && (ToPointeeType->getKind() == BuiltinType::Char_U || ToPointeeType->getKind() == BuiltinType::Char_S)))) return true; } return false; } static ExprResult BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, Expr *From) { switch (Kind) { default: assert(0 && "Unhandled cast kind!"); case CK_ConstructorConversion: { ASTOwningVector<Expr*> ConstructorArgs(S); if (S.CompleteConstructorCall(cast<CXXConstructorDecl>(Method), MultiExprArg(&From, 1), CastLoc, ConstructorArgs)) return ExprError(); ExprResult Result = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method), move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (Result.isInvalid()) return ExprError(); return S.MaybeBindToTemporary(Result.takeAs<Expr>()); } case CK_UserDefinedConversion: { assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); // Create an implicit call expr that calls it. // FIXME: pass the FoundDecl for the user-defined conversion here CXXMemberCallExpr *CE = S.BuildCXXMemberCallExpr(From, Method, Method); return S.MaybeBindToTemporary(CE); } } } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType using the pre-computed implicit /// conversion sequence ICS. Returns true if there was an error, false /// otherwise. The expression From is replaced with the converted /// expression. Action is the kind of conversion we're performing, /// used in the error message. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, bool IgnoreBaseAccess) { switch (ICS.getKind()) { case ImplicitConversionSequence::StandardConversion: if (PerformImplicitConversion(From, ToType, ICS.Standard, Action, IgnoreBaseAccess)) return true; break; case ImplicitConversionSequence::UserDefinedConversion: { FunctionDecl *FD = ICS.UserDefined.ConversionFunction; CastKind CastKind = CK_Unknown; QualType BeforeToType; if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { CastKind = CK_UserDefinedConversion; // If the user-defined conversion is specified by a conversion function, // the initial standard conversion sequence converts the source type to // the implicit object parameter of the conversion function. BeforeToType = Context.getTagDeclType(Conv->getParent()); } else if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { CastKind = CK_ConstructorConversion; // Do no conversion if dealing with ... for the first conversion. if (!ICS.UserDefined.EllipsisConversion) { // If the user-defined conversion is specified by a constructor, the // initial standard conversion sequence converts the source type to the // type required by the argument of the constructor BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); } } else assert(0 && "Unknown conversion function kind!"); // Whatch out for elipsis conversion. if (!ICS.UserDefined.EllipsisConversion) { if (PerformImplicitConversion(From, BeforeToType, ICS.UserDefined.Before, AA_Converting, IgnoreBaseAccess)) return true; } ExprResult CastArg = BuildCXXCastArgument(*this, From->getLocStart(), ToType.getNonReferenceType(), CastKind, cast<CXXMethodDecl>(FD), From); if (CastArg.isInvalid()) return true; From = CastArg.takeAs<Expr>(); return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, AA_Converting, IgnoreBaseAccess); } case ImplicitConversionSequence::AmbiguousConversion: ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), PDiag(diag::err_typecheck_ambiguous_condition) << From->getSourceRange()); return true; case ImplicitConversionSequence::EllipsisConversion: assert(false && "Cannot perform an ellipsis conversion"); return false; case ImplicitConversionSequence::BadConversion: return true; } // Everything went well. return false; } /// PerformImplicitConversion - Perform an implicit conversion of the /// expression From to the type ToType by following the standard /// conversion sequence SCS. Returns true if there was an error, false /// otherwise. The expression From is replaced with the converted /// expression. Flavor is the context in which we're performing this /// conversion, for use in error messages. bool Sema::PerformImplicitConversion(Expr *&From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, bool IgnoreBaseAccess) { // Overall FIXME: we are recomputing too many types here and doing far too // much extra work. What this means is that we need to keep track of more // information that is computed when we try the implicit conversion initially, // so that we don't need to recompute anything here. QualType FromType = From->getType(); if (SCS.CopyConstructor) { // FIXME: When can ToType be a reference type? assert(!ToType->isReferenceType()); if (SCS.Second == ICK_Derived_To_Base) { ASTOwningVector<Expr*> ConstructorArgs(*this); if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), MultiExprArg(*this, &From, 1), /*FIXME:ConstructLoc*/SourceLocation(), ConstructorArgs)) return true; ExprResult FromResult = BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), ToType, SCS.CopyConstructor, move_arg(ConstructorArgs), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (FromResult.isInvalid()) return true; From = FromResult.takeAs<Expr>(); return false; } ExprResult FromResult = BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(), ToType, SCS.CopyConstructor, MultiExprArg(*this, &From, 1), /*ZeroInit*/ false, CXXConstructExpr::CK_Complete); if (FromResult.isInvalid()) return true; From = FromResult.takeAs<Expr>(); return false; } // Resolve overloaded function references. if (Context.hasSameType(FromType, Context.OverloadTy)) { DeclAccessPair Found; FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true, Found); if (!Fn) return true; if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin())) return true; From = FixOverloadedFunctionReference(From, Found, Fn); FromType = From->getType(); } // Perform the first implicit conversion. switch (SCS.First) { case ICK_Identity: case ICK_Lvalue_To_Rvalue: // Nothing to do. break; case ICK_Array_To_Pointer: FromType = Context.getArrayDecayedType(FromType); ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay); break; case ICK_Function_To_Pointer: FromType = Context.getPointerType(FromType); ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay); break; default: assert(false && "Improper first standard conversion"); break; } // Perform the second implicit conversion switch (SCS.Second) { case ICK_Identity: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (CheckExceptionSpecCompatibility(From, ToType)) return true; // Nothing else to do. break; case ICK_NoReturn_Adjustment: // If both sides are functions (or pointers/references to them), there could // be incompatible exception declarations. if (CheckExceptionSpecCompatibility(From, ToType)) return true; ImpCastExprToType(From, Context.getNoReturnType(From->getType(), false), CK_NoOp); break; case ICK_Integral_Promotion: case ICK_Integral_Conversion: ImpCastExprToType(From, ToType, CK_IntegralCast); break; case ICK_Floating_Promotion: case ICK_Floating_Conversion: ImpCastExprToType(From, ToType, CK_FloatingCast); break; case ICK_Complex_Promotion: case ICK_Complex_Conversion: ImpCastExprToType(From, ToType, CK_Unknown); break; case ICK_Floating_Integral: if (ToType->isRealFloatingType()) ImpCastExprToType(From, ToType, CK_IntegralToFloating); else ImpCastExprToType(From, ToType, CK_FloatingToIntegral); break; case ICK_Compatible_Conversion: ImpCastExprToType(From, ToType, CK_NoOp); break; case ICK_Pointer_Conversion: { if (SCS.IncompatibleObjC) { // Diagnose incompatible Objective-C conversions Diag(From->getSourceRange().getBegin(), diag::ext_typecheck_convert_incompatible_pointer) << From->getType() << ToType << Action << From->getSourceRange(); } CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case ICK_Pointer_Member: { CastKind Kind = CK_Unknown; CXXCastPath BasePath; if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, IgnoreBaseAccess)) return true; if (CheckExceptionSpecCompatibility(From, ToType)) return true; ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath); break; } case ICK_Boolean_Conversion: { CastKind Kind = CK_Unknown; if (FromType->isMemberPointerType()) Kind = CK_MemberPointerToBoolean; ImpCastExprToType(From, Context.BoolTy, Kind); break; } case ICK_Derived_To_Base: { CXXCastPath BasePath; if (CheckDerivedToBaseConversion(From->getType(), ToType.getNonReferenceType(), From->getLocStart(), From->getSourceRange(), &BasePath, IgnoreBaseAccess)) return true; ImpCastExprToType(From, ToType.getNonReferenceType(), CK_DerivedToBase, CastCategory(From), &BasePath); break; } case ICK_Vector_Conversion: ImpCastExprToType(From, ToType, CK_BitCast); break; case ICK_Vector_Splat: ImpCastExprToType(From, ToType, CK_VectorSplat); break; case ICK_Complex_Real: ImpCastExprToType(From, ToType, CK_Unknown); break; case ICK_Lvalue_To_Rvalue: case ICK_Array_To_Pointer: case ICK_Function_To_Pointer: case ICK_Qualification: case ICK_Num_Conversion_Kinds: assert(false && "Improper second standard conversion"); break; } switch (SCS.Third) { case ICK_Identity: // Nothing to do. break; case ICK_Qualification: { // The qualification keeps the category of the inner expression, unless the // target type isn't a reference. ExprValueKind VK = ToType->isReferenceType() ? CastCategory(From) : VK_RValue; ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK_NoOp, VK); if (SCS.DeprecatedStringLiteralToCharPtr) Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion) << ToType.getNonReferenceType(); break; } default: assert(false && "Improper third standard conversion"); break; } return false; } ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT, SourceLocation KWLoc, SourceLocation LParen, ParsedType Ty, SourceLocation RParen) { QualType T = GetTypeFromParser(Ty); // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html // all traits except __is_class, __is_enum and __is_union require a the type // to be complete. if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) { if (RequireCompleteType(KWLoc, T, diag::err_incomplete_type_used_in_type_trait_expr)) return ExprError(); } // There is no point in eagerly computing the value. The traits are designed // to be used from type trait templates, so Ty will be a template parameter // 99% of the time. return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T, RParen, Context.BoolTy)); } QualType Sema::CheckPointerToMemberOperands( Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect) { const char *OpSpelling = isIndirect ? "->*" : ".*"; // C++ 5.5p2 // The binary operator .* [p3: ->*] binds its second operand, which shall // be of type "pointer to member of T" (where T is a completely-defined // class type) [...] QualType RType = rex->getType(); const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>(); if (!MemPtr) { Diag(Loc, diag::err_bad_memptr_rhs) << OpSpelling << RType << rex->getSourceRange(); return QualType(); } QualType Class(MemPtr->getClass(), 0); if (RequireCompleteType(Loc, Class, diag::err_memptr_rhs_to_incomplete)) return QualType(); // C++ 5.5p2 // [...] to its first operand, which shall be of class T or of a class of // which T is an unambiguous and accessible base class. [p3: a pointer to // such a class] QualType LType = lex->getType(); if (isIndirect) { if (const PointerType *Ptr = LType->getAs<PointerType>()) LType = Ptr->getPointeeType().getNonReferenceType(); else { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << 1 << LType << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); return QualType(); } } if (!Context.hasSameUnqualifiedType(Class, LType)) { // If we want to check the hierarchy, we need a complete type. if (RequireCompleteType(Loc, LType, PDiag(diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect)) { return QualType(); } CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/false); // FIXME: Would it be useful to print full ambiguity paths, or is that // overkill? if (!IsDerivedFrom(LType, Class, Paths) || Paths.isAmbiguous(Context.getCanonicalType(Class))) { Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling << (int)isIndirect << lex->getType(); return QualType(); } // Cast LHS to type of use. QualType UseType = isIndirect ? Context.getPointerType(Class) : Class; ExprValueKind VK = isIndirect ? VK_RValue : CastCategory(lex); CXXCastPath BasePath; BuildBasePathArray(Paths, BasePath); ImpCastExprToType(lex, UseType, CK_DerivedToBase, VK, &BasePath); } if (isa<CXXScalarValueInitExpr>(rex->IgnoreParens())) { // Diagnose use of pointer-to-member type which when used as // the functional cast in a pointer-to-member expression. Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; return QualType(); } // C++ 5.5p2 // The result is an object or a function of the type specified by the // second operand. // The cv qualifiers are the union of those in the pointer and the left side, // in accordance with 5.5p5 and 5.2.5. // FIXME: This returns a dereferenced member function pointer as a normal // function type. However, the only operation valid on such functions is // calling them. There's also a GCC extension to get a function pointer to the // thing, which is another complication, because this type - unlike the type // that is the result of this expression - takes the class as the first // argument. // We probably need a "MemberFunctionClosureType" or something like that. QualType Result = MemPtr->getPointeeType(); Result = Context.getCVRQualifiedType(Result, LType.getCVRQualifiers()); return Result; } /// \brief Try to convert a type to another according to C++0x 5.16p3. /// /// This is part of the parameter validation for the ? operator. If either /// value operand is a class type, the two operands are attempted to be /// converted to each other. This function does the conversion in one direction. /// It returns true if the program is ill-formed and has already been diagnosed /// as such. static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, SourceLocation QuestionLoc, bool &HaveConversion, QualType &ToType) { HaveConversion = false; ToType = To->getType(); InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(), SourceLocation()); // C++0x 5.16p3 // The process for determining whether an operand expression E1 of type T1 // can be converted to match an operand expression E2 of type T2 is defined // as follows: // -- If E2 is an lvalue: bool ToIsLvalue = (To->isLvalue(Self.Context) == Expr::LV_Valid); if (ToIsLvalue) { // E1 can be converted to match E2 if E1 can be implicitly converted to // type "lvalue reference to T2", subject to the constraint that in the // conversion the reference must bind directly to E1. QualType T = Self.Context.getLValueReferenceType(ToType); InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.isDirectReferenceBinding()) { ToType = T; HaveConversion = true; return false; } if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); } // -- If E2 is an rvalue, or if the conversion above cannot be done: // -- if E1 and E2 have class type, and the underlying class types are // the same or one is a base class of the other: QualType FTy = From->getType(); QualType TTy = To->getType(); const RecordType *FRec = FTy->getAs<RecordType>(); const RecordType *TRec = TTy->getAs<RecordType>(); bool FDerivedFromT = FRec && TRec && FRec != TRec && Self.IsDerivedFrom(FTy, TTy); if (FRec && TRec && (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) { // E1 can be converted to match E2 if the class of T2 is the // same type as, or a base class of, the class of T1, and // [cv2 > cv1]. if (FRec == TRec || FDerivedFromT) { if (TTy.isAtLeastAsQualifiedAs(FTy)) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); if (InitSeq.getKind() != InitializationSequence::FailedSequence) { HaveConversion = true; return false; } if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); } } return false; } // -- Otherwise: E1 can be converted to match E2 if E1 can be // implicitly converted to the type that expression E2 would have // if E2 were converted to an rvalue (or the type it has, if E2 is // an rvalue). // // This actually refers very narrowly to the lvalue-to-rvalue conversion, not // to the array-to-pointer or function-to-pointer conversions. if (!TTy->getAs<TagType>()) TTy = TTy.getUnqualifiedType(); InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); InitializationSequence InitSeq(Self, Entity, Kind, &From, 1); HaveConversion = InitSeq.getKind() != InitializationSequence::FailedSequence; ToType = TTy; if (InitSeq.isAmbiguous()) return InitSeq.Diagnose(Self, Entity, Kind, &From, 1); return false; } /// \brief Try to find a common type for two according to C++0x 5.16p5. /// /// This is part of the parameter validation for the ? operator. If either /// value operand is a class type, overload resolution is used to find a /// conversion to a common type. static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS, SourceLocation Loc) { Expr *Args[2] = { LHS, RHS }; OverloadCandidateSet CandidateSet(Loc); Self.AddBuiltinOperatorCandidates(OO_Conditional, Loc, Args, 2, CandidateSet); OverloadCandidateSet::iterator Best; switch (CandidateSet.BestViableFunction(Self, Loc, Best)) { case OR_Success: // We found a match. Perform the conversions on the arguments and move on. if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0], Best->Conversions[0], Sema::AA_Converting) || Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1], Best->Conversions[1], Sema::AA_Converting)) break; return false; case OR_No_Viable_Function: Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return true; case OR_Ambiguous: Self.Diag(Loc, diag::err_conditional_ambiguous_ovl) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); // FIXME: Print the possible common types by printing the return types of // the viable candidates. break; case OR_Deleted: assert(false && "Conditional operator has only built-in overloads"); break; } return true; } /// \brief Perform an "extended" implicit conversion as returned by /// TryClassUnification. static bool ConvertForConditional(Sema &Self, Expr *&E, QualType T) { InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); InitializationKind Kind = InitializationKind::CreateCopy(E->getLocStart(), SourceLocation()); InitializationSequence InitSeq(Self, Entity, Kind, &E, 1); ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&E, 1)); if (Result.isInvalid()) return true; E = Result.takeAs<Expr>(); return false; } /// \brief Check the operands of ?: under C++ semantics. /// /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y /// extension. In this case, LHS == Cond. (But they're not aliases.) QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS, SourceLocation QuestionLoc) { // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++ // interface pointers. // C++0x 5.16p1 // The first expression is contextually converted to bool. if (!Cond->isTypeDependent()) { if (CheckCXXBooleanCondition(Cond)) return QualType(); } // Either of the arguments dependent? if (LHS->isTypeDependent() || RHS->isTypeDependent()) return Context.DependentTy; // C++0x 5.16p2 // If either the second or the third operand has type (cv) void, ... QualType LTy = LHS->getType(); QualType RTy = RHS->getType(); bool LVoid = LTy->isVoidType(); bool RVoid = RTy->isVoidType(); if (LVoid || RVoid) { // ... then the [l2r] conversions are performed on the second and third // operands ... DefaultFunctionArrayLvalueConversion(LHS); DefaultFunctionArrayLvalueConversion(RHS); LTy = LHS->getType(); RTy = RHS->getType(); // ... and one of the following shall hold: // -- The second or the third operand (but not both) is a throw- // expression; the result is of the type of the other and is an rvalue. bool LThrow = isa<CXXThrowExpr>(LHS); bool RThrow = isa<CXXThrowExpr>(RHS); if (LThrow && !RThrow) return RTy; if (RThrow && !LThrow) return LTy; // -- Both the second and third operands have type void; the result is of // type void and is an rvalue. if (LVoid && RVoid) return Context.VoidTy; // Neither holds, error. Diag(QuestionLoc, diag::err_conditional_void_nonvoid) << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } // Neither is void. // C++0x 5.16p3 // Otherwise, if the second and third operand have different types, and // either has (cv) class type, and attempt is made to convert each of those // operands to the other. if (!Context.hasSameType(LTy, RTy) && (LTy->isRecordType() || RTy->isRecordType())) { ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft; // These return true if a single direction is already ambiguous. QualType L2RType, R2LType; bool HaveL2R, HaveR2L; if (TryClassUnification(*this, LHS, RHS, QuestionLoc, HaveL2R, L2RType)) return QualType(); if (TryClassUnification(*this, RHS, LHS, QuestionLoc, HaveR2L, R2LType)) return QualType(); // If both can be converted, [...] the program is ill-formed. if (HaveL2R && HaveR2L) { Diag(QuestionLoc, diag::err_conditional_ambiguous) << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } // If exactly one conversion is possible, that conversion is applied to // the chosen operand and the converted operands are used in place of the // original operands for the remainder of this section. if (HaveL2R) { if (ConvertForConditional(*this, LHS, L2RType)) return QualType(); LTy = LHS->getType(); } else if (HaveR2L) { if (ConvertForConditional(*this, RHS, R2LType)) return QualType(); RTy = RHS->getType(); } } // C++0x 5.16p4 // If the second and third operands are lvalues and have the same type, // the result is of that type [...] bool Same = Context.hasSameType(LTy, RTy); if (Same && LHS->isLvalue(Context) == Expr::LV_Valid && RHS->isLvalue(Context) == Expr::LV_Valid) return LTy; // C++0x 5.16p5 // Otherwise, the result is an rvalue. If the second and third operands // do not have the same type, and either has (cv) class type, ... if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { // ... overload resolution is used to determine the conversions (if any) // to be applied to the operands. If the overload resolution fails, the // program is ill-formed. if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) return QualType(); } // C++0x 5.16p6 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard // conversions are performed on the second and third operands. DefaultFunctionArrayLvalueConversion(LHS); DefaultFunctionArrayLvalueConversion(RHS); LTy = LHS->getType(); RTy = RHS->getType(); // After those conversions, one of the following shall hold: // -- The second and third operands have the same type; the result // is of that type. If the operands have class type, the result // is a prvalue temporary of the result type, which is // copy-initialized from either the second operand or the third // operand depending on the value of the first operand. if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { if (LTy->isRecordType()) { // The operands have class type. Make a temporary copy. InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); ExprResult LHSCopy = PerformCopyInitialization(Entity, SourceLocation(), Owned(LHS)); if (LHSCopy.isInvalid()) return QualType(); ExprResult RHSCopy = PerformCopyInitialization(Entity, SourceLocation(), Owned(RHS)); if (RHSCopy.isInvalid()) return QualType(); LHS = LHSCopy.takeAs<Expr>(); RHS = RHSCopy.takeAs<Expr>(); } return LTy; } // Extension: conditional operator involving vector types. if (LTy->isVectorType() || RTy->isVectorType()) return CheckVectorOperands(QuestionLoc, LHS, RHS); // -- The second and third operands have arithmetic or enumeration type; // the usual arithmetic conversions are performed to bring them to a // common type, and the result is of that type. if (LTy->isArithmeticType() && RTy->isArithmeticType()) { UsualArithmeticConversions(LHS, RHS); return LHS->getType(); } // -- The second and third operands have pointer type, or one has pointer // type and the other is a null pointer constant; pointer conversions // and qualification conversions are performed to bring them to their // composite pointer type. The result is of the composite pointer type. // -- The second and third operands have pointer to member type, or one has // pointer to member type and the other is a null pointer constant; // pointer to member conversions and qualification conversions are // performed to bring them to a common type, whose cv-qualification // shall match the cv-qualification of either the second or the third // operand. The result is of the common type. bool NonStandardCompositeType = false; QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS, isSFINAEContext()? 0 : &NonStandardCompositeType); if (!Composite.isNull()) { if (NonStandardCompositeType) Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands_nonstandard) << LTy << RTy << Composite << LHS->getSourceRange() << RHS->getSourceRange(); return Composite; } // Similarly, attempt to find composite type of two objective-c pointers. Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); if (!Composite.isNull()) return Composite; Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) << LHS->getType() << RHS->getType() << LHS->getSourceRange() << RHS->getSourceRange(); return QualType(); } /// \brief Find a merged pointer type and convert the two expressions to it. /// /// This finds the composite pointer type (or member pointer type) for @p E1 /// and @p E2 according to C++0x 5.9p2. It converts both expressions to this /// type and returns it. /// It does not emit diagnostics. /// /// \param Loc The location of the operator requiring these two expressions to /// be converted to the composite pointer type. /// /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find /// a non-standard (but still sane) composite type to which both expressions /// can be converted. When such a type is chosen, \c *NonStandardCompositeType /// will be set true. QualType Sema::FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool *NonStandardCompositeType) { if (NonStandardCompositeType) *NonStandardCompositeType = false; assert(getLangOptions().CPlusPlus && "This function assumes C++"); QualType T1 = E1->getType(), T2 = E2->getType(); if (!T1->isAnyPointerType() && !T1->isMemberPointerType() && !T2->isAnyPointerType() && !T2->isMemberPointerType()) return QualType(); // C++0x 5.9p2 // Pointer conversions and qualification conversions are performed on // pointer operands to bring them to their composite pointer type. If // one operand is a null pointer constant, the composite pointer type is // the type of the other operand. if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { if (T2->isMemberPointerType()) ImpCastExprToType(E1, T2, CK_NullToMemberPointer); else ImpCastExprToType(E1, T2, CK_IntegralToPointer); return T2; } if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { if (T1->isMemberPointerType()) ImpCastExprToType(E2, T1, CK_NullToMemberPointer); else ImpCastExprToType(E2, T1, CK_IntegralToPointer); return T1; } // Now both have to be pointers or member pointers. if ((!T1->isPointerType() && !T1->isMemberPointerType()) || (!T2->isPointerType() && !T2->isMemberPointerType())) return QualType(); // Otherwise, of one of the operands has type "pointer to cv1 void," then // the other has type "pointer to cv2 T" and the composite pointer type is // "pointer to cv12 void," where cv12 is the union of cv1 and cv2. // Otherwise, the composite pointer type is a pointer type similar to the // type of one of the operands, with a cv-qualification signature that is // the union of the cv-qualification signatures of the operand types. // In practice, the first part here is redundant; it's subsumed by the second. // What we do here is, we build the two possible composite types, and try the // conversions in both directions. If only one works, or if the two composite // types are the same, we have succeeded. // FIXME: extended qualifiers? typedef llvm::SmallVector<unsigned, 4> QualifierVector; QualifierVector QualifierUnion; typedef llvm::SmallVector<std::pair<const Type *, const Type *>, 4> ContainingClassVector; ContainingClassVector MemberOfClass; QualType Composite1 = Context.getCanonicalType(T1), Composite2 = Context.getCanonicalType(T2); unsigned NeedConstBefore = 0; do { const PointerType *Ptr1, *Ptr2; if ((Ptr1 = Composite1->getAs<PointerType>()) && (Ptr2 = Composite2->getAs<PointerType>())) { Composite1 = Ptr1->getPointeeType(); Composite2 = Ptr2->getPointeeType(); // If we're allowed to create a non-standard composite type, keep track // of where we need to fill in additional 'const' qualifiers. if (NonStandardCompositeType && Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) NeedConstBefore = QualifierUnion.size(); QualifierUnion.push_back( Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0)); continue; } const MemberPointerType *MemPtr1, *MemPtr2; if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && (MemPtr2 = Composite2->getAs<MemberPointerType>())) { Composite1 = MemPtr1->getPointeeType(); Composite2 = MemPtr2->getPointeeType(); // If we're allowed to create a non-standard composite type, keep track // of where we need to fill in additional 'const' qualifiers. if (NonStandardCompositeType && Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers()) NeedConstBefore = QualifierUnion.size(); QualifierUnion.push_back( Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers()); MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(), MemPtr2->getClass())); continue; } // FIXME: block pointer types? // Cannot unwrap any more types. break; } while (true); if (NeedConstBefore && NonStandardCompositeType) { // Extension: Add 'const' to qualifiers that come before the first qualifier // mismatch, so that our (non-standard!) composite type meets the // requirements of C++ [conv.qual]p4 bullet 3. for (unsigned I = 0; I != NeedConstBefore; ++I) { if ((QualifierUnion[I] & Qualifiers::Const) == 0) { QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const; *NonStandardCompositeType = true; } } } // Rewrap the composites as pointers or member pointers with the union CVRs. ContainingClassVector::reverse_iterator MOC = MemberOfClass.rbegin(); for (QualifierVector::reverse_iterator I = QualifierUnion.rbegin(), E = QualifierUnion.rend(); I != E; (void)++I, ++MOC) { Qualifiers Quals = Qualifiers::fromCVRMask(*I); if (MOC->first && MOC->second) { // Rebuild member pointer type Composite1 = Context.getMemberPointerType( Context.getQualifiedType(Composite1, Quals), MOC->first); Composite2 = Context.getMemberPointerType( Context.getQualifiedType(Composite2, Quals), MOC->second); } else { // Rebuild pointer type Composite1 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals)); Composite2 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals)); } } // Try to convert to the first composite pointer type. InitializedEntity Entity1 = InitializedEntity::InitializeTemporary(Composite1); InitializationKind Kind = InitializationKind::CreateCopy(Loc, SourceLocation()); InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1); InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1); if (E1ToC1 && E2ToC1) { // Conversion to Composite1 is viable. if (!Context.hasSameType(Composite1, Composite2)) { // Composite2 is a different type from Composite1. Check whether // Composite2 is also viable. InitializedEntity Entity2 = InitializedEntity::InitializeTemporary(Composite2); InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); if (E1ToC2 && E2ToC2) { // Both Composite1 and Composite2 are viable and are different; // this is an ambiguity. return QualType(); } } // Convert E1 to Composite1 ExprResult E1Result = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1)); if (E1Result.isInvalid()) return QualType(); E1 = E1Result.takeAs<Expr>(); // Convert E2 to Composite1 ExprResult E2Result = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1)); if (E2Result.isInvalid()) return QualType(); E2 = E2Result.takeAs<Expr>(); return Composite1; } // Check whether Composite2 is viable. InitializedEntity Entity2 = InitializedEntity::InitializeTemporary(Composite2); InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1); InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1); if (!E1ToC2 || !E2ToC2) return QualType(); // Convert E1 to Composite2 ExprResult E1Result = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1)); if (E1Result.isInvalid()) return QualType(); E1 = E1Result.takeAs<Expr>(); // Convert E2 to Composite2 ExprResult E2Result = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1)); if (E2Result.isInvalid()) return QualType(); E2 = E2Result.takeAs<Expr>(); return Composite2; } ExprResult Sema::MaybeBindToTemporary(Expr *E) { if (!Context.getLangOptions().CPlusPlus) return Owned(E); assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); const RecordType *RT = E->getType()->getAs<RecordType>(); if (!RT) return Owned(E); // If this is the result of a call or an Objective-C message send expression, // our source might actually be a reference, in which case we shouldn't bind. if (CallExpr *CE = dyn_cast<CallExpr>(E)) { if (CE->getCallReturnType()->isReferenceType()) return Owned(E); } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { if (const ObjCMethodDecl *MD = ME->getMethodDecl()) { if (MD->getResultType()->isReferenceType()) return Owned(E); } } // That should be enough to guarantee that this type is complete. // If it has a trivial destructor, we can avoid the extra copy. CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); if (RD->isInvalidDecl() || RD->hasTrivialDestructor()) return Owned(E); CXXTemporary *Temp = CXXTemporary::Create(Context, LookupDestructor(RD)); ExprTemporaries.push_back(Temp); if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { MarkDeclarationReferenced(E->getExprLoc(), Destructor); CheckDestructorAccess(E->getExprLoc(), Destructor, PDiag(diag::err_access_dtor_temp) << E->getType()); } // FIXME: Add the temporary to the temporaries vector. return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E)); } Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr) { assert(SubExpr && "sub expression can't be null!"); // Check any implicit conversions within the expression. CheckImplicitConversions(SubExpr); unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); if (ExprTemporaries.size() == FirstTemporary) return SubExpr; Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr, &ExprTemporaries[FirstTemporary], ExprTemporaries.size() - FirstTemporary); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::MaybeCreateCXXExprWithTemporaries(ExprResult SubExpr) { if (SubExpr.isInvalid()) return ExprError(); return Owned(MaybeCreateCXXExprWithTemporaries(SubExpr.takeAs<Expr>())); } FullExpr Sema::CreateFullExpr(Expr *SubExpr) { unsigned FirstTemporary = ExprEvalContexts.back().NumTemporaries; assert(ExprTemporaries.size() >= FirstTemporary); unsigned NumTemporaries = ExprTemporaries.size() - FirstTemporary; CXXTemporary **Temporaries = NumTemporaries == 0 ? 0 : &ExprTemporaries[FirstTemporary]; FullExpr E = FullExpr::Create(Context, SubExpr, Temporaries, NumTemporaries); ExprTemporaries.erase(ExprTemporaries.begin() + FirstTemporary, ExprTemporaries.end()); return E; } ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor) { // Since this might be a postfix expression, get rid of ParenListExprs. ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); if (Result.isInvalid()) return ExprError(); Base = Result.get(); QualType BaseType = Base->getType(); MayBePseudoDestructor = false; if (BaseType->isDependentType()) { // If we have a pointer to a dependent type and are using the -> operator, // the object type is the type that the pointer points to. We might still // have enough information about that type to do something useful. if (OpKind == tok::arrow) if (const PointerType *Ptr = BaseType->getAs<PointerType>()) BaseType = Ptr->getPointeeType(); ObjectType = ParsedType::make(BaseType); MayBePseudoDestructor = true; return Owned(Base); } // C++ [over.match.oper]p8: // [...] When operator->returns, the operator-> is applied to the value // returned, with the original second operand. if (OpKind == tok::arrow) { // The set of types we've considered so far. llvm::SmallPtrSet<CanQualType,8> CTypes; llvm::SmallVector<SourceLocation, 8> Locations; CTypes.insert(Context.getCanonicalType(BaseType)); while (BaseType->isRecordType()) { Result = BuildOverloadedArrowExpr(S, Base, OpLoc); if (Result.isInvalid()) return ExprError(); Base = Result.get(); if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) Locations.push_back(OpCall->getDirectCallee()->getLocation()); BaseType = Base->getType(); CanQualType CBaseType = Context.getCanonicalType(BaseType); if (!CTypes.insert(CBaseType)) { Diag(OpLoc, diag::err_operator_arrow_circular); for (unsigned i = 0; i < Locations.size(); i++) Diag(Locations[i], diag::note_declared_at); return ExprError(); } } if (BaseType->isPointerType()) BaseType = BaseType->getPointeeType(); } // We could end up with various non-record types here, such as extended // vector types or Objective-C interfaces. Just return early and let // ActOnMemberReferenceExpr do the work. if (!BaseType->isRecordType()) { // C++ [basic.lookup.classref]p2: // [...] If the type of the object expression is of pointer to scalar // type, the unqualified-id is looked up in the context of the complete // postfix-expression. // // This also indicates that we should be parsing a // pseudo-destructor-name. ObjectType = ParsedType(); MayBePseudoDestructor = true; return Owned(Base); } // The object type must be complete (or dependent). if (!BaseType->isDependentType() && RequireCompleteType(OpLoc, BaseType, PDiag(diag::err_incomplete_member_access))) return ExprError(); // C++ [basic.lookup.classref]p2: // If the id-expression in a class member access (5.2.5) is an // unqualified-id, and the type of the object expression is of a class // type C (or of pointer to a class type C), the unqualified-id is looked // up in the scope of class C. [...] ObjectType = ParsedType::make(BaseType); return move(Base); } ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr) { SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc); Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call) << isa<CXXPseudoDestructorExpr>(MemExpr) << FixItHint::CreateInsertion(ExpectedLParenLoc, "()"); return ActOnCallExpr(/*Scope*/ 0, MemExpr, /*LPLoc*/ ExpectedLParenLoc, MultiExprArg(), /*CommaLocs*/ 0, /*RPLoc*/ ExpectedLParenLoc); } ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeTypeInfo, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage Destructed, bool HasTrailingLParen) { TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); // C++ [expr.pseudo]p2: // The left-hand side of the dot operator shall be of scalar type. The // left-hand side of the arrow operator shall be of pointer to scalar type. // This scalar type is the object type. QualType ObjectType = Base->getType(); if (OpKind == tok::arrow) { if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { ObjectType = Ptr->getPointeeType(); } else if (!Base->isTypeDependent()) { // The user wrote "p->" when she probably meant "p."; fix it. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) { Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) << ObjectType << Base->getSourceRange(); return ExprError(); } // C++ [expr.pseudo]p2: // [...] The cv-unqualified versions of the object type and of the type // designated by the pseudo-destructor-name shall be the same type. if (DestructedTypeInfo) { QualType DestructedType = DestructedTypeInfo->getType(); SourceLocation DestructedTypeStart = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); if (!DestructedType->isDependentType() && !ObjectType->isDependentType() && !Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) << ObjectType << DestructedType << Base->getSourceRange() << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); // Recover by setting the destructed type to the object type. DestructedType = ObjectType; DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); } } // C++ [expr.pseudo]p2: // [...] Furthermore, the two type-names in a pseudo-destructor-name of the // form // // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name // // shall designate the same scalar type. if (ScopeTypeInfo) { QualType ScopeType = ScopeTypeInfo->getType(); if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), diag::err_pseudo_dtor_type_mismatch) << ObjectType << ScopeType << Base->getSourceRange() << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); ScopeType = QualType(); ScopeTypeInfo = 0; } } Expr *Result = new (Context) CXXPseudoDestructorExpr(Context, Base, OpKind == tok::arrow, OpLoc, SS.getScopeRep(), SS.getRange(), ScopeTypeInfo, CCLoc, TildeLoc, Destructed); if (HasTrailingLParen) return Owned(Result); return DiagnoseDtorReference(Destructed.getLocation(), Result); } ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName, bool HasTrailingLParen) { assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) && "Invalid first type name in pseudo-destructor"); assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) && "Invalid second type name in pseudo-destructor"); // C++ [expr.pseudo]p2: // The left-hand side of the dot operator shall be of scalar type. The // left-hand side of the arrow operator shall be of pointer to scalar type. // This scalar type is the object type. QualType ObjectType = Base->getType(); if (OpKind == tok::arrow) { if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { ObjectType = Ptr->getPointeeType(); } else if (!ObjectType->isDependentType()) { // The user wrote "p->" when she probably meant "p."; fix it. Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) << ObjectType << true << FixItHint::CreateReplacement(OpLoc, "."); if (isSFINAEContext()) return ExprError(); OpKind = tok::period; } } // Compute the object type that we should use for name lookup purposes. Only // record types and dependent types matter. ParsedType ObjectTypePtrForLookup; if (!SS.isSet()) { if (const Type *T = ObjectType->getAs<RecordType>()) ObjectTypePtrForLookup = ParsedType::make(QualType(T, 0)); else if (ObjectType->isDependentType()) ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); } // Convert the name of the type being destructed (following the ~) into a // type (with source-location information). QualType DestructedType; TypeSourceInfo *DestructedTypeInfo = 0; PseudoDestructorTypeStorage Destructed; if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*SecondTypeName.Identifier, SecondTypeName.StartLocation, S, &SS, true, ObjectTypePtrForLookup); if (!T && ((SS.isSet() && !computeDeclContext(SS, false)) || (!SS.isSet() && ObjectType->isDependentType()))) { // The name of the type being destroyed is a dependent name, and we // couldn't find anything useful in scope. Just store the identifier and // it's location, and we'll perform (qualified) name lookup again at // template instantiation time. Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, SecondTypeName.StartLocation); } else if (!T) { Diag(SecondTypeName.StartLocation, diag::err_pseudo_dtor_destructor_non_type) << SecondTypeName.Identifier << ObjectType; if (isSFINAEContext()) return ExprError(); // Recover by assuming we had the right type all along. DestructedType = ObjectType; } else DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); } else { // Resolve the template-id to a type. TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; ASTTemplateArgsPtr TemplateArgsPtr(*this, TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult T = ActOnTemplateIdType(TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); if (T.isInvalid() || !T.get()) { // Recover by assuming we had the right type all along. DestructedType = ObjectType; } else DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); } // If we've performed some kind of recovery, (re-)build the type source // information. if (!DestructedType.isNull()) { if (!DestructedTypeInfo) DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, SecondTypeName.StartLocation); Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); } // Convert the name of the scope type (the type prior to '::') into a type. TypeSourceInfo *ScopeTypeInfo = 0; QualType ScopeType; if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId || FirstTypeName.Identifier) { if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) { ParsedType T = getTypeName(*FirstTypeName.Identifier, FirstTypeName.StartLocation, S, &SS, false, ObjectTypePtrForLookup); if (!T) { Diag(FirstTypeName.StartLocation, diag::err_pseudo_dtor_destructor_non_type) << FirstTypeName.Identifier << ObjectType; if (isSFINAEContext()) return ExprError(); // Just drop this type. It's unnecessary anyway. ScopeType = QualType(); } else ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); } else { // Resolve the template-id to a type. TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; ASTTemplateArgsPtr TemplateArgsPtr(*this, TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult T = ActOnTemplateIdType(TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); if (T.isInvalid() || !T.get()) { // Recover by dropping this type. ScopeType = QualType(); } else ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); } } if (!ScopeType.isNull() && !ScopeTypeInfo) ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, FirstTypeName.StartLocation); return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, ScopeTypeInfo, CCLoc, TildeLoc, Destructed, HasTrailingLParen); } CXXMemberCallExpr *Sema::BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXMethodDecl *Method) { if (PerformObjectArgumentInitialization(Exp, /*Qualifier=*/0, FoundDecl, Method)) assert(0 && "Calling BuildCXXMemberCallExpr with invalid call?"); MemberExpr *ME = new (Context) MemberExpr(Exp, /*IsArrow=*/false, Method, SourceLocation(), Method->getType()); QualType ResultType = Method->getCallResultType(); MarkDeclarationReferenced(Exp->getLocStart(), Method); CXXMemberCallExpr *CE = new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, Exp->getLocEnd()); return CE; } ExprResult Sema::ActOnFinishFullExpr(Expr *FullExpr) { if (!FullExpr) return ExprError(); return MaybeCreateCXXExprWithTemporaries(FullExpr); }
chriskmanx/qmole
QMOLEDEV/llvm-2.8/tools/clang-2.8/lib/Sema/SemaExprCXX.cpp
C++
gpl-3.0
124,344
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.virtualization; import java.io.IOException; /** * @author Lucian Chirita ([email protected]) */ public class FloatSerializer implements ObjectSerializer<Float> { @Override public int typeValue() { return SerializationConstants.OBJECT_TYPE_FLOAT; } @Override public ReferenceType defaultReferenceType() { return ReferenceType.OBJECT; } @Override public boolean defaultStoreReference() { return true; } @Override public void write(Float value, VirtualizationOutput out) throws IOException { out.writeFloat(value); } @Override public Float read(VirtualizationInput in) throws IOException { return in.readFloat(); } }
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/virtualization/FloatSerializer.java
Java
gpl-3.0
1,687
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action_Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @see Zend_Session */ require_once 'Zend/Session.php'; /** * @see Zend_Controller_Action_Helper_Abstract */ require_once 'Zend/Controller/Action/Helper/Abstract.php'; /** * Flash Messenger - implement session-based messages * * @uses Zend_Controller_Action_Helper_Abstract * @category Zend * @package Zend_Controller * @subpackage Zend_Controller_Action_Helper * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: FlashMessenger.php 23775 2011-03-01 17:25:24Z ralph $ */ class Zend_Controller_Action_Helper_FlashMessengerType extends Zend_Controller_Action_Helper_Abstract implements IteratorAggregate, Countable { /** * $_messages - Messages from previous request * * @var array */ static protected $_messages = array(); /** * $_session - Zend_Session storage object * * @var Zend_Session */ static protected $_session = null; /** * $_messageAdded - Wether a message has been previously added * * @var boolean */ static protected $_messageAdded = false; /** * $_namespace - Instance namespace, default is 'default' * * @var string */ protected $_namespace = 'default'; /** * __construct() - Instance constructor, needed to get iterators, etc * * @param string $namespace * @return void */ public function __construct() { if (!self::$_session instanceof Zend_Session_Namespace) { self::$_session = new Zend_Session_Namespace($this->getName()); foreach (self::$_session as $namespace => $messages) { self::$_messages[$namespace] = $messages; unset(self::$_session->{$namespace}); } } } /** * postDispatch() - runs after action is dispatched, in this * case, it is resetting the namespace in case we have forwarded to a different * action, Flashmessage will be 'clean' (default namespace) * * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function postDispatch() { $this->resetNamespace(); return $this; } /** * setNamespace() - change the namespace messages are added to, useful for * per action controller messaging between requests * * @param string $namespace * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function setNamespace($namespace = 'default') { $this->_namespace = $namespace; return $this; } /** * resetNamespace() - reset the namespace to the default * * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function resetNamespace() { $this->setNamespace(); return $this; } /** * addMessage() - Add a message to flash message * * @param string $message * @return Zend_Controller_Action_Helper_FlashMessenger Provides a fluent interface */ public function addMessage($message) { if (self::$_messageAdded === false) { self::$_session->setExpirationHops(1, null, true); } if (!is_array(self::$_session->{$this->_namespace})) { self::$_session->{$this->_namespace} = array(); } self::$_session->{$this->_namespace}[] = $message; return $this; } /** * hasMessages() - Wether a specific namespace has messages * * @return boolean */ public function hasMessages() { return isset(self::$_messages[$this->_namespace]); } /** * getMessages() - Get messages from a specific namespace * * @return array */ public function getMessages() { if ($this->hasMessages()) { return self::$_messages[$this->_namespace]; } return array(); } /** * Clear all messages from the previous request & current namespace * * @return boolean True if messages were cleared, false if none existed */ public function clearMessages() { if ($this->hasMessages()) { unset(self::$_messages[$this->_namespace]); return true; } return false; } /** * hasCurrentMessages() - check to see if messages have been added to current * namespace within this request * * @return boolean */ public function hasCurrentMessages() { return isset(self::$_session->{$this->_namespace}); } /** * getCurrentMessages() - get messages that have been added to the current * namespace within this request * * @return array */ public function getCurrentMessages() { if ($this->hasCurrentMessages()) { return self::$_session->{$this->_namespace}; } return array(); } /** * clear messages from the current request & current namespace * * @return boolean */ public function clearCurrentMessages() { if ($this->hasCurrentMessages()) { unset(self::$_session->{$this->_namespace}); return true; } return false; } /** * getIterator() - complete the IteratorAggregate interface, for iterating * * @return ArrayObject */ public function getIterator() { if ($this->hasMessages()) { return new ArrayObject($this->getMessages()); } return new ArrayObject(); } /** * count() - Complete the countable interface * * @return int */ public function count() { if ($this->hasMessages()) { return count($this->getMessages()); } return 0; } /** * Strategy pattern: proxy to addMessage() * * @param string $message * @return void */ public function direct($message) { return $this->addMessage($message); } }
culturagovbr/portal-vale-cultura
projeto/library/Zend/Controller/Action/Helper/FlashMessengerType.php
PHP
gpl-3.0
6,914
#exploderLightPanel{ position: absolute; width: 90%; margin-left: 5%; height: 90%; margin-top: 5%; background-color: white; z-index: 999; padding: 2em; } .level{ }
foundry196-web/triage
Test Extensions/HTML Exploder/exploder.css
CSS
gpl-3.0
186
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## */ $language_array = Array( /* do not edit above this line */ 'author'=>'Auteur', 'bbcode'=>'BBCode is <b><u>AAN</u></b>', 'cancel'=>'annuleren', 'comm'=>'reactie', 'comment'=>'<a href="$url">[1] reactie</a>, laatst door $lastposter - $lastdate', 'comments'=>'<a href="$url">[$anzcomments] reacties</a>, laatst door $lastposter - $lastdate', 'date'=>'Datum', 'delete'=>'verwijder', 'delete_selected'=>'verwijder geselecteerden', 'edit'=>'bewerk', 'enter_title'=>'Je moet een titel invullen!', 'enter_text'=>'Je moet tekst invullen', 'go'=>'Ga!', 'headline'=>'Titel', 'html'=>'HTML is <b><u>AAN</u></b>', 'intern'=>'intern', 'languages'=>'Talen', 'link'=>'Link', 'links'=>'Links', 'new_post'=>'Nieuw Bericht', 'new_window'=>'nieuw venster', 'news'=>'Nieuws', 'news_archive'=>'Archief', 'no'=>'nee', 'no_access'=>'geen toegang', 'no_comment'=>'<a href="$url">geen reacties</a>', 'no_comments'=>'sta commentaar niet toe', 'no_topnews'=>'geen top nieuws', 'options'=>'opties', 'post_languages'=>'Nieuws in <select name="language_count" onchange="update_textarea(this.options[this.selectedIndex].value)">$selects</select> talen', 'post_news'=>'plaats nieuws', 'preview'=>'preview', 'publish_now'=>'plaats nu', 'publish_selected'=>'plaats geselecteerden', 'really_delete'=>'Dit Nieuws echt verwijderen?', 'rubric'=>'Rubriek', 'save_news'=>'opslaan', 'select_all'=>'selecteer allen', 'self'=>'zelf venster', 'show_news'=>'bekijk nieuws', 'smilies'=>'Smileys zijn <b><u>AAN</u></b>', 'sort'=>'Sorteer:', 'title_unpublished_news'=>'<h2>ONGEPUCLICEERD NIEUWS:</h2>', 'topnews'=>'top nieuws', 'unpublish'=>'onpubliceer', 'unpublish_selected'=>'onpubliceer geselecteerden', 'unpublished_news'=>'onpubliceer nieuws', 'upload_images'=>'upload afbeeldingen', 'user_comments'=>'sta gebruikers commentaar toe', 'view_more'=>'zie meer...', 'visitor_comments'=>'sta bezoekers commentaar toe', 'written_by'=>'geschreven door', 'yes'=>'ja' ); ?>
webSPELL/webSPELL
languages/nl/news.php
PHP
gpl-3.0
3,801
package com.ouser.module; import java.util.HashMap; import java.util.Map; import com.ouser.util.StringUtil; import android.os.Bundle; /** * 照片 * @author hanlixin * */ public class Photo { public enum Size { Small(80, 0), /** 小列表,菜单 */ Normal(100, 1), /** profile */ Large(134, 2), /** 大列表 */ XLarge(640, 3); /** 大图 */ private int size = 0; private int key = 0; Size(int size, int key) { this.size = size; this.key = key; } public int getSize() { return size; } int getKey() { return key; } static Size fromKey(int key) { for(Size s : Size.values()) { if(s.getKey() == key) { return s; } } return null; } } private String url = ""; private int resId = 0; private Map<Size, String> paths = new HashMap<Size, String>(); private Map<Size, Integer> tryTimes = new HashMap<Size, Integer>(); public String getUrl() { return url; } public void setUrl(String url) { this.url = url; this.tryTimes.clear(); } public int getResId() { return resId; } public void setResId(int res) { this.resId = res; } public void setPath(String path, Size size) { paths.put(size, path); } public String getPath(Size size) { if(paths.containsKey(size)) { return paths.get(size); } return ""; } public void setTryTime(int value, Size size) { tryTimes.put(size, value); } public int getTryTime(Size size) { if(tryTimes.containsKey(size)) { return tryTimes.get(size); } return 0; } public boolean isEmpty() { return StringUtil.isEmpty(url) && resId == 0; } public boolean isSame(Photo p) { return p.url.equals(this.url) || ( this.resId != 0 && p.resId == this.resId); } public Bundle toBundle() { StringBuilder sbPath = new StringBuilder(); for(Map.Entry<Size, String> entry : paths.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } StringBuilder sbTryTime = new StringBuilder(); for(Map.Entry<Size, Integer> entry : tryTimes.entrySet()) { sbPath.append(entry.getKey().getKey()).append(":").append(entry.getValue()).append(";"); } Bundle bundle = new Bundle(); bundle.putString("url", url); bundle.putInt("resid", resId); bundle.putString("path", sbPath.toString()); bundle.putString("trytime", sbTryTime.toString()); return bundle; } public void fromBundle(Bundle bundle) { url = bundle.getString("url"); resId = bundle.getInt("resid"); String strPath = bundle.getString("path"); String strTryTime = bundle.getString("trytime"); this.paths.clear(); for(String str : strPath.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.paths.put(Size.fromKey(Integer.parseInt(values[0])), values[1]); } this.tryTimes.clear(); for(String str : strTryTime.split(";")) { if("".equals(str)) { continue; } String[] values = str.split(":"); this.tryTimes.put(Size.fromKey(Integer.parseInt(values[0])), Integer.parseInt(values[1])); } } }
tassadar2002/ouser
src/com/ouser/module/Photo.java
Java
gpl-3.0
3,179
package bdv.server; import bdv.db.UserController; import bdv.model.DataSet; import bdv.util.Render; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.ContextHandlerCollection; import org.eclipse.jetty.util.log.Log; import org.stringtemplate.v4.ST; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STRawGroupDir; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.security.Principal; import java.util.List; import java.util.stream.Collectors; /** * Author: HongKee Moon ([email protected]), Scientific Computing Facility * Organization: MPI-CBG Dresden * Date: December 2016 */ public class UserPageHandler extends BaseContextHandler { private static final org.eclipse.jetty.util.log.Logger LOG = Log.getLogger( UserPageHandler.class ); UserPageHandler( final Server server, final ContextHandlerCollection publicDatasetHandlers, final ContextHandlerCollection privateDatasetHandlers, final String thumbnailsDirectoryName ) throws IOException, URISyntaxException { super( server, publicDatasetHandlers, privateDatasetHandlers, thumbnailsDirectoryName ); setContextPath( "/private/user/*" ); } @Override public void doHandle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response ) throws IOException, ServletException { // System.out.println(target); Principal principal = request.getUserPrincipal(); // System.out.println( principal.getName() ); if ( null == request.getQueryString() ) { list( baseRequest, response, principal.getName() ); } else { // System.out.println(request.getQueryString()); updateDataSet( baseRequest, request, response, principal.getName() ); } } private void updateDataSet( Request baseRequest, HttpServletRequest request, HttpServletResponse response, String userId ) throws IOException { final String op = request.getParameter( "op" ); if ( null != op ) { if ( op.equals( "addDS" ) ) { final String dataSetName = request.getParameter( "name" ); final String tags = request.getParameter( "tags" ); final String description = request.getParameter( "description" ); final String file = request.getParameter( "file" ); final boolean isPublic = Boolean.parseBoolean( request.getParameter( "public" ) ); // System.out.println( "name: " + dataSetName ); // System.out.println( "tags: " + tags ); // System.out.println( "description: " + description ); // System.out.println( "file: " + file ); // System.out.println( "isPublic: " + isPublic ); final DataSet ds = new DataSet( dataSetName, file, tags, description, isPublic ); // Add it the database UserController.addDataSet( userId, ds ); // Add new CellHandler depending on public property addDataSet( ds, baseRequest, response ); } else if ( op.equals( "removeDS" ) ) { final long dsId = Long.parseLong( request.getParameter( "dataset" ) ); // Remove it from the database UserController.removeDataSet( userId, dsId ); // Remove the CellHandler removeDataSet( dsId, baseRequest, response ); } else if ( op.equals( "updateDS" ) ) { // UpdateDS uses x-editable // Please, refer http://vitalets.github.io/x-editable/docs.html final String field = request.getParameter( "name" ); final long dataSetId = Long.parseLong( request.getParameter( "pk" ) ); final String value = request.getParameter( "value" ); // Update the database final DataSet ds = UserController.getDataSet( userId, dataSetId ); if ( field.equals( "dataSetName" ) ) { ds.setName( value ); } else if ( field.equals( "dataSetDescription" ) ) { ds.setDescription( value ); } // Update DataBase UserController.updateDataSet( userId, ds ); // Update the CellHandler updateHandler( ds, baseRequest, response ); // System.out.println( field + ":" + value ); } else if ( op.equals( "addTag" ) || op.equals( "removeTag" ) ) { processTag( op, baseRequest, request, response ); } else if ( op.equals( "setPublic" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final boolean checked = Boolean.parseBoolean( request.getParameter( "checked" ) ); final DataSet ds = UserController.getDataSet( userId, dataSetId ); ds.setPublic( checked ); UserController.updateDataSet( userId, ds ); ds.setPublic( !checked ); updateHandlerVisibility( ds, checked, baseRequest, response ); } else if ( op.equals( "addSharedUser" ) || op.equals( "removeSharedUser" ) ) { final long dataSetId = Long.parseLong( request.getParameter( "dataset" ) ); final String sharedUserId = request.getParameter( "userId" ); if ( op.equals( "addSharedUser" ) ) { // System.out.println("Add a shared user"); UserController.addReadableSharedUser( userId, dataSetId, sharedUserId ); } else if ( op.equals( "removeSharedUser" ) ) { // System.out.println("Remove the shared user"); UserController.removeReadableSharedUser( userId, dataSetId, sharedUserId ); } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); ow.write( "Success: " ); ow.close(); } } } private void updateHandlerVisibility( DataSet ds, boolean newVisibility, Request baseRequest, HttpServletResponse response ) throws IOException { String dsName = ds.getName(); boolean ret = removeCellHandler( ds.getIndex() ); if ( ret ) { ds.setPublic( newVisibility ); final boolean isPublic = newVisibility; final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); ret = false; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is removed." ); } else { ow.write( "Error: " + dsName + " cannot be removed." ); } ow.close(); } private void updateHandler( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; String dsName = ""; for ( final Handler handler : server.getChildHandlersByClass( CellHandler.class ) ) { final CellHandler contextHandler = ( CellHandler ) handler; if ( contextHandler.getDataSet().getIndex() == ds.getIndex() ) { final DataSet dataSet = contextHandler.getDataSet(); dataSet.setName( ds.getName() ); dataSet.setDescription( ds.getDescription() ); ret = true; dsName = ds.getName(); break; } } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsName + " is updated." ); } else { ow.write( "Error: " + dsName + " cannot be updated." ); } ow.close(); } private void removeDataSet( long dsId, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = removeCellHandler( dsId ); response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) { ow.write( "Success: " + dsId + " is removed." ); } else { ow.write( "Error: " + dsId + " cannot be removed." ); } ow.close(); } private void addDataSet( DataSet ds, Request baseRequest, HttpServletResponse response ) throws IOException { boolean ret = false; if ( !ds.getXmlPath().isEmpty() && !ds.getName().isEmpty() ) { final boolean isPublic = ds.isPublic(); final String context = "/" + ( isPublic ? Constants.PUBLIC_DATASET_CONTEXT_NAME : Constants.PRIVATE_DATASET_CONTEXT_NAME ) + "/id/" + ds.getIndex(); LOG.info( "Add new context: " + ds.getName() + " on " + context ); CellHandler ctx = getCellHandler( ds, isPublic, context ); ctx.setContextPath( context ); try { ctx.start(); } catch ( Exception e ) { LOG.warn( "Failed to start CellHandler", e ); e.printStackTrace(); } ret = true; } response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); if ( ret ) ow.write( "Success: " + ds.getName() + " is added." ); else ow.write( "Error: " + ds.getName() + " cannot be added." ); ow.close(); } private void list( final Request baseRequest, final HttpServletResponse response, final String userId ) throws IOException { response.setContentType( "text/html" ); response.setStatus( HttpServletResponse.SC_OK ); baseRequest.setHandled( true ); final PrintWriter ow = response.getWriter(); getHtmlDatasetList( ow, userId ); ow.close(); } private void getHtmlDatasetList( final PrintWriter out, final String userId ) throws IOException { final List< DataSet >[] dataSets = UserController.getDataSets( userId ); final List< DataSet > myDataSetList = dataSets[ 0 ]; final List< DataSet > sharedDataSetList = dataSets[ 1 ]; final STGroup g = new STRawGroupDir( "templates", '$', '$' ); final ST userPage = g.getInstanceOf( "userPage" ); final STGroup g2 = new STRawGroupDir( "templates", '~', '~' ); final ST userPageJS = g2.getInstanceOf( "userPageJS" ); final StringBuilder dsString = new StringBuilder(); for ( DataSet ds : myDataSetList ) { StringBuilder sharedUserString = new StringBuilder(); final ST dataSetTr = g.getInstanceOf( "privateDataSetTr" ); for ( String sharedUser : ds.getSharedUsers() ) { final ST userToBeRemoved = g.getInstanceOf( "userToBeRemoved" ); userToBeRemoved.add( "dataSetId", ds.getIndex() ); userToBeRemoved.add( "sharedUserId", sharedUser ); sharedUserString.append( userToBeRemoved.render() ); } if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", ds.getTags().stream().collect( Collectors.joining( "," ) ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", sharedUserString.toString() ); dsString.append( dataSetTr.render() ); } if ( sharedDataSetList != null ) { for ( DataSet ds : sharedDataSetList ) { final ST dataSetTr = g.getInstanceOf( "sharedDataSetTr" ); if ( ds.getDatasetUrl() == null ) { // Setup the dataset url if ( ds.isPublic() ) { ds.setDatasetUrl( "/" + Constants.PUBLIC_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } else { ds.setDatasetUrl( "/" + Constants.PRIVATE_DATASET_CONTEXT_NAME + "/id/" + ds.getIndex() + "/" ); } } dataSetTr.add( "thumbnailUrl", ds.getThumbnailUrl() ); dataSetTr.add( "dataSetId", ds.getIndex() ); dataSetTr.add( "dataSetTags", Render.createTagsLabel( ds ) ); dataSetTr.add( "dataSetName", ds.getName() ); dataSetTr.add( "dataSetDescription", ds.getDescription() ); dataSetTr.add( "dataSetLocation", ds.getXmlPath() ); String url = ds.getDatasetUrl(); if ( url.endsWith( "/" ) ) url = url.substring( 0, url.lastIndexOf( "/" ) ); dataSetTr.add( "dataSetUrl", url ); dataSetTr.add( "dataSetIsPublic", ds.isPublic() ); dataSetTr.add( "sharedUsers", ds.getOwner() ); dsString.append( dataSetTr.render() ); } } userPage.add( "userId", userId ); userPage.add( "dataSetTr", dsString.toString() ); userPage.add( "JS", userPageJS.render() ); out.write( userPage.render() ); out.close(); } }
hkmoon/bigdataviewer-server
src/main/java/bdv/server/UserPageHandler.java
Java
gpl-3.0
13,172
/* * Copyright 2006, 2007 Alessandro Chiari. * * This file is part of BrewPlus. * * BrewPlus 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. * * BrewPlus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPlus; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package jmash; import jmash.interfaces.XmlAble; import org.apache.log4j.Logger; import org.jdom.Element; /** * * @author Alessandro */ public class YeastType implements XmlAble { private static Logger LOGGER = Logger.getLogger(YeastType.class); /** Creates a new instance of YeastType */ public YeastType() { } private String nome; private String codice; private String produttore; private String forma; private String categoria; private String descrizione; private String attenuazioneMed; private String attenuazioneMin; private String attenuazioneMax; private String temperaturaMin; private String temperaturaMax; private String temperaturaMaxFerm; private static String campiXml[] = { "nome", "codice", "produttore", "forma", "categoria", "attenuazioneMed", "attenuazioneMin", "attenuazioneMax", "temperaturaMin", "temperaturaMax", "descrizione"}; public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public String getCodice() { return this.codice; } public void setCodice(String codice) { this.codice = codice; } public String getProduttore() { return this.produttore; } public void setProduttore(String produttore) { this.produttore = produttore; } public String getForma() { return this.forma; } public void setForma(String forma) { this.forma = forma; } public String getCategoria() { return this.categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public String getAttenuazioneMin() { return this.attenuazioneMin; } public void setAttenuazioneMin(String attenuazioneMin) { this.attenuazioneMin = attenuazioneMin; } public String getAttenuazioneMax() { return this.attenuazioneMax; } public void setAttenuazioneMax(String attenuazioneMax) { this.attenuazioneMax = attenuazioneMax; } public String getTemperaturaMin() { return this.temperaturaMin; } public void setTemperaturaMin(String temperaturaMin) { this.temperaturaMin = temperaturaMin; } public String getTemperaturaMax() { return this.temperaturaMax; } public void setTemperaturaMax(String temperaturaMax) { this.temperaturaMax = temperaturaMax; } public String getAttenuazioneMed() { if (attenuazioneMed != null && !"".equals(attenuazioneMed)) { return this.attenuazioneMed; } else if (getAttenuazioneMin() != null && !"".equals(getAttenuazioneMin()) && getAttenuazioneMax() != null && !"".equals(getAttenuazioneMax())) { return (String.valueOf((Integer.valueOf(getAttenuazioneMin())+Integer.valueOf(getAttenuazioneMax()))/2)); } return this.attenuazioneMed; } public void setAttenuazioneMed(String attenuazioneMed) { this.attenuazioneMed = attenuazioneMed; } public String getTemperaturaMaxFerm() { return temperaturaMaxFerm; } public void setTemperaturaMaxFerm(String temperaturaMaxFerm) { this.temperaturaMaxFerm = temperaturaMaxFerm; } public static String[] getCampiXml() { return campiXml; } public static void setCampiXml(String[] aCampiXml) { campiXml = aCampiXml; } @Override public Element toXml() { try { return Utils.toXml(this, campiXml); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } return null; } @Override public String getTag() { return "yeasts"; } @Override public String[] getXmlFields() { return campiXml; } }
rekhyt75/BrewPlus-IFDB
brewplus/brewplus-ifdb/src/main/java/jmash/YeastType.java
Java
gpl-3.0
4,355
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>FastaPlus: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">FastaPlus &#160;<span id="projectnumber">0.01</span> </div> <div id="projectbrief">by Robert Bakaric</div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacefasta.html">fasta</a> </li> <li class="navelem"><a class="el" href="classfasta_1_1XnuScores.html">XnuScores</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <div class="title">fasta::XnuScores Member List</div> </div> </div><!--header--> <div class="contents"> This is the complete list of members for <a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a>, including all inherited members.<table> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#aee0be2c87cc3d73aa25a37ea14c27c94">Alphabet</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a05dbb507f32b777d8cf5fb258b7332e5">Blast</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#aae61ad59c699d17788ebdc9f8fe0ad0f">Dayhoff</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a596b08d1891b73acfdd04fd2d2f6ebd6">Lambda120</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a9f671bdc8bb39683ddc8f3aa22e0fae3">Lambda250</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a3dce3b13d85b3d638ac4d10c24a4a65b">Lambda60</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a8034e6cbcd828e4d70b37741af985468">M</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a28615d4d2423e18aba59582e63f47ea2">Pam120</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a74d39ed5e0f4686b64f817b7fefca6bf">Pam250</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#adf657d46e889bc4047e634615c4918b0">Pam60</a></td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [protected]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#ad8583a13daf5fa32a64794eae87de201">XnuScores</a>()</td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [inline]</code></td></tr> <tr class="memlist"><td><a class="el" href="classfasta_1_1XnuScores.html#a9361babb4dd827117c55cb61dfee9553">~XnuScores</a>()</td><td><a class="el" href="classfasta_1_1XnuScores.html">fasta::XnuScores</a></td><td><code> [inline]</code></td></tr> </table></div><!-- contents --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Variables</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small> Generated on Mon Nov 9 2015 20:13:47 for FastaPlus by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
RobertBakaric/FastaPlus
doc/doxy/html/classfasta_1_1XnuScores-members.html
HTML
gpl-3.0
7,921
/* * Copyright 2016 The Chromium OS 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 "cros_gralloc_helpers.h" #include <cstdlib> #include <cutils/log.h> #include <fcntl.h> #include <xf86drm.h> uint64_t cros_gralloc_convert_flags(int flags) { uint64_t usage = DRV_BO_USE_NONE; if (flags & GRALLOC_USAGE_CURSOR) usage |= DRV_BO_USE_CURSOR; if ((flags & sw_read()) == GRALLOC_USAGE_SW_READ_RARELY) usage |= DRV_BO_USE_SW_READ_RARELY; if ((flags & sw_read()) == GRALLOC_USAGE_SW_READ_OFTEN) usage |= DRV_BO_USE_SW_READ_OFTEN; if ((flags & sw_write()) == GRALLOC_USAGE_SW_WRITE_RARELY) usage |= DRV_BO_USE_SW_WRITE_RARELY; if ((flags & sw_write()) == GRALLOC_USAGE_SW_WRITE_OFTEN) usage |= DRV_BO_USE_SW_WRITE_OFTEN; if (flags & GRALLOC_USAGE_HW_TEXTURE) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_RENDER) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_2D) usage |= DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_COMPOSER) /* HWC wants to use display hardware, but can defer to OpenGL. */ usage |= DRV_BO_USE_SCANOUT | DRV_BO_USE_RENDERING; if (flags & GRALLOC_USAGE_HW_FB) usage |= DRV_BO_USE_SCANOUT; if (flags & GRALLOC_USAGE_EXTERNAL_DISP) /* We're ignoring this flag until we decide what to with display link */ usage |= DRV_BO_USE_NONE; if (flags & GRALLOC_USAGE_PROTECTED) usage |= DRV_BO_USE_PROTECTED; if (flags & GRALLOC_USAGE_HW_VIDEO_ENCODER) /*HACK: See b/30054495 */ usage |= DRV_BO_USE_SW_READ_OFTEN; if (flags & GRALLOC_USAGE_HW_CAMERA_WRITE) usage |= DRV_BO_USE_HW_CAMERA_WRITE; if (flags & GRALLOC_USAGE_HW_CAMERA_READ) usage |= DRV_BO_USE_HW_CAMERA_READ; if (flags & GRALLOC_USAGE_HW_CAMERA_ZSL) usage |= DRV_BO_USE_HW_CAMERA_ZSL; if (flags & GRALLOC_USAGE_RENDERSCRIPT) usage |= DRV_BO_USE_RENDERSCRIPT; return usage; } drv_format_t cros_gralloc_convert_format(int format) { /* * Conversion from HAL to fourcc-based DRV formats based on * platform_android.c in mesa. */ switch (format) { case HAL_PIXEL_FORMAT_BGRA_8888: return DRV_FORMAT_ARGB8888; case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED: return DRV_FORMAT_FLEX_IMPLEMENTATION_DEFINED; case HAL_PIXEL_FORMAT_RGB_565: return DRV_FORMAT_RGB565; case HAL_PIXEL_FORMAT_RGB_888: return DRV_FORMAT_RGB888; case HAL_PIXEL_FORMAT_RGBA_8888: return DRV_FORMAT_ABGR8888; case HAL_PIXEL_FORMAT_RGBX_8888: return DRV_FORMAT_XBGR8888; case HAL_PIXEL_FORMAT_YCbCr_420_888: return DRV_FORMAT_FLEX_YCbCr_420_888; case HAL_PIXEL_FORMAT_YV12: return DRV_FORMAT_YVU420; } return DRV_FORMAT_NONE; } static int32_t cros_gralloc_query_rendernode(struct driver **drv, const char *name) { /* TODO(gsingh): Enable render nodes on udl/evdi. */ int fd; drmVersionPtr version; char const *str = "%s/renderD%d"; int32_t num_nodes = 63; int32_t min_node = 128; int32_t max_node = (min_node + num_nodes); for (int i = min_node; i < max_node; i++) { char *node; if (asprintf(&node, str, DRM_DIR_NAME, i) < 0) continue; fd = open(node, O_RDWR, 0); free(node); if (fd < 0) continue; version = drmGetVersion(fd); if (version && name && !strcmp(version->name, name)) { drmFreeVersion(version); continue; } drmFreeVersion(version); *drv = drv_create(fd); if (*drv) return CROS_GRALLOC_ERROR_NONE; } return CROS_GRALLOC_ERROR_NO_RESOURCES; } int32_t cros_gralloc_rendernode_open(struct driver **drv) { int32_t ret; ret = cros_gralloc_query_rendernode(drv, NULL); /* Look for vgem driver if no hardware is found. */ if (ret) ret = cros_gralloc_query_rendernode(drv, "vgem"); return ret; } int32_t cros_gralloc_validate_handle(struct cros_gralloc_handle *hnd) { if (!hnd || hnd->magic != cros_gralloc_magic()) return CROS_GRALLOC_ERROR_BAD_HANDLE; return CROS_GRALLOC_ERROR_NONE; } void cros_gralloc_log(const char *prefix, const char *file, int line, const char *format, ...) { va_list args; va_start(args, format); ALOGE("%s - [%s(%d)]", prefix, basename(file), line); __android_log_vprint(ANDROID_LOG_ERROR, prefix, format, args); va_end(args); }
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/minigbm/src/cros_gralloc/cros_gralloc_helpers.cc
C++
gpl-3.0
4,210
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component, PropTypes } from 'react'; import { observer } from 'mobx-react'; import { Button, GasPriceEditor } from '~/ui'; import TransactionMainDetails from '../TransactionMainDetails'; import TransactionPendingForm from '../TransactionPendingForm'; import styles from './transactionPending.css'; import * as tUtil from '../util/transaction'; @observer export default class TransactionPending extends Component { static contextTypes = { api: PropTypes.object.isRequired }; static propTypes = { className: PropTypes.string, date: PropTypes.instanceOf(Date).isRequired, focus: PropTypes.bool, gasLimit: PropTypes.object, id: PropTypes.object.isRequired, isSending: PropTypes.bool.isRequired, isTest: PropTypes.bool.isRequired, nonce: PropTypes.number, onConfirm: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, store: PropTypes.object.isRequired, transaction: PropTypes.shape({ data: PropTypes.string, from: PropTypes.string.isRequired, gas: PropTypes.object.isRequired, gasPrice: PropTypes.object.isRequired, to: PropTypes.string, value: PropTypes.object.isRequired }).isRequired }; static defaultProps = { focus: false }; gasStore = new GasPriceEditor.Store(this.context.api, { gas: this.props.transaction.gas.toFixed(), gasLimit: this.props.gasLimit, gasPrice: this.props.transaction.gasPrice.toFixed() }); componentWillMount () { const { store, transaction } = this.props; const { from, gas, gasPrice, to, value } = transaction; const fee = tUtil.getFee(gas, gasPrice); // BigNumber object const gasPriceEthmDisplay = tUtil.getEthmFromWeiDisplay(gasPrice); const gasToDisplay = tUtil.getGasDisplay(gas); const totalValue = tUtil.getTotalValue(fee, value); this.setState({ gasPriceEthmDisplay, totalValue, gasToDisplay }); this.gasStore.setEthValue(value); store.fetchBalances([from, to]); } render () { return this.gasStore.isEditing ? this.renderGasEditor() : this.renderTransaction(); } renderTransaction () { const { className, focus, id, isSending, isTest, store, transaction } = this.props; const { totalValue } = this.state; const { from, value } = transaction; const fromBalance = store.balances[from]; return ( <div className={ `${styles.container} ${className}` }> <TransactionMainDetails className={ styles.transactionDetails } from={ from } fromBalance={ fromBalance } gasStore={ this.gasStore } id={ id } isTest={ isTest } totalValue={ totalValue } transaction={ transaction } value={ value } /> <TransactionPendingForm address={ from } focus={ focus } isSending={ isSending } onConfirm={ this.onConfirm } onReject={ this.onReject } /> </div> ); } renderGasEditor () { const { className } = this.props; return ( <div className={ `${styles.container} ${className}` }> <GasPriceEditor store={ this.gasStore }> <Button label='view transaction' onClick={ this.toggleGasEditor } /> </GasPriceEditor> </div> ); } onConfirm = (data) => { const { id, transaction } = this.props; const { password, wallet } = data; const { gas, gasPrice } = this.gasStore.overrideTransaction(transaction); this.props.onConfirm({ gas, gasPrice, id, password, wallet }); } onReject = () => { this.props.onReject(this.props.id); } toggleGasEditor = () => { this.gasStore.setEditing(false); } }
jesuscript/parity
js/src/views/Signer/components/TransactionPending/transactionPending.js
JavaScript
gpl-3.0
4,499
from controllers.job_ctrl import JobController from models.job_model import JobModel from views.job_view import JobView class MainController(object): def __init__(self, main_model): self.main_view = None self.main_model = main_model self.main_model.begin_job_fetch.connect(self.on_begin_job_fetch) self.main_model.update_job_fetch_progress.connect(self.on_job_fetch_update) self.main_model.fetched_job.connect(self.on_fetched_job) def init_ui(self, main_view): self.main_view = main_view self.init_hotkeys() def init_hotkeys(self): self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "J"], self.main_view.focus_job_num_edit) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "O"], self.main_view.open_current_job_folder) self.main_model.hotkey_model.add_hotkey(["Lcontrol", "Lmenu", "B"], self.main_view.open_current_job_basecamp) self.main_model.hotkey_model.start_detection() def fetch_job(self): job_num = self.main_view.job_num if self.main_model.job_exists(job_num): self.main_view.show_job_already_exists_dialog() return self.main_model.fetch_job(job_num) def cancel_job_fetch(self): self.main_model.cancel_job_fetch() def on_begin_job_fetch(self, max): self.main_view.show_job_fetch_progress_dialog(max) def on_job_fetch_update(self, progress): self.main_view.update_job_fetch_progress_dialog(progress) def on_fetched_job(self, job_num, base_folder): job = JobModel(job_num, base_folder, self.main_model.settings_model.basecamp_email, self.main_model.settings_model.basecamp_password, self.main_model.settings_model.google_maps_js_api_key, self.main_model.settings_model.google_maps_static_api_key, self.main_model.settings_model.google_earth_exe_path, self.main_model.settings_model.scene_exe_path) self.main_model.jobs[job.job_num] = job found = bool(job.base_folder) self.main_view.close_job_fetch_progress_dialog() if not found: open_anyway = self.main_view.show_job_not_found_dialog() if not open_anyway: return job_view = JobView(JobController(job)) job_view.request_minimize.connect(self.main_view.close) self.main_view.add_tab(job_view, job.job_name) def remove_job(self, index): job_num = int(self.main_view.ui.jobs_tab_widget.tabText(index)[1:]) self.main_model.jobs.pop(job_num, None) self.main_view.remove_tab(index)
redline-forensics/auto-dm
controllers/main_ctrl.py
Python
gpl-3.0
2,757
<?php namespace ModulusAcl\Form; use ModulusForm\Form\FormDefault, Zend\Form\Element\Select; class Route extends FormDefault { public function addElements() { $this->add(array( 'name' => 'id', 'options' => array( 'label' => '', ), 'attributes' => array( 'type' => 'hidden' ), )); $this->add(array( 'name' => 'route', 'options' => array( 'label' => 'Rota: ', 'value_options' => array( ), ), 'type' => 'Zend\Form\Element\Select', 'attributes' => array( 'placeholder' => 'Selecione a url', ), )); $this->add(array( 'name' => 'displayName', 'options' => array( 'label' => 'Nome de exibição: ', ), 'type' => 'Zend\Form\Element\Text', 'attributes' => array( 'placeholder' => 'Entre com o nome', ), )); $this->add(array( 'type' => 'DoctrineModule\Form\Element\ObjectSelect', 'name' => 'role', 'options' => array( 'label' => 'Tipo de usuário: ', 'object_manager' => $this->getEntityManager(), 'target_class' => 'ModulusAcl\Entity\AclRole', 'find_method' => array( 'name' => 'findByActives', 'params' => array('criteria' => array()), ), 'property' => 'name', 'selected' =>1, 'empty_option' => '', ), )); $this->add(array( 'type' => 'ModulusForm\Form\Element\Toggle', 'name' => 'doLog', 'options' => array( 'label' => 'Log ao acessar? ', ), )); $this->add(new \Zend\Form\Element\Csrf('security')); $this->add(array( 'name' => 'submit', 'attributes' => array( 'value' => 'Salvar', 'type' => 'submit', 'class' => 'btn btn-primary', ), )); } }
ZF2-Modulus/ModulusAcl
src/ModulusAcl/Form/Route.php
PHP
gpl-3.0
2,291
package edu.stanford.nlp.mt.lm; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import edu.stanford.nlp.mt.util.IString; import edu.stanford.nlp.mt.util.Sequence; import edu.stanford.nlp.mt.util.TokenUtils; import edu.stanford.nlp.mt.util.Vocabulary; /** * KenLM language model support via JNI. * * @author daniel cer * @author Spence Green * @author Kenneth Heafield * */ public class KenLanguageModel implements LanguageModel<IString> { private static final Logger logger = LogManager.getLogger(KenLanguageModel.class.getName()); private static final int[] EMPTY_INT_ARRAY = new int[0]; private static final KenLMState ZERO_LENGTH_STATE = new KenLMState(0.0f, EMPTY_INT_ARRAY, 0); public static final String KENLM_LIBRARY_NAME = "PhrasalKenLM"; static { try { System.loadLibrary(KENLM_LIBRARY_NAME); logger.info("Loaded KenLM JNI library."); } catch (java.lang.UnsatisfiedLinkError e) { logger.fatal("KenLM has not been compiled!", e); System.exit(-1); } } private final KenLM model; private final String name; private AtomicReference<int[]> istringIdToKenLMId; private final ReentrantLock preventDuplicateWork = new ReentrantLock(); /** * Constructor for multi-threaded queries. * * @param filename */ public KenLanguageModel(String filename) { model = new KenLM(filename); name = String.format("KenLM(%s)", filename); initializeIdTable(); } /** * Create the mapping between IString word ids and KenLM word ids. */ private void initializeIdTable() { // Don't remove this line!! Sanity check to make sure that start and end load before // building the index. logger.info("Special tokens: start: {} end: {}", TokenUtils.START_TOKEN, TokenUtils.END_TOKEN); int[] table = new int[Vocabulary.systemSize()]; for (int i = 0; i < table.length; ++i) { table[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId = new AtomicReference<int[]>(table); } /** * Maps the IString id to a kenLM id. If the IString * id is out of range, update the vocab mapping. * @param token * @return kenlm id of the string */ private int toKenLMId(IString token) { { int[] map = istringIdToKenLMId.get(); if (token.id < map.length) { return map[token.id]; } } // Rare event: we have to expand the vocabulary. // In principle, this doesn't need to be a lock, but it does // prevent unnecessary work duplication. if (preventDuplicateWork.tryLock()) { // This thread is responsible for updating the mapping. try { // Maybe another thread did the work for us? int[] oldTable = istringIdToKenLMId.get(); if (token.id < oldTable.length) { return oldTable[token.id]; } int[] newTable = new int[Vocabulary.systemSize()]; System.arraycopy(oldTable, 0, newTable, 0, oldTable.length); for (int i = oldTable.length; i < newTable.length; ++i) { newTable[i] = model.index(Vocabulary.systemGet(i)); } istringIdToKenLMId.set(newTable); return newTable[token.id]; } finally { preventDuplicateWork.unlock(); } } // Another thread is working. Lookup directly. return model.index(token.toString()); } @Override public IString getStartToken() { return TokenUtils.START_TOKEN; } @Override public IString getEndToken() { return TokenUtils.END_TOKEN; } @Override public String getName() { return name; } @Override public int order() { return model.order(); } @Override public LMState score(Sequence<IString> sequence, int startIndex, LMState priorState) { if (sequence.size() == 0) { // Source deletion rule return priorState == null ? ZERO_LENGTH_STATE : priorState; } // Extract prior state final int[] state = priorState == null ? EMPTY_INT_ARRAY : ((KenLMState) priorState).getState(); final int[] ngramIds = makeKenLMInput(sequence, state); if (sequence.size() == 1 && priorState == null && sequence.get(0).equals(TokenUtils.START_TOKEN)) { // Special case: Source deletion rule (e.g., from the OOV model) at the start of a string assert ngramIds.length == 1; return new KenLMState(0.0f, ngramIds, ngramIds.length); } // Reverse the start index for KenLM final int kenLMStartIndex = ngramIds.length - state.length - startIndex - 1; assert kenLMStartIndex >= 0; // Execute the query (via JNI) and construct the return state final long got = model.scoreSeqMarshalled(ngramIds, kenLMStartIndex); return new KenLMState(KenLM.scoreFromMarshalled(got), ngramIds, KenLM.rightStateFromMarshalled(got)); } /** * Convert a Sequence and an optional state to an input for KenLM. * * @param sequence * @param priorState * @return */ private int[] makeKenLMInput(Sequence<IString> sequence, int[] priorState) { final int sequenceSize = sequence.size(); int[] ngramIds = new int[sequenceSize + priorState.length]; if (priorState.length > 0) { System.arraycopy(priorState, 0, ngramIds, sequenceSize, priorState.length); } for (int i = 0; i < sequenceSize; i++) { // Notice: ngramids are in reverse order vv. the Sequence ngramIds[sequenceSize-1-i] = toKenLMId(sequence.get(i)); } return ngramIds; } // TODO(spenceg) This never yielded an improvement.... // private static final int DEFAULT_CACHE_SIZE = 10000; // private static final ThreadLocal<KenLMCache> threadLocalCache = // new ThreadLocal<KenLMCache>(); // // private static class KenLMCache { // private final long[] keys; // private final long[] values; // private final int mask; // public KenLMCache(int size) { // this.keys = new long[size]; // this.values = new long[size]; // this.mask = size - 1; // } // // public Long get(int[] kenLMInput, int startIndex) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // return keys[k] == hashValue ? values[k] : null; // } // private int ideal(long hashed) { // return ((int)hashed) & mask; // } // public void insert(int[] kenLMInput, int startIndex, long value) { // long hashValue = MurmurHash2.hash64(kenLMInput, kenLMInput.length, startIndex); // int k = ideal(hashValue); // keys[k] = hashValue; // values[k] = value; // } // } }
Andy-Peng/phrasal
src/edu/stanford/nlp/mt/lm/KenLanguageModel.java
Java
gpl-3.0
6,706
// Decompiled with JetBrains decompiler // Type: System.Xml.Linq.BaseUriAnnotation // Assembly: System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: D3650A80-743D-4EFB-8926-AE790E9DB30F // Assembly location: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll namespace System.Xml.Linq { internal class BaseUriAnnotation { internal string baseUri; public BaseUriAnnotation(string baseUri) { this.baseUri = baseUri; } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Xml.Linq/System/Xml/Linq/BaseUriAnnotation.cs
C#
gpl-3.0
530
#!/usr/bin/python # # Problem: Making Chess Boards # Language: Python # Author: KirarinSnow # Usage: python thisfile.py <input.in >output.out from heapq import * def process(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: if g[i][j] == None: s[i][j] = 0 elif i == 0 or j == 0: s[i][j] = 1 elif g[i-1][j] != g[i][j] and g[i][j-1] != g[i][j] and \ g[i-1][j-1] == g[i][j]: s[i][j] = 1 + min(s[i-1][j], s[i][j-1], s[i-1][j-1]) else: s[i][j] = 1 heappush(q, (-s[i][j], i, j)) def clear(r1, r2, c1, c2): for i in range(r1, r2): for j in range(c1, c2): if 0 <= i < m and 0 <= j < n: g[i][j] = None for case in range(int(raw_input())): m, n = map(int, raw_input().split()) v = [eval('0x'+raw_input()) for i in range(m)] g = map(lambda x: map(lambda y: (x>>y)%2, range(n)[::-1]), v) s = [[1 for i in range(n)] for j in range(m)] q = [] process(0, m, 0, n) b = [] while q: x, r, c = heappop(q) if x != 0 and s[r][c] == -x: b.append((-x, r, c)) clear(r+x+1, r+1, c+x+1, c+1) process(r+x+1, r-x+1, c+x+1, c-x+1) vs = sorted(list(set(map(lambda x: x[0], b))))[::-1] print "Case #%d: %d" % (case+1, len(vs)) for k in vs: print k, len(filter(lambda x: x[0] == k, b))
KirarinSnow/Google-Code-Jam
Round 1C 2010/C.py
Python
gpl-3.0
1,627
package appalachia.rtg.world.biome.realistic.appalachia.adirondack; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import appalachia.api.AppalachiaBiomes; import rtg.api.config.BiomeConfig; import rtg.api.util.BlockUtil; import rtg.api.util.CliffCalculator; import rtg.api.util.noise.OpenSimplexNoise; import rtg.api.world.IRTGWorld; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; public class RealisticBiomeAPLAdirondackBeach extends RealisticBiomeAPLAdirondackBase { public static Biome biome = AppalachiaBiomes.adirondackBeach; public static Biome river = AppalachiaBiomes.adirondackRiver; public RealisticBiomeAPLAdirondackBeach() { super(biome, river); } @Override public void initConfig() { this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK_META).set(0); } @Override public TerrainBase initTerrain() { return new TerrainAPLAdirondackBeach(); } @Override public SurfaceBase initSurface() { return new SurfaceAPLAdirondackBeach(config, biome.topBlock, biome.fillerBlock, BlockUtil.getStateDirt(2), 12f, 0.27f); } public class SurfaceAPLAdirondackBeach extends SurfaceBase { protected IBlockState mixBlock; protected float width; protected float height; public SurfaceAPLAdirondackBeach(BiomeConfig config, IBlockState top, IBlockState filler, IBlockState mix, float mixWidth, float mixHeight) { super(config, top, filler); mixBlock = this.getConfigBlock(config.SURFACE_MIX_BLOCK.get(), config.SURFACE_MIX_BLOCK_META.get(), mix); width = mixWidth; height = mixHeight; } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, IRTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); OpenSimplexNoise simplex = rtgWorld.simplex(); float c = CliffCalculator.calc(x, z, noise); boolean cliff = c > 2.3f ? true : false; // 2.3f because higher thresholds result in fewer stone cliffs (more grassy cliffs) for (int k = 255; k > -1; k--) { Block b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (cliff) { if (depth > -1 && depth < 2) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble(rtgWorld, i, j, x, z, k)); } else { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else if (depth < 10) { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else { if (depth == 0 && k > 61) { if (simplex.noise2(i / width, j / width) > height) // > 0.27f, i / 12f { primer.setBlockState(x, k, z, mixBlock); } else { primer.setBlockState(x, k, z, topBlock); } } else if (depth < 4) { primer.setBlockState(x, k, z, fillerBlock); } } } } } } @Override public void initDecos() { } public class TerrainAPLAdirondackBeach extends TerrainBase { public TerrainAPLAdirondackBeach() { } @Override public float generateNoise(IRTGWorld rtgWorld, int x, int y, float border, float river) { return terrainBeach(x, y, rtgWorld.simplex(), river, 180f, 35f, 63f); } } }
Team-RTG/Appalachia
src/main/java/appalachia/rtg/world/biome/realistic/appalachia/adirondack/RealisticBiomeAPLAdirondackBeach.java
Java
gpl-3.0
4,464
// Decompiled with JetBrains decompiler // Type: System.Boolean // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 255ABCDF-D9D6-4E3D-BAD4-F74D4CE3D7A8 // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll using System.Runtime.InteropServices; namespace System { /// <summary> /// Represents a Boolean value. /// </summary> /// <filterpriority>1</filterpriority> [ComVisible(true)] [__DynamicallyInvokable] [Serializable] public struct Boolean : IComparable, IConvertible, IComparable<bool>, IEquatable<bool> { /// <summary> /// Represents the Boolean value true as a string. This field is read-only. /// </summary> /// <filterpriority>1</filterpriority> [__DynamicallyInvokable] public static readonly string TrueString = "True"; /// <summary> /// Represents the Boolean value false as a string. This field is read-only. /// </summary> /// <filterpriority>1</filterpriority> [__DynamicallyInvokable] public static readonly string FalseString = "False"; internal const int True = 1; internal const int False = 0; internal const string TrueLiteral = "True"; internal const string FalseLiteral = "False"; private bool m_value; /// <summary> /// Returns the hash code for this instance. /// </summary> /// /// <returns> /// A hash code for the current <see cref="T:System.Boolean"/>. /// </returns> /// <filterpriority>2</filterpriority> [__DynamicallyInvokable] public override int GetHashCode() { return !this ? 0 : 1; } /// <summary> /// Converts the value of this instance to its equivalent string representation (either "True" or "False"). /// </summary> /// /// <returns> /// <see cref="F:System.Boolean.TrueString"/> if the value of this instance is true, or <see cref="F:System.Boolean.FalseString"/> if the value of this instance is false. /// </returns> /// <filterpriority>2</filterpriority> [__DynamicallyInvokable] public override string ToString() { return !this ? "False" : "True"; } /// <summary> /// Converts the value of this instance to its equivalent string representation (either "True" or "False"). /// </summary> /// /// <returns> /// <see cref="F:System.Boolean.TrueString"/> if the value of this instance is true, or <see cref="F:System.Boolean.FalseString"/> if the value of this instance is false. /// </returns> /// <param name="provider">(Reserved) An <see cref="T:System.IFormatProvider"/> object. </param><filterpriority>2</filterpriority> public string ToString(IFormatProvider provider) { return !this ? "False" : "True"; } /// <summary> /// Returns a value indicating whether this instance is equal to a specified object. /// </summary> /// /// <returns> /// true if <paramref name="obj"/> is a <see cref="T:System.Boolean"/> and has the same value as this instance; otherwise, false. /// </returns> /// <param name="obj">An object to compare to this instance. </param><filterpriority>2</filterpriority> [__DynamicallyInvokable] public override bool Equals(object obj) { if (!(obj is bool)) return false; return this == (bool) obj; } /// <summary> /// Returns a value indicating whether this instance is equal to a specified <see cref="T:System.Boolean"/> object. /// </summary> /// /// <returns> /// true if <paramref name="obj"/> has the same value as this instance; otherwise, false. /// </returns> /// <param name="obj">A <see cref="T:System.Boolean"/> value to compare to this instance.</param><filterpriority>2</filterpriority> [__DynamicallyInvokable] public bool Equals(bool obj) { return this == obj; } /// <summary> /// Compares this instance to a specified object and returns an integer that indicates their relationship to one another. /// </summary> /// /// <returns> /// A signed integer that indicates the relative order of this instance and <paramref name="obj"/>.Return Value Condition Less than zero This instance is false and <paramref name="obj"/> is true. Zero This instance and <paramref name="obj"/> are equal (either both are true or both are false). Greater than zero This instance is true and <paramref name="obj"/> is false.-or- <paramref name="obj"/> is null. /// </returns> /// <param name="obj">An object to compare to this instance, or null. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not a <see cref="T:System.Boolean"/>. </exception><filterpriority>2</filterpriority> public int CompareTo(object obj) { if (obj == null) return 1; if (!(obj is bool)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeBoolean")); if (this == (bool) obj) return 0; return !this ? -1 : 1; } /// <summary> /// Compares this instance to a specified <see cref="T:System.Boolean"/> object and returns an integer that indicates their relationship to one another. /// </summary> /// /// <returns> /// A signed integer that indicates the relative values of this instance and <paramref name="value"/>.Return Value Condition Less than zero This instance is false and <paramref name="value"/> is true. Zero This instance and <paramref name="value"/> are equal (either both are true or both are false). Greater than zero This instance is true and <paramref name="value"/> is false. /// </returns> /// <param name="value">A <see cref="T:System.Boolean"/> object to compare to this instance. </param><filterpriority>2</filterpriority> [__DynamicallyInvokable] public int CompareTo(bool value) { if (this == value) return 0; return !this ? -1 : 1; } /// <summary> /// Converts the specified string representation of a logical value to its <see cref="T:System.Boolean"/> equivalent, or throws an exception if the string is not equivalent to the value of <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/>. /// </summary> /// /// <returns> /// true if <paramref name="value"/> is equivalent to the value of the <see cref="F:System.Boolean.TrueString"/> field; false if <paramref name="value"/> is equivalent to the value of the <see cref="F:System.Boolean.FalseString"/> field. /// </returns> /// <param name="value">A string containing the value to convert. </param><exception cref="T:System.ArgumentNullException"><paramref name="value"/> is null. </exception><exception cref="T:System.FormatException"><paramref name="value"/> is not equivalent to the value of the <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/> field. </exception><filterpriority>1</filterpriority> [__DynamicallyInvokable] public static bool Parse(string value) { if (value == null) throw new ArgumentNullException("value"); bool result = false; if (!bool.TryParse(value, out result)) throw new FormatException(Environment.GetResourceString("Format_BadBoolean")); return result; } /// <summary> /// Tries to convert the specified string representation of a logical value to its <see cref="T:System.Boolean"/> equivalent. A return value indicates whether the conversion succeeded or failed. /// </summary> /// /// <returns> /// true if <paramref name="value"/> was converted successfully; otherwise, false. /// </returns> /// <param name="value">A string containing the value to convert. </param><param name="result">When this method returns, if the conversion succeeded, contains true if <paramref name="value"/> is equivalent to <see cref="F:System.Boolean.TrueString"/> or false if <paramref name="value"/> is equivalent to <see cref="F:System.Boolean.FalseString"/>. If the conversion failed, contains false. The conversion fails if <paramref name="value"/> is null or is not equivalent to the value of either the <see cref="F:System.Boolean.TrueString"/> or <see cref="F:System.Boolean.FalseString"/> field.</param><filterpriority>1</filterpriority> [__DynamicallyInvokable] public static bool TryParse(string value, out bool result) { result = false; if (value == null) return false; if ("True".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if ("False".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = false; return true; } value = bool.TrimWhiteSpaceAndNull(value); if ("True".Equals(value, StringComparison.OrdinalIgnoreCase)) { result = true; return true; } if (!"False".Equals(value, StringComparison.OrdinalIgnoreCase)) return false; result = false; return true; } /// <summary> /// Returns the <see cref="T:System.TypeCode"/> for value type <see cref="T:System.Boolean"/>. /// </summary> /// /// <returns> /// The enumerated constant, <see cref="F:System.TypeCode.Boolean"/>. /// </returns> /// <filterpriority>2</filterpriority> public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return this; } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", (object) "Boolean", (object) "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", (object) "Boolean", (object) "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible) (bool) (this ? 1 : 0), type, provider); } private static string TrimWhiteSpaceAndNull(string value) { int startIndex = 0; int index = value.Length - 1; char ch = char.MinValue; while (startIndex < value.Length && (char.IsWhiteSpace(value[startIndex]) || (int) value[startIndex] == (int) ch)) ++startIndex; while (index >= startIndex && (char.IsWhiteSpace(value[index]) || (int) value[index] == (int) ch)) --index; return value.Substring(startIndex, index - startIndex + 1); } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/mscorlib/System/Boolean.cs
C#
gpl-3.0
11,794
/* * Copyright (c) 2010-2012 Matthias Klass, Johannes Leimer, * Rico Lieback, Sebastian Gabriel, Lothar Gesslein, * Alexander Rampp, Kai Weidner * * This file is part of the Physalix Enrollment System * * Foobar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Foobar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package hsa.awp.usergui; import hsa.awp.event.model.Event; import hsa.awp.event.model.Occurrence; import hsa.awp.user.model.SingleUser; import hsa.awp.user.model.User; import hsa.awp.usergui.controller.IUserGuiController; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; /** * Panel showing detailed information about an {@link Event}. * * @author klassm */ public class EventDetailPanel extends Panel { /** * unique serialization id. */ private static final long serialVersionUID = 9180564827437598145L; /** * GuiController which feeds the Gui with Data. */ @SpringBean(name = "usergui.controller") private transient IUserGuiController controller; /** * Constructor. * * @param id wicket:id. * @param event event to show. */ public EventDetailPanel(String id, Event event) { super(id); List<SingleUser> teachers = new LinkedList<SingleUser>(); event = controller.getEventById(event.getId()); for (Long teacherId : event.getTeachers()) { User user = controller.getUserById(teacherId); if (user != null && user instanceof SingleUser) { teachers.add((SingleUser) user); } } Collections.sort(teachers, new Comparator<SingleUser>() { @Override public int compare(SingleUser o1, SingleUser o2) { return o1.getName().compareTo(o2.getName()); } }); StringBuffer teachersList = new StringBuffer(); if (teachers.size() == 0) { teachersList.append("keine"); } else { boolean first = true; for (SingleUser teacher : teachers) { if (first) { first = false; } else { teachersList.append(", "); } teachersList.append(teacher.getName()); } } WebMarkupContainer eventGeneral = new WebMarkupContainer("event.general"); add(eventGeneral); eventGeneral.add(new Label("event.general.caption", "Allgemeines")); eventGeneral.add(new Label("event.general.eventId", new Model<Integer>(event.getEventId()))); eventGeneral.add(new Label("event.general.subjectName", new Model<String>(event.getSubject().getName()))); eventGeneral.add(new Label("event.general.maxParticipants", new Model<Integer>(event.getMaxParticipants()))); Label teacherLabel = new Label("event.general.teachers", new Model<String>(teachersList.toString())); eventGeneral.add(teacherLabel); eventGeneral.add(new Label("event.general.eventDescription", new Model<String>(event.getDetailInformation()))); ExternalLink detailLink = new ExternalLink("event.general.link", event.getSubject().getLink()); eventGeneral.add(detailLink); detailLink.add(new Label("event.general.linkDesc", event.getSubject().getLink())); String description = event.getSubject().getDescription(); if (description == null || ((description = description.trim().replace("\n", "<br>")).equals(""))) { description = "keine"; } Label subjectDescription = new Label("event.general.subjectDescription", new Model<String>(description)); subjectDescription.setEscapeModelStrings(false); eventGeneral.add(subjectDescription); WebMarkupContainer eventTimetable = new WebMarkupContainer("event.timetable"); add(eventTimetable); eventTimetable.add(new Label("event.timetable.caption", "Stundenplan")); List<Occurrence> occurences; if (event.getTimetable() == null) { occurences = new LinkedList<Occurrence>(); } else { occurences = new LinkedList<Occurrence>(event.getTimetable().getOccurrences()); } eventTimetable.add(new ListView<Occurrence>("event.timetable.list", occurences) { /** * unique serialization id. */ private static final long serialVersionUID = -1041971433878928045L; @Override protected void populateItem(ListItem<Occurrence> item) { DateFormat singleFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); DateFormat dayFormat = new SimpleDateFormat("EEEE"); DateFormat timeFormat = new SimpleDateFormat("HH:mm"); String s; switch (item.getModelObject().getType()) { case SINGLE: s = "Einzeltermin vom " + singleFormat.format(item.getModelObject().getStartDate().getTime()); s += " bis " + singleFormat.format(item.getModelObject().getEndDate().getTime()); break; case PERIODICAL: s = "Wöchentlich am " + dayFormat.format(item.getModelObject().getStartDate().getTime()); s += " von " + timeFormat.format(item.getModelObject().getStartDate().getTime()) + " bis " + timeFormat.format(item.getModelObject().getEndDate().getTime()); break; default: s = ""; } item.add(new Label("event.timetable.list.occurrence", s)); } }); if (occurences.size() == 0) { eventTimetable.setVisible(false); } } }
physalix-enrollment/physalix
UserGui/src/main/java/hsa/awp/usergui/EventDetailPanel.java
Java
gpl-3.0
6,335
@import url("e4_basestyle.css"); @import url("relations.css"); .MTrimmedWindow { background-color: #E1E6F6; } .MPartStack { font-size: 9; font-family: 'Segoe UI'; swt-simple: true; swt-mru-visible: true; } .MTrimBar { background-color: #E1E6F6; } .MToolControl.TrimStack { frame-image: url(./win7TSFrame.png); handle-image: url(./win7Handle.png); } .MTrimBar#org-eclipse-ui-main-toolbar { background-image: url(./win7.png); } .MPartStack.active { swt-unselected-tabs-color: #F3F9FF #D0DFEE #CEDDED #CEDDED #D2E1F0 #D2E1F0 #FFFFFF 20% 45% 60% 70% 100% 100%; swt-outer-keyline-color: #B6BCCC; } #PerspectiveSwitcher { background-color: #F5F7FC #E1E6F6 100%; } #org-eclipse-ui-editorss { swt-tab-renderer: url('bundleclass://org.eclipse.e4.ui.workbench.renderers.swt/org.eclipse.e4.ui.workbench.renderers.swt.CTabRendering'); swt-unselected-tabs-color: #F0F0F0 #F0F0F0 #F0F0F0 100% 100%; swt-outer-keyline-color: #B4B4B4; swt-inner-keyline-color: #F0F0F0; swt-tab-outline: #F0F0F0; color: #F0F0F0; swt-tab-height: 8px; padding: 0px 5px 7px; } CTabFolder.MArea .MPartStack, CTabFolder.MArea .MPartStack.active { swt-shadow-visible: false; } CTabFolder Canvas { background-color: #F8F8F8; }
aktion-hip/relations
org.elbe.relations/css/e4_default_mru_on_win7.css
CSS
gpl-3.0
1,254
/* * AverMedia RM-KS remote controller keytable * * Copyright (C) 2010 Antti Palosaari <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <media/rc-map.h> #include <linux/module.h> /* Initial keytable is from Jose Alberto Reguero <[email protected]> and Felipe Morales Moreno <[email protected]> */ /* Keytable fixed by Philippe Valembois <[email protected]> */ static struct rc_map_table avermedia_rm_ks[] = { { 0x0501, KEY_POWER2 }, /* Power (RED POWER BUTTON) */ { 0x0502, KEY_CHANNELUP }, /* Channel+ */ { 0x0503, KEY_CHANNELDOWN }, /* Channel- */ { 0x0504, KEY_VOLUMEUP }, /* Volume+ */ { 0x0505, KEY_VOLUMEDOWN }, /* Volume- */ { 0x0506, KEY_MUTE }, /* Mute */ { 0x0507, KEY_AGAIN }, /* Recall */ { 0x0508, KEY_VIDEO }, /* Source */ { 0x0509, KEY_1 }, /* 1 */ { 0x050a, KEY_2 }, /* 2 */ { 0x050b, KEY_3 }, /* 3 */ { 0x050c, KEY_4 }, /* 4 */ { 0x050d, KEY_5 }, /* 5 */ { 0x050e, KEY_6 }, /* 6 */ { 0x050f, KEY_7 }, /* 7 */ { 0x0510, KEY_8 }, /* 8 */ { 0x0511, KEY_9 }, /* 9 */ { 0x0512, KEY_0 }, /* 0 */ { 0x0513, KEY_AUDIO }, /* Audio */ { 0x0515, KEY_EPG }, /* EPG */ { 0x0516, KEY_PLAYPAUSE }, /* Play/Pause */ { 0x0517, KEY_RECORD }, /* Record */ { 0x0518, KEY_STOP }, /* Stop */ { 0x051c, KEY_BACK }, /* << */ { 0x051d, KEY_FORWARD }, /* >> */ { 0x054d, KEY_INFO }, /* Display information */ { 0x0556, KEY_ZOOM }, /* Fullscreen */ }; static struct rc_map_list avermedia_rm_ks_map = { .map = { .scan = avermedia_rm_ks, .size = ARRAY_SIZE(avermedia_rm_ks), .rc_type = RC_TYPE_NEC, .name = RC_MAP_AVERMEDIA_RM_KS, } }; static int __init init_rc_map_avermedia_rm_ks(void) { return rc_map_register(&avermedia_rm_ks_map); } static void __exit exit_rc_map_avermedia_rm_ks(void) { rc_map_unregister(&avermedia_rm_ks_map); } module_init(init_rc_map_avermedia_rm_ks) module_exit(exit_rc_map_avermedia_rm_ks) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Antti Palosaari <[email protected]>");
williamfdevine/PrettyLinux
drivers/media/rc/keymaps/rc-avermedia-rm-ks.c
C
gpl-3.0
2,710
// Copyright (C) 2015 xaizek <[email protected]> // // This file is part of dit. // // dit is free software: you can redistribute it and/or modify // it under the terms of version 3 of the GNU Affero General Public // License as published by the Free Software Foundation. // // dit is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with dit. If not, see <http://www.gnu.org/licenses/>. #include <cassert> #include <cstdlib> #include <functional> #include <ostream> #include <sstream> #include <string> #include <vector> #include <boost/filesystem.hpp> #include "Command.hpp" #include "Commands.hpp" #include "Config.hpp" #include "Dit.hpp" #include "Project.hpp" namespace fs = boost::filesystem; /** * @brief Usage message for "complete" command. */ const char *const USAGE = "Usage: complete <regular args>"; namespace { /** * @brief Implementation of "complete" command, which helps with completion. */ class CompleteCmd : public AutoRegisteredCommand<CompleteCmd> { public: /** * @brief Constructs the command implementation. */ CompleteCmd(); public: /** * @copydoc Command::run() */ virtual boost::optional<int> run( Dit &dit, const std::vector<std::string> &args) override; }; } CompleteCmd::CompleteCmd() : parent("complete", "perform command-line completion", USAGE) { } boost::optional<int> CompleteCmd::run(Dit &dit, const std::vector<std::string> &args) { std::ostringstream estream; int exitCode = dit.complete(args, out(), estream); if (!estream.str().empty()) { // Calling err() has side effects, so don't call unless error occurred. err() << estream.str(); } return exitCode; }
xaizek/dit
src/cmds/CompleteCmd.cpp
C++
gpl-3.0
1,964
namespace DemoWinForm { partial class frmMapFinder { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.comboBox7 = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.comboBox8 = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.comboBox9 = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.comboBox2 = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.comboBox5 = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.comboBox6 = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); this.comboBox4 = new System.Windows.Forms.ComboBox(); this.label10 = new System.Windows.Forms.Label(); this.comboBox3 = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cmbCity = new System.Windows.Forms.ComboBox(); this.lblLandParcelCity = new System.Windows.Forms.Label(); this.cmbCountry = new System.Windows.Forms.ComboBox(); this.lblLandParcelCountry = new System.Windows.Forms.Label(); this.comboBox10 = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.comboBox11 = new System.Windows.Forms.ComboBox(); this.label11 = new System.Windows.Forms.Label(); this.comboBox12 = new System.Windows.Forms.ComboBox(); this.label12 = new System.Windows.Forms.Label(); this.comboBox13 = new System.Windows.Forms.ComboBox(); this.label13 = new System.Windows.Forms.Label(); this.comboBox14 = new System.Windows.Forms.ComboBox(); this.label14 = new System.Windows.Forms.Label(); this.comboBox15 = new System.Windows.Forms.ComboBox(); this.label15 = new System.Windows.Forms.Label(); this.comboBox16 = new System.Windows.Forms.ComboBox(); this.label16 = new System.Windows.Forms.Label(); this.comboBox17 = new System.Windows.Forms.ComboBox(); this.label17 = new System.Windows.Forms.Label(); this.comboBox18 = new System.Windows.Forms.ComboBox(); this.label18 = new System.Windows.Forms.Label(); this.comboBox19 = new System.Windows.Forms.ComboBox(); this.label19 = new System.Windows.Forms.Label(); this.comboBox20 = new System.Windows.Forms.ComboBox(); this.label20 = new System.Windows.Forms.Label(); this.spltMapFinder = new System.Windows.Forms.SplitContainer(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.comboBox21 = new System.Windows.Forms.ComboBox(); this.label21 = new System.Windows.Forms.Label(); this.comboBox22 = new System.Windows.Forms.ComboBox(); this.label22 = new System.Windows.Forms.Label(); this.comboBox23 = new System.Windows.Forms.ComboBox(); this.label23 = new System.Windows.Forms.Label(); this.comboBox24 = new System.Windows.Forms.ComboBox(); this.label24 = new System.Windows.Forms.Label(); this.comboBox25 = new System.Windows.Forms.ComboBox(); this.label25 = new System.Windows.Forms.Label(); this.comboBox26 = new System.Windows.Forms.ComboBox(); this.label26 = new System.Windows.Forms.Label(); this.comboBox27 = new System.Windows.Forms.ComboBox(); this.label27 = new System.Windows.Forms.Label(); this.comboBox28 = new System.Windows.Forms.ComboBox(); this.label28 = new System.Windows.Forms.Label(); this.comboBox29 = new System.Windows.Forms.ComboBox(); this.label29 = new System.Windows.Forms.Label(); this.comboBox30 = new System.Windows.Forms.ComboBox(); this.label30 = new System.Windows.Forms.Label(); this.comboBox31 = new System.Windows.Forms.ComboBox(); this.label31 = new System.Windows.Forms.Label(); this.mapbxMapFinder = new SharpMap.Forms.MapBox(); this.spltMapFinder.Panel1.SuspendLayout(); this.spltMapFinder.Panel2.SuspendLayout(); this.spltMapFinder.SuspendLayout(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // comboBox7 // this.comboBox7.FormattingEnabled = true; this.comboBox7.Location = new System.Drawing.Point(216, 291); this.comboBox7.Name = "comboBox7"; this.comboBox7.Size = new System.Drawing.Size(319, 21); this.comboBox7.TabIndex = 85; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(146, 291); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 13); this.label2.TabIndex = 86; this.label2.Text = "Location"; // // comboBox8 // this.comboBox8.FormattingEnabled = true; this.comboBox8.Location = new System.Drawing.Point(216, 237); this.comboBox8.Name = "comboBox8"; this.comboBox8.Size = new System.Drawing.Size(319, 21); this.comboBox8.TabIndex = 83; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(128, 237); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(70, 13); this.label3.TabIndex = 84; this.label3.Text = "Sub-Location"; // // comboBox9 // this.comboBox9.FormattingEnabled = true; this.comboBox9.Location = new System.Drawing.Point(216, 264); this.comboBox9.Name = "comboBox9"; this.comboBox9.Size = new System.Drawing.Size(319, 21); this.comboBox9.TabIndex = 81; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(154, 264); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 13); this.label4.TabIndex = 82; this.label4.Text = "County"; // // comboBox2 // this.comboBox2.FormattingEnabled = true; this.comboBox2.Location = new System.Drawing.Point(216, 210); this.comboBox2.Name = "comboBox2"; this.comboBox2.Size = new System.Drawing.Size(319, 21); this.comboBox2.TabIndex = 79; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(150, 213); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 13); this.label1.TabIndex = 80; this.label1.Text = "Location"; // // comboBox5 // this.comboBox5.FormattingEnabled = true; this.comboBox5.Location = new System.Drawing.Point(216, 156); this.comboBox5.Name = "comboBox5"; this.comboBox5.Size = new System.Drawing.Size(319, 21); this.comboBox5.TabIndex = 77; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(159, 156); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(39, 13); this.label5.TabIndex = 78; this.label5.Text = "District"; // // comboBox6 // this.comboBox6.FormattingEnabled = true; this.comboBox6.Location = new System.Drawing.Point(216, 183); this.comboBox6.Name = "comboBox6"; this.comboBox6.Size = new System.Drawing.Size(319, 21); this.comboBox6.TabIndex = 75; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(155, 183); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(44, 13); this.label6.TabIndex = 76; this.label6.Text = "Division"; // // comboBox4 // this.comboBox4.FormattingEnabled = true; this.comboBox4.Location = new System.Drawing.Point(216, 101); this.comboBox4.Name = "comboBox4"; this.comboBox4.Size = new System.Drawing.Size(319, 21); this.comboBox4.TabIndex = 73; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(159, 104); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(39, 13); this.label10.TabIndex = 74; this.label10.Text = "District"; // // comboBox3 // this.comboBox3.FormattingEnabled = true; this.comboBox3.Location = new System.Drawing.Point(216, 128); this.comboBox3.Name = "comboBox3"; this.comboBox3.Size = new System.Drawing.Size(319, 21); this.comboBox3.TabIndex = 71; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(155, 131); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(44, 13); this.label9.TabIndex = 72; this.label9.Text = "Division"; // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Location = new System.Drawing.Point(216, 74); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(319, 21); this.comboBox1.TabIndex = 69; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(149, 77); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(49, 13); this.label7.TabIndex = 70; this.label7.Text = "Province"; // // cmbCity // this.cmbCity.FormattingEnabled = true; this.cmbCity.Location = new System.Drawing.Point(216, 44); this.cmbCity.Name = "cmbCity"; this.cmbCity.Size = new System.Drawing.Size(319, 21); this.cmbCity.TabIndex = 66; // // lblLandParcelCity // this.lblLandParcelCity.AutoSize = true; this.lblLandParcelCity.Location = new System.Drawing.Point(170, 44); this.lblLandParcelCity.Name = "lblLandParcelCity"; this.lblLandParcelCity.Size = new System.Drawing.Size(24, 13); this.lblLandParcelCity.TabIndex = 68; this.lblLandParcelCity.Text = "City"; // // cmbCountry // this.cmbCountry.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbCountry.FormattingEnabled = true; this.cmbCountry.Location = new System.Drawing.Point(216, 17); this.cmbCountry.MaxDropDownItems = 10; this.cmbCountry.Name = "cmbCountry"; this.cmbCountry.Size = new System.Drawing.Size(319, 21); this.cmbCountry.TabIndex = 65; // // lblLandParcelCountry // this.lblLandParcelCountry.AutoSize = true; this.lblLandParcelCountry.Location = new System.Drawing.Point(151, 17); this.lblLandParcelCountry.Name = "lblLandParcelCountry"; this.lblLandParcelCountry.Size = new System.Drawing.Size(43, 13); this.lblLandParcelCountry.TabIndex = 67; this.lblLandParcelCountry.Text = "Country"; this.lblLandParcelCountry.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // comboBox10 // this.comboBox10.FormattingEnabled = true; this.comboBox10.Location = new System.Drawing.Point(216, 291); this.comboBox10.Name = "comboBox10"; this.comboBox10.Size = new System.Drawing.Size(319, 21); this.comboBox10.TabIndex = 85; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(146, 291); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(48, 13); this.label8.TabIndex = 86; this.label8.Text = "Location"; // // comboBox11 // this.comboBox11.FormattingEnabled = true; this.comboBox11.Location = new System.Drawing.Point(216, 237); this.comboBox11.Name = "comboBox11"; this.comboBox11.Size = new System.Drawing.Size(319, 21); this.comboBox11.TabIndex = 83; // // label11 // this.label11.AutoSize = true; this.label11.Location = new System.Drawing.Point(128, 237); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(70, 13); this.label11.TabIndex = 84; this.label11.Text = "Sub-Location"; // // comboBox12 // this.comboBox12.FormattingEnabled = true; this.comboBox12.Location = new System.Drawing.Point(216, 264); this.comboBox12.Name = "comboBox12"; this.comboBox12.Size = new System.Drawing.Size(319, 21); this.comboBox12.TabIndex = 81; // // label12 // this.label12.AutoSize = true; this.label12.Location = new System.Drawing.Point(154, 264); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(40, 13); this.label12.TabIndex = 82; this.label12.Text = "County"; // // comboBox13 // this.comboBox13.FormattingEnabled = true; this.comboBox13.Location = new System.Drawing.Point(216, 210); this.comboBox13.Name = "comboBox13"; this.comboBox13.Size = new System.Drawing.Size(319, 21); this.comboBox13.TabIndex = 79; // // label13 // this.label13.AutoSize = true; this.label13.Location = new System.Drawing.Point(150, 213); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(48, 13); this.label13.TabIndex = 80; this.label13.Text = "Location"; // // comboBox14 // this.comboBox14.FormattingEnabled = true; this.comboBox14.Location = new System.Drawing.Point(216, 156); this.comboBox14.Name = "comboBox14"; this.comboBox14.Size = new System.Drawing.Size(319, 21); this.comboBox14.TabIndex = 77; // // label14 // this.label14.AutoSize = true; this.label14.Location = new System.Drawing.Point(159, 156); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(39, 13); this.label14.TabIndex = 78; this.label14.Text = "District"; // // comboBox15 // this.comboBox15.FormattingEnabled = true; this.comboBox15.Location = new System.Drawing.Point(216, 183); this.comboBox15.Name = "comboBox15"; this.comboBox15.Size = new System.Drawing.Size(319, 21); this.comboBox15.TabIndex = 75; // // label15 // this.label15.AutoSize = true; this.label15.Location = new System.Drawing.Point(155, 183); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(44, 13); this.label15.TabIndex = 76; this.label15.Text = "Division"; // // comboBox16 // this.comboBox16.FormattingEnabled = true; this.comboBox16.Location = new System.Drawing.Point(216, 101); this.comboBox16.Name = "comboBox16"; this.comboBox16.Size = new System.Drawing.Size(319, 21); this.comboBox16.TabIndex = 73; // // label16 // this.label16.AutoSize = true; this.label16.Location = new System.Drawing.Point(159, 104); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(39, 13); this.label16.TabIndex = 74; this.label16.Text = "District"; // // comboBox17 // this.comboBox17.FormattingEnabled = true; this.comboBox17.Location = new System.Drawing.Point(216, 128); this.comboBox17.Name = "comboBox17"; this.comboBox17.Size = new System.Drawing.Size(319, 21); this.comboBox17.TabIndex = 71; // // label17 // this.label17.AutoSize = true; this.label17.Location = new System.Drawing.Point(155, 131); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(44, 13); this.label17.TabIndex = 72; this.label17.Text = "Division"; // // comboBox18 // this.comboBox18.FormattingEnabled = true; this.comboBox18.Location = new System.Drawing.Point(216, 74); this.comboBox18.Name = "comboBox18"; this.comboBox18.Size = new System.Drawing.Size(319, 21); this.comboBox18.TabIndex = 69; // // label18 // this.label18.AutoSize = true; this.label18.Location = new System.Drawing.Point(149, 77); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(49, 13); this.label18.TabIndex = 70; this.label18.Text = "Province"; // // comboBox19 // this.comboBox19.FormattingEnabled = true; this.comboBox19.Location = new System.Drawing.Point(216, 44); this.comboBox19.Name = "comboBox19"; this.comboBox19.Size = new System.Drawing.Size(319, 21); this.comboBox19.TabIndex = 66; // // label19 // this.label19.AutoSize = true; this.label19.Location = new System.Drawing.Point(170, 44); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(24, 13); this.label19.TabIndex = 68; this.label19.Text = "City"; // // comboBox20 // this.comboBox20.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox20.FormattingEnabled = true; this.comboBox20.Location = new System.Drawing.Point(216, 17); this.comboBox20.MaxDropDownItems = 10; this.comboBox20.Name = "comboBox20"; this.comboBox20.Size = new System.Drawing.Size(319, 21); this.comboBox20.TabIndex = 65; // // label20 // this.label20.AutoSize = true; this.label20.Location = new System.Drawing.Point(151, 17); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(43, 13); this.label20.TabIndex = 67; this.label20.Text = "Country"; this.label20.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // spltMapFinder // this.spltMapFinder.Dock = System.Windows.Forms.DockStyle.Fill; this.spltMapFinder.Location = new System.Drawing.Point(0, 0); this.spltMapFinder.Name = "spltMapFinder"; this.spltMapFinder.Orientation = System.Windows.Forms.Orientation.Horizontal; // // spltMapFinder.Panel1 // this.spltMapFinder.Panel1.Controls.Add(this.groupBox1); // // spltMapFinder.Panel2 // this.spltMapFinder.Panel2.Controls.Add(this.mapbxMapFinder); this.spltMapFinder.Size = new System.Drawing.Size(874, 548); this.spltMapFinder.SplitterDistance = 240; this.spltMapFinder.TabIndex = 0; // // groupBox1 // this.groupBox1.Controls.Add(this.comboBox21); this.groupBox1.Controls.Add(this.label21); this.groupBox1.Controls.Add(this.comboBox22); this.groupBox1.Controls.Add(this.label22); this.groupBox1.Controls.Add(this.comboBox23); this.groupBox1.Controls.Add(this.label23); this.groupBox1.Controls.Add(this.comboBox24); this.groupBox1.Controls.Add(this.label24); this.groupBox1.Controls.Add(this.comboBox25); this.groupBox1.Controls.Add(this.label25); this.groupBox1.Controls.Add(this.comboBox26); this.groupBox1.Controls.Add(this.label26); this.groupBox1.Controls.Add(this.comboBox27); this.groupBox1.Controls.Add(this.label27); this.groupBox1.Controls.Add(this.comboBox28); this.groupBox1.Controls.Add(this.label28); this.groupBox1.Controls.Add(this.comboBox29); this.groupBox1.Controls.Add(this.label29); this.groupBox1.Controls.Add(this.comboBox30); this.groupBox1.Controls.Add(this.label30); this.groupBox1.Controls.Add(this.comboBox31); this.groupBox1.Controls.Add(this.label31); this.groupBox1.Location = new System.Drawing.Point(2, 5); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(870, 217); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "Search Map"; this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter); // // comboBox21 // this.comboBox21.FormattingEnabled = true; this.comboBox21.Location = new System.Drawing.Point(514, 135); this.comboBox21.Name = "comboBox21"; this.comboBox21.Size = new System.Drawing.Size(319, 21); this.comboBox21.TabIndex = 85; this.comboBox21.SelectedIndexChanged += new System.EventHandler(this.comboBox21_SelectedIndexChanged); // // label21 // this.label21.AutoSize = true; this.label21.Location = new System.Drawing.Point(419, 135); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(92, 13); this.label21.TabIndex = 86; this.label21.Text = "Universal Address"; // // comboBox22 // this.comboBox22.FormattingEnabled = true; this.comboBox22.Location = new System.Drawing.Point(514, 81); this.comboBox22.Name = "comboBox22"; this.comboBox22.Size = new System.Drawing.Size(319, 21); this.comboBox22.TabIndex = 83; // // label22 // this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(438, 84); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(70, 13); this.label22.TabIndex = 84; this.label22.Text = "Sub-Location"; // // comboBox23 // this.comboBox23.FormattingEnabled = true; this.comboBox23.Location = new System.Drawing.Point(514, 108); this.comboBox23.Name = "comboBox23"; this.comboBox23.Size = new System.Drawing.Size(319, 21); this.comboBox23.TabIndex = 81; // // label23 // this.label23.AutoSize = true; this.label23.Location = new System.Drawing.Point(468, 109); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(40, 13); this.label23.TabIndex = 82; this.label23.Text = "County"; // // comboBox24 // this.comboBox24.FormattingEnabled = true; this.comboBox24.Location = new System.Drawing.Point(514, 54); this.comboBox24.Name = "comboBox24"; this.comboBox24.Size = new System.Drawing.Size(319, 21); this.comboBox24.TabIndex = 79; // // label24 // this.label24.AutoSize = true; this.label24.Location = new System.Drawing.Point(460, 55); this.label24.Name = "label24"; this.label24.Size = new System.Drawing.Size(48, 13); this.label24.TabIndex = 80; this.label24.Text = "Location"; // // comboBox25 // this.comboBox25.FormattingEnabled = true; this.comboBox25.Location = new System.Drawing.Point(81, 166); this.comboBox25.Name = "comboBox25"; this.comboBox25.Size = new System.Drawing.Size(319, 21); this.comboBox25.TabIndex = 77; // // label25 // this.label25.AutoSize = true; this.label25.Location = new System.Drawing.Point(24, 166); this.label25.Name = "label25"; this.label25.Size = new System.Drawing.Size(39, 13); this.label25.TabIndex = 78; this.label25.Text = "District"; // // comboBox26 // this.comboBox26.FormattingEnabled = true; this.comboBox26.Location = new System.Drawing.Point(514, 27); this.comboBox26.Name = "comboBox26"; this.comboBox26.Size = new System.Drawing.Size(319, 21); this.comboBox26.TabIndex = 75; // // label26 // this.label26.AutoSize = true; this.label26.Location = new System.Drawing.Point(464, 29); this.label26.Name = "label26"; this.label26.Size = new System.Drawing.Size(44, 13); this.label26.TabIndex = 76; this.label26.Text = "Division"; // // comboBox27 // this.comboBox27.FormattingEnabled = true; this.comboBox27.Location = new System.Drawing.Point(81, 111); this.comboBox27.Name = "comboBox27"; this.comboBox27.Size = new System.Drawing.Size(319, 21); this.comboBox27.TabIndex = 73; // // label27 // this.label27.AutoSize = true; this.label27.Location = new System.Drawing.Point(24, 114); this.label27.Name = "label27"; this.label27.Size = new System.Drawing.Size(39, 13); this.label27.TabIndex = 74; this.label27.Text = "District"; // // comboBox28 // this.comboBox28.FormattingEnabled = true; this.comboBox28.Location = new System.Drawing.Point(81, 138); this.comboBox28.Name = "comboBox28"; this.comboBox28.Size = new System.Drawing.Size(319, 21); this.comboBox28.TabIndex = 71; // // label28 // this.label28.AutoSize = true; this.label28.Location = new System.Drawing.Point(20, 141); this.label28.Name = "label28"; this.label28.Size = new System.Drawing.Size(44, 13); this.label28.TabIndex = 72; this.label28.Text = "Division"; // // comboBox29 // this.comboBox29.FormattingEnabled = true; this.comboBox29.Location = new System.Drawing.Point(81, 84); this.comboBox29.Name = "comboBox29"; this.comboBox29.Size = new System.Drawing.Size(319, 21); this.comboBox29.TabIndex = 69; // // label29 // this.label29.AutoSize = true; this.label29.Location = new System.Drawing.Point(14, 87); this.label29.Name = "label29"; this.label29.Size = new System.Drawing.Size(49, 13); this.label29.TabIndex = 70; this.label29.Text = "Province"; // // comboBox30 // this.comboBox30.FormattingEnabled = true; this.comboBox30.Location = new System.Drawing.Point(81, 54); this.comboBox30.Name = "comboBox30"; this.comboBox30.Size = new System.Drawing.Size(319, 21); this.comboBox30.TabIndex = 66; // // label30 // this.label30.AutoSize = true; this.label30.Location = new System.Drawing.Point(35, 54); this.label30.Name = "label30"; this.label30.Size = new System.Drawing.Size(24, 13); this.label30.TabIndex = 68; this.label30.Text = "City"; // // comboBox31 // this.comboBox31.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox31.FormattingEnabled = true; this.comboBox31.Location = new System.Drawing.Point(81, 27); this.comboBox31.MaxDropDownItems = 10; this.comboBox31.Name = "comboBox31"; this.comboBox31.Size = new System.Drawing.Size(319, 21); this.comboBox31.TabIndex = 65; // // label31 // this.label31.AutoSize = true; this.label31.Location = new System.Drawing.Point(16, 27); this.label31.Name = "label31"; this.label31.Size = new System.Drawing.Size(43, 13); this.label31.TabIndex = 67; this.label31.Text = "Country"; this.label31.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // mapbxMapFinder // this.mapbxMapFinder.ActiveTool = SharpMap.Forms.MapBox.Tools.None; this.mapbxMapFinder.BackColor = System.Drawing.SystemColors.Info; this.mapbxMapFinder.Cursor = System.Windows.Forms.Cursors.Default; this.mapbxMapFinder.Dock = System.Windows.Forms.DockStyle.Fill; this.mapbxMapFinder.FineZoomFactor = 10; this.mapbxMapFinder.Location = new System.Drawing.Point(0, 0); this.mapbxMapFinder.Name = "mapbxMapFinder"; this.mapbxMapFinder.QueryLayerIndex = 0; this.mapbxMapFinder.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244))))); this.mapbxMapFinder.SelectionForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(244)))), ((int)(((byte)(244)))), ((int)(((byte)(244))))); this.mapbxMapFinder.Size = new System.Drawing.Size(874, 304); this.mapbxMapFinder.TabIndex = 5; this.mapbxMapFinder.WheelZoomMagnitude = 2; // // frmMapFinder // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(874, 548); this.Controls.Add(this.spltMapFinder); this.Name = "frmMapFinder"; this.Text = "frmMapFinder"; this.Load += new System.EventHandler(this.frmMapFinder_Load); this.spltMapFinder.Panel1.ResumeLayout(false); this.spltMapFinder.Panel2.ResumeLayout(false); this.spltMapFinder.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox comboBox7; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox comboBox8; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox comboBox9; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox comboBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBox5; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox comboBox6; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox comboBox4; private System.Windows.Forms.Label label10; private System.Windows.Forms.ComboBox comboBox3; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cmbCity; private System.Windows.Forms.Label lblLandParcelCity; private System.Windows.Forms.ComboBox cmbCountry; private System.Windows.Forms.Label lblLandParcelCountry; private System.Windows.Forms.ComboBox comboBox10; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox comboBox11; private System.Windows.Forms.Label label11; private System.Windows.Forms.ComboBox comboBox12; private System.Windows.Forms.Label label12; private System.Windows.Forms.ComboBox comboBox13; private System.Windows.Forms.Label label13; private System.Windows.Forms.ComboBox comboBox14; private System.Windows.Forms.Label label14; private System.Windows.Forms.ComboBox comboBox15; private System.Windows.Forms.Label label15; private System.Windows.Forms.ComboBox comboBox16; private System.Windows.Forms.Label label16; private System.Windows.Forms.ComboBox comboBox17; private System.Windows.Forms.Label label17; private System.Windows.Forms.ComboBox comboBox18; private System.Windows.Forms.Label label18; private System.Windows.Forms.ComboBox comboBox19; private System.Windows.Forms.Label label19; private System.Windows.Forms.ComboBox comboBox20; private System.Windows.Forms.Label label20; private System.Windows.Forms.SplitContainer spltMapFinder; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox comboBox21; private System.Windows.Forms.Label label21; private System.Windows.Forms.ComboBox comboBox22; private System.Windows.Forms.Label label22; private System.Windows.Forms.ComboBox comboBox23; private System.Windows.Forms.Label label23; private System.Windows.Forms.ComboBox comboBox24; private System.Windows.Forms.Label label24; private System.Windows.Forms.ComboBox comboBox25; private System.Windows.Forms.Label label25; private System.Windows.Forms.ComboBox comboBox26; private System.Windows.Forms.Label label26; private System.Windows.Forms.ComboBox comboBox27; private System.Windows.Forms.Label label27; private System.Windows.Forms.ComboBox comboBox28; private System.Windows.Forms.Label label28; private System.Windows.Forms.ComboBox comboBox29; private System.Windows.Forms.Label label29; private System.Windows.Forms.ComboBox comboBox30; private System.Windows.Forms.Label label30; private System.Windows.Forms.ComboBox comboBox31; private System.Windows.Forms.Label label31; private SharpMap.Forms.MapBox mapbxMapFinder; } }
anonymouskeyboard47/Tripodmaps
ShapeFileTools/frmMapFinder.Designer.cs
C#
gpl-3.0
38,884
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.dialer.calllog; import android.content.Context; import android.content.res.Resources; import android.provider.CallLog.Calls; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.util.Log; import com.android.contacts.common.CallUtil; import com.android.dialer.PhoneCallDetails; import com.android.dialer.PhoneCallDetailsHelper; import com.android.dialer.R; /** * Helper class to fill in the views of a call log entry. */ /* package */class CallLogListItemHelper { private static final String TAG = "CallLogListItemHelper"; /** Helper for populating the details of a phone call. */ private final PhoneCallDetailsHelper mPhoneCallDetailsHelper; /** Helper for handling phone numbers. */ private final PhoneNumberDisplayHelper mPhoneNumberHelper; /** Resources to look up strings. */ private final Resources mResources; /** * Creates a new helper instance. * * @param phoneCallDetailsHelper used to set the details of a phone call * @param phoneNumberHelper used to process phone number */ public CallLogListItemHelper(PhoneCallDetailsHelper phoneCallDetailsHelper, PhoneNumberDisplayHelper phoneNumberHelper, Resources resources) { mPhoneCallDetailsHelper = phoneCallDetailsHelper; mPhoneNumberHelper = phoneNumberHelper; mResources = resources; } /** * Sets the name, label, and number for a contact. * * @param context The application context. * @param views the views to populate * @param details the details of a phone call needed to fill in the data */ public void setPhoneCallDetails( Context context, CallLogListItemViews views, PhoneCallDetails details) { mPhoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details); // Set the accessibility text for the contact badge views.quickContactView.setContentDescription(getContactBadgeDescription(details)); // Set the primary action accessibility description views.primaryActionView.setContentDescription(getCallDescription(context, details)); // Cache name or number of caller. Used when setting the content descriptions of buttons // when the actions ViewStub is inflated. views.nameOrNumber = this.getNameOrNumber(details); } /** * Sets the accessibility descriptions for the action buttons in the action button ViewStub. * * @param views The views associated with the current call log entry. */ public void setActionContentDescriptions(CallLogListItemViews views) { if (views.nameOrNumber == null) { Log.e(TAG, "setActionContentDescriptions; name or number is null."); } // Calling expandTemplate with a null parameter will cause a NullPointerException. // Although we don't expect a null name or number, it is best to protect against it. CharSequence nameOrNumber = views.nameOrNumber == null ? "" : views.nameOrNumber; views.callBackButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_call_back_action), nameOrNumber)); views.videoCallButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_video_call_action), nameOrNumber)); views.voicemailButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_voicemail_action), nameOrNumber)); views.detailsButtonView.setContentDescription( TextUtils.expandTemplate( mResources.getString(R.string.description_details_action), nameOrNumber)); } /** * Returns the accessibility description for the contact badge for a call log entry. * * @param details Details of call. * @return Accessibility description. */ private CharSequence getContactBadgeDescription(PhoneCallDetails details) { return mResources.getString(R.string.description_contact_details, getNameOrNumber(details)); } /** * Returns the accessibility description of the "return call/call" action for a call log * entry. * Accessibility text is a combination of: * {Voicemail Prefix}. {Number of Calls}. {Caller information} {Phone Account}. * If most recent call is a voicemail, {Voicemail Prefix} is "New Voicemail.", otherwise "". * * If more than one call for the caller, {Number of Calls} is: * "{number of calls} calls.", otherwise "". * * The {Caller Information} references the most recent call associated with the caller. * For incoming calls: * If missed call: Missed call from {Name/Number} {Call Type} {Call Time}. * If answered call: Answered call from {Name/Number} {Call Type} {Call Time}. * * For outgoing calls: * If outgoing: Call to {Name/Number] {Call Type} {Call Time}. * * Where: * {Name/Number} is the name or number of the caller (as shown in call log). * {Call type} is the contact phone number type (eg mobile) or location. * {Call Time} is the time since the last call for the contact occurred. * * The {Phone Account} refers to the account/SIM through which the call was placed or received * in multi-SIM devices. * * Examples: * 3 calls. New Voicemail. Missed call from Joe Smith mobile 2 hours ago on SIM 1. * * 2 calls. Answered call from John Doe mobile 1 hour ago. * * @param context The application context. * @param details Details of call. * @return Return call action description. */ public CharSequence getCallDescription(Context context, PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); boolean isVoiceMail = lastCallType == Calls.VOICEMAIL_TYPE; // Get the name or number of the caller. final CharSequence nameOrNumber = getNameOrNumber(details); // Get the call type or location of the caller; null if not applicable final CharSequence typeOrLocation = mPhoneCallDetailsHelper.getCallTypeOrLocation(details); // Get the time/date of the call final CharSequence timeOfCall = mPhoneCallDetailsHelper.getCallDate(details); SpannableStringBuilder callDescription = new SpannableStringBuilder(); // Prepend the voicemail indication. if (isVoiceMail) { callDescription.append(mResources.getString(R.string.description_new_voicemail)); } // Add number of calls if more than one. if (details.callTypes.length > 1) { callDescription.append(mResources.getString(R.string.description_num_calls, details.callTypes.length)); } // If call had video capabilities, add the "Video Call" string. if ((details.features & Calls.FEATURES_VIDEO) == Calls.FEATURES_VIDEO && CallUtil.isVideoEnabled(context)) { callDescription.append(mResources.getString(R.string.description_video_call)); } int stringID = getCallDescriptionStringID(details); String accountLabel = PhoneAccountUtils.getAccountLabel(context, details.accountHandle); // Use chosen string resource to build up the message. CharSequence onAccountLabel = accountLabel == null ? "" : TextUtils.expandTemplate( mResources.getString(R.string.description_phone_account), accountLabel); callDescription.append( TextUtils.expandTemplate( mResources.getString(stringID), nameOrNumber, // If no type or location can be determined, sub in empty string. typeOrLocation == null ? "" : typeOrLocation, timeOfCall, onAccountLabel)); return callDescription; } /** * Determine the appropriate string ID to describe a call for accessibility purposes. * * @param details Call details. * @return String resource ID to use. */ public int getCallDescriptionStringID(PhoneCallDetails details) { int lastCallType = getLastCallType(details.callTypes); int stringID; if (lastCallType == Calls.VOICEMAIL_TYPE || lastCallType == Calls.MISSED_TYPE) { //Message: Missed call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_missed_call; } else if (lastCallType == Calls.INCOMING_TYPE) { //Message: Answered call from <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, //<PhoneAccount>. stringID = R.string.description_incoming_answered_call; } else { //Message: Call to <NameOrNumber>, <TypeOrLocation>, <TimeOfCall>, <PhoneAccount>. stringID = R.string.description_outgoing_call; } return stringID; } /** * Determine the call type for the most recent call. * @param callTypes Call types to check. * @return Call type. */ private int getLastCallType(int[] callTypes) { if (callTypes.length > 0) { return callTypes[0]; } else { return Calls.MISSED_TYPE; } } /** * Return the name or number of the caller specified by the details. * @param details Call details * @return the name (if known) of the caller, otherwise the formatted number. */ private CharSequence getNameOrNumber(PhoneCallDetails details) { final CharSequence recipient; if (!TextUtils.isEmpty(details.name)) { recipient = details.name; } else { recipient = mPhoneNumberHelper.getDisplayNumber(details.accountHandle, details.number, details.numberPresentation, details.formattedNumber); } return recipient; } }
s20121035/rk3288_android5.1_repo
packages/apps/Dialer/src/com/android/dialer/calllog/CallLogListItemHelper.java
Java
gpl-3.0
10,890
#ifndef _TREENODE_H #define _TREENODE_H #include <stdio.h> #include <stdbool.h> #include <wptypes.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ typedef struct _wp_treenode wp_tree_node_t; typedef enum _rb_wp_tree_node_cloor { RB_TREE_RED = 0, RB_TREE_BLACK, } wp_rb_tree_node_color_t; wp_tree_node_t *wp_tree_node_new (void); wp_tree_node_t *wp_tree_node_new_full (void *content, wp_tree_node_t *parent, wp_tree_node_t *left, wp_tree_node_t *right); void wp_tree_node_copy (wp_tree_node_t *dest, const wp_tree_node_t *src); void wp_tree_node_free (wp_tree_node_t *node); void wp_tree_node_set_content (wp_tree_node_t *node, void *data); void wp_tree_node_set_parent (wp_tree_node_t *node, wp_tree_node_t *parent); void wp_tree_node_set_left (wp_tree_node_t *node, wp_tree_node_t *left); void wp_tree_node_set_right (wp_tree_node_t *node, wp_tree_node_t *right); void *wp_tree_node_get_content (const wp_tree_node_t *node); wp_tree_node_t *wp_tree_node_get_parent (const wp_tree_node_t *node); wp_tree_node_t *wp_tree_node_get_left (const wp_tree_node_t *node); wp_tree_node_t *wp_tree_node_get_right (const wp_tree_node_t *node); int wp_tree_node_is_leaf (const wp_tree_node_t *node); int wp_tree_node_is_root (const wp_tree_node_t *node); void wp_tree_node_dump (const wp_tree_node_t *node, FILE *file, wp_write_func_t f, void *data); /* For Red-Black Tree */ void wp_tree_node_set_red (wp_tree_node_t *node); void wp_tree_node_set_black (wp_tree_node_t *node); int wp_tree_node_is_red (const wp_tree_node_t *node); int wp_tree_node_is_black (const wp_tree_node_t *node); wp_rb_tree_node_color_t wp_tree_node_get_color (const wp_tree_node_t *node); void wp_tree_node_set_color (wp_tree_node_t *node, wp_rb_tree_node_color_t color); void wp_tree_node_copy_color (wp_tree_node_t *dest, const wp_tree_node_t *src); void rb_wp_tree_node_dump (const wp_tree_node_t *node, FILE *file, wp_write_func_t f, void *data); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _TREENODE_H */
4179e1/libwp
src/wptreenode.h
C
gpl-3.0
2,011
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ENetSharp { public class ENetList { public List<object> data = new List<object>(); internal int position; } public static class ENetListHelper { /// <summary> /// Removes everything from the list /// </summary> /// <param name="list">The target list</param> public static void enet_list_clear(ref ENetList list) { list.data.Clear(); } public static ENetList enet_list_insert(ref ENetList list, int position, object data) { list.data.Insert(position, data); return list; } public static ENetList enet_list_insert(ref ENetList list, object data) { list.data.Add(data); return list; } public static object enet_list_remove(ref ENetList list, int position) { var data = list.data[position]; list.data.RemoveAt(position); return data; } public static object enet_list_remove(ref ENetList list) { var item = list.data[list.position]; list.data.Remove(item); return item; } public static object enet_list_remove(ref ENetList list, object item) { list.data.Remove(item); return item; } public static void enet_list_remove(ref ENetList list, Predicate<object> items) { list.data.RemoveAll(items); } public static ENetList enet_list_move(ref ENetList list, int positionFirst, int positionLast) { object tmp = list.data[positionFirst]; list.data[positionFirst] = list.data[positionLast]; list.data[positionLast] = tmp; return list; } public static int enet_list_size(ref ENetList list) { return list.data.Count; } //#define enet_list_begin(list) ((list) -> sentinel.next) public static object enet_list_begin(ref ENetList list) { return list.data.First(); } //#define enet_list_end(list) (& (list) -> sentinel) public static object enet_list_end(ref ENetList list) { return list.data.Last(); } //#define enet_list_empty(list) (enet_list_begin (list) == enet_list_end (list)) public static bool enet_list_empty(ref ENetList list) { return !list.data.Any(); } //#define enet_list_next(iterator) ((iterator) -> next) public static object enet_list_next(ref ENetList list) { var d = list.data[list.position]; list.position++; return d; } //#define enet_list_previous(iterator) ((iterator) -> previous) public static object enet_list_previous(ref ENetList list) { var d = list.data[list.position]; list.position--; return d; } //#define enet_list_front(list) ((void *) (list) -> sentinel.next) public static object enet_list_front(ref ENetList list) { return list.data.First(); } //#define enet_list_back(list) ((void *) (list) -> sentinel.previous) public static object enet_list_back(ref ENetList list) { list.position--; return list.data[list.position]; } public static object enet_list_current(ref ENetList list) { return list.data[list.position]; } } }
eddy5641/ENetSharp
ENetSharp/ENetSharp/List.cs
C#
gpl-3.0
3,725
/* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /* * Creates all the demo application tasks, then starts the scheduler. The WEB * documentation provides more details of the demo application tasks. * * In addition to the standard demo tasks, the follow demo specific tasks are * create: * * The "Check" task. This only executes every three seconds but has the highest * priority so is guaranteed to get processor time. Its main function is to * check that all the other tasks are still operational. Most tasks maintain * a unique count that is incremented each time the task successfully completes * its function. Should any error occur within such a task the count is * permanently halted. The check task inspects the count of each task to ensure * it has changed since the last time the check task executed. If all the count * variables have changed all the tasks are still executing error free, and the * check task toggles the onboard LED. Should any task contain an error at any time * the LED toggle rate will change from 3 seconds to 500ms. * * The "Register Check" tasks. These tasks fill the CPU registers with known * values, then check that each register still contains the expected value, the * discovery of an unexpected value being indicative of an error in the RTOS * context switch mechanism. The register check tasks operate at low priority * so are switched in and out frequently. * */ /* Scheduler includes. */ #include "FreeRTOS.h" #include "task.h" /* Xilinx library includes. */ #include "xcache_l.h" #include "xintc.h" /* Demo application includes. */ #include "flash.h" #include "integer.h" #include "comtest2.h" #include "semtest.h" #include "BlockQ.h" #include "dynamic.h" #include "GenQTest.h" #include "QPeek.h" #include "blocktim.h" #include "death.h" #include "partest.h" #include "countsem.h" #include "recmutex.h" #include "flop.h" #include "flop-reg-test.h" /* Priorities assigned to the demo tasks. */ #define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 4 ) #define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 ) #define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainQUEUE_BLOCK_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainDEATH_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainGENERIC_QUEUE_PRIORITY ( tskIDLE_PRIORITY ) #define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 1 ) #define mainFLOP_PRIORITY ( tskIDLE_PRIORITY ) /* The first LED used by the COM test and check tasks respectively. */ #define mainCOM_TEST_LED ( 4 ) #define mainCHECK_TEST_LED ( 3 ) /* The baud rate used by the comtest tasks is set by the hardware, so the baud rate parameters passed into the comtest initialisation has no effect. */ #define mainBAUD_SET_IN_HARDWARE ( 0 ) /* Delay periods used by the check task. If no errors have been found then the check LED will toggle every mainNO_ERROR_CHECK_DELAY milliseconds. If an error has been found at any time then the toggle rate will increase to mainERROR_CHECK_DELAY milliseconds. */ #define mainNO_ERROR_CHECK_DELAY ( ( TickType_t ) 3000 / portTICK_PERIOD_MS ) #define mainERROR_CHECK_DELAY ( ( TickType_t ) 500 / portTICK_PERIOD_MS ) /* * The tasks defined within this file - described within the comments at the * head of this page. */ static void prvRegTestTask1( void *pvParameters ); static void prvRegTestTask2( void *pvParameters ); static void prvErrorChecks( void *pvParameters ); /* * Called by the 'check' task to inspect all the standard demo tasks within * the system, as described within the comments at the head of this page. */ static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void ); /* * Perform any hardware initialisation required by the demo application. */ static void prvSetupHardware( void ); /*-----------------------------------------------------------*/ /* xRegTestStatus will get set to pdFAIL by the regtest tasks if they discover an unexpected value. */ static volatile unsigned portBASE_TYPE xRegTestStatus = pdPASS; /* Counters used to ensure the regtest tasks are still running. */ static volatile unsigned long ulRegTest1Counter = 0UL, ulRegTest2Counter = 0UL; /*-----------------------------------------------------------*/ int main( void ) { /* Must be called prior to installing any interrupt handlers! */ vPortSetupInterruptController(); /* In this case prvSetupHardware() just enables the caches and and configures the IO ports for the LED outputs. */ prvSetupHardware(); /* Start the standard demo application tasks. Note that the baud rate used by the comtest tasks is set by the hardware, so the baud rate parameter passed has no effect. */ vStartLEDFlashTasks( mainLED_TASK_PRIORITY ); vStartIntegerMathTasks( tskIDLE_PRIORITY ); vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainBAUD_SET_IN_HARDWARE, mainCOM_TEST_LED ); vStartSemaphoreTasks( mainSEM_TEST_PRIORITY ); vStartBlockingQueueTasks ( mainQUEUE_BLOCK_PRIORITY ); vStartDynamicPriorityTasks(); vStartGenericQueueTasks( mainGENERIC_QUEUE_PRIORITY ); vStartQueuePeekTasks(); vCreateBlockTimeTasks(); vStartCountingSemaphoreTasks(); vStartRecursiveMutexTasks(); #if ( configUSE_FPU == 1 ) { /* A different project is provided that has configUSE_FPU set to 1 in order to demonstrate all the settings required to use the floating point unit. If you wish to use the floating point unit do not start with this project. */ vStartMathTasks( mainFLOP_PRIORITY ); vStartFlopRegTests(); } #endif /* Create the tasks defined within this file. */ xTaskCreate( prvRegTestTask1, "Regtest1", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvRegTestTask2, "Regtest2", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL ); /* The suicide tasks must be started last as they record the number of other tasks that exist within the system. The value is then used to ensure at run time the number of tasks that exists is within expected bounds. */ vCreateSuicidalTasks( mainDEATH_PRIORITY ); /* Now start the scheduler. Following this call the created tasks should be executing. */ vTaskStartScheduler(); /* vTaskStartScheduler() will only return if an error occurs while the idle task is being created. */ for( ;; ); return 0; } /*-----------------------------------------------------------*/ static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void ) { portBASE_TYPE lReturn = pdPASS; static unsigned long ulLastRegTest1Counter= 0UL, ulLastRegTest2Counter = 0UL; /* The demo tasks maintain a count that increments every cycle of the task provided that the task has never encountered an error. This function checks the counts maintained by the tasks to ensure they are still being incremented. A count remaining at the same value between calls therefore indicates that an error has been detected. */ if( xAreIntegerMathsTaskStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreComTestTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreSemaphoreTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreBlockingQueuesStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreDynamicPriorityTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xIsCreateTaskStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreBlockTimeTestTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreGenericQueueTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreQueuePeekTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreCountingSemaphoreTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreRecursiveMutexTasksStillRunning() != pdTRUE ) { lReturn = pdFAIL; } #if ( configUSE_FPU == 1 ) if( xAreMathsTaskStillRunning() != pdTRUE ) { lReturn = pdFAIL; } if( xAreFlopRegisterTestsStillRunning() != pdTRUE ) { lReturn = pdFAIL; } #endif /* Have the register test tasks found any errors? */ if( xRegTestStatus != pdPASS ) { lReturn = pdFAIL; } /* Are the register test tasks still looping? */ if( ulLastRegTest1Counter == ulRegTest1Counter ) { lReturn = pdFAIL; } else { ulLastRegTest1Counter = ulRegTest1Counter; } if( ulLastRegTest2Counter == ulRegTest2Counter ) { lReturn = pdFAIL; } else { ulLastRegTest2Counter = ulRegTest2Counter; } return lReturn; } /*-----------------------------------------------------------*/ static void prvErrorChecks( void *pvParameters ) { TickType_t xDelayPeriod = mainNO_ERROR_CHECK_DELAY, xLastExecutionTime; volatile unsigned portBASE_TYPE uxFreeStack; /* Just to remove compiler warning. */ ( void ) pvParameters; /* This call is just to demonstrate the use of the function - nothing is done with the value. You would expect the stack high water mark to be lower (the function to return a larger value) here at function entry than later following calls to other functions. */ uxFreeStack = uxTaskGetStackHighWaterMark( NULL ); /* Initialise xLastExecutionTime so the first call to vTaskDelayUntil() works correctly. */ xLastExecutionTime = xTaskGetTickCount(); /* Cycle for ever, delaying then checking all the other tasks are still operating without error. */ for( ;; ) { /* Again just for demo purposes - uxFreeStack should have a lower value here than following the call to uxTaskGetStackHighWaterMark() on the task entry. */ uxFreeStack = uxTaskGetStackHighWaterMark( NULL ); /* Wait until it is time to check again. The time we wait here depends on whether an error has been detected or not. When an error is detected the time is shortened resulting in a faster LED flash rate. */ vTaskDelayUntil( &xLastExecutionTime, xDelayPeriod ); /* See if the other tasks are all ok. */ if( prvCheckOtherTasksAreStillRunning() != pdPASS ) { /* An error occurred in one of the tasks so shorten the delay period - which has the effect of increasing the frequency of the LED toggle. */ xDelayPeriod = mainERROR_CHECK_DELAY; } /* Flash! */ vParTestToggleLED( mainCHECK_TEST_LED ); } } /*-----------------------------------------------------------*/ static void prvSetupHardware( void ) { XCache_EnableICache( 0x80000000 ); XCache_EnableDCache( 0x80000000 ); /* Setup the IO port for use with the LED outputs. */ vParTestInitialise(); } /*-----------------------------------------------------------*/ void prvRegTest1Pass( void ) { /* Called from the inline assembler - this cannot be static otherwise it can get optimised away. */ ulRegTest1Counter++; } /*-----------------------------------------------------------*/ void prvRegTest2Pass( void ) { /* Called from the inline assembler - this cannot be static otherwise it can get optimised away. */ ulRegTest2Counter++; } /*-----------------------------------------------------------*/ void prvRegTestFail( void ) { /* Called from the inline assembler - this cannot be static otherwise it can get optimised away. */ xRegTestStatus = pdFAIL; } /*-----------------------------------------------------------*/ static void prvRegTestTask1( void *pvParameters ) { /* Just to remove compiler warning. */ ( void ) pvParameters; /* The first register test task as described at the top of this file. The values used in the registers are different to those use in the second register test task. Also, unlike the second register test task, this task yields between setting the register values and subsequently checking the register values. */ asm volatile ( "RegTest1Start: \n\t" \ " \n\t" \ " li 0, 301 \n\t" \ " mtspr 256, 0 #USPRG0 \n\t" \ " li 0, 501 \n\t" \ " mtspr 8, 0 #LR \n\t" \ " li 0, 4 \n\t" \ " mtspr 1, 0 #XER \n\t" \ " \n\t" \ " li 0, 1 \n\t" \ " li 2, 2 \n\t" \ " li 3, 3 \n\t" \ " li 4, 4 \n\t" \ " li 5, 5 \n\t" \ " li 6, 6 \n\t" \ " li 7, 7 \n\t" \ " li 8, 8 \n\t" \ " li 9, 9 \n\t" \ " li 10, 10 \n\t" \ " li 11, 11 \n\t" \ " li 12, 12 \n\t" \ " li 13, 13 \n\t" \ " li 14, 14 \n\t" \ " li 15, 15 \n\t" \ " li 16, 16 \n\t" \ " li 17, 17 \n\t" \ " li 18, 18 \n\t" \ " li 19, 19 \n\t" \ " li 20, 20 \n\t" \ " li 21, 21 \n\t" \ " li 22, 22 \n\t" \ " li 23, 23 \n\t" \ " li 24, 24 \n\t" \ " li 25, 25 \n\t" \ " li 26, 26 \n\t" \ " li 27, 27 \n\t" \ " li 28, 28 \n\t" \ " li 29, 29 \n\t" \ " li 30, 30 \n\t" \ " li 31, 31 \n\t" \ " \n\t" \ " sc \n\t" \ " nop \n\t" \ " \n\t" \ " cmpwi 0, 1 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 2, 2 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 3, 3 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 4, 4 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 5, 5 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 6, 6 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 7, 7 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 8, 8 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 9, 9 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 10, 10 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 11, 11 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 12, 12 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 13, 13 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 14, 14 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 15, 15 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 16, 16 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 17, 17 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 18, 18 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 19, 19 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 20, 20 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 21, 21 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 22, 22 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 23, 23 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 24, 24 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 25, 25 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 26, 26 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 27, 27 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 28, 28 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 29, 29 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 30, 30 \n\t" \ " bne RegTest1Fail \n\t" \ " cmpwi 31, 31 \n\t" \ " bne RegTest1Fail \n\t" \ " \n\t" \ " mfspr 0, 256 #USPRG0 \n\t" \ " cmpwi 0, 301 \n\t" \ " bne RegTest1Fail \n\t" \ " mfspr 0, 8 #LR \n\t" \ " cmpwi 0, 501 \n\t" \ " bne RegTest1Fail \n\t" \ " mfspr 0, 1 #XER \n\t" \ " cmpwi 0, 4 \n\t" \ " bne RegTest1Fail \n\t" \ " \n\t" \ " bl prvRegTest1Pass \n\t" \ " b RegTest1Start \n\t" \ " \n\t" \ "RegTest1Fail: \n\t" \ " \n\t" \ " \n\t" \ " bl prvRegTestFail \n\t" \ " b RegTest1Start \n\t" \ ); } /*-----------------------------------------------------------*/ static void prvRegTestTask2( void *pvParameters ) { /* Just to remove compiler warning. */ ( void ) pvParameters; /* The second register test task as described at the top of this file. Note that this task fills the registers with different values to the first register test task. */ asm volatile ( "RegTest2Start: \n\t" \ " \n\t" \ " li 0, 300 \n\t" \ " mtspr 256, 0 #USPRG0 \n\t" \ " li 0, 500 \n\t" \ " mtspr 8, 0 #LR \n\t" \ " li 0, 4 \n\t" \ " mtspr 1, 0 #XER \n\t" \ " \n\t" \ " li 0, 11 \n\t" \ " li 2, 12 \n\t" \ " li 3, 13 \n\t" \ " li 4, 14 \n\t" \ " li 5, 15 \n\t" \ " li 6, 16 \n\t" \ " li 7, 17 \n\t" \ " li 8, 18 \n\t" \ " li 9, 19 \n\t" \ " li 10, 110 \n\t" \ " li 11, 111 \n\t" \ " li 12, 112 \n\t" \ " li 13, 113 \n\t" \ " li 14, 114 \n\t" \ " li 15, 115 \n\t" \ " li 16, 116 \n\t" \ " li 17, 117 \n\t" \ " li 18, 118 \n\t" \ " li 19, 119 \n\t" \ " li 20, 120 \n\t" \ " li 21, 121 \n\t" \ " li 22, 122 \n\t" \ " li 23, 123 \n\t" \ " li 24, 124 \n\t" \ " li 25, 125 \n\t" \ " li 26, 126 \n\t" \ " li 27, 127 \n\t" \ " li 28, 128 \n\t" \ " li 29, 129 \n\t" \ " li 30, 130 \n\t" \ " li 31, 131 \n\t" \ " \n\t" \ " cmpwi 0, 11 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 2, 12 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 3, 13 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 4, 14 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 5, 15 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 6, 16 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 7, 17 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 8, 18 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 9, 19 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 10, 110 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 11, 111 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 12, 112 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 13, 113 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 14, 114 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 15, 115 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 16, 116 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 17, 117 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 18, 118 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 19, 119 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 20, 120 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 21, 121 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 22, 122 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 23, 123 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 24, 124 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 25, 125 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 26, 126 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 27, 127 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 28, 128 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 29, 129 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 30, 130 \n\t" \ " bne RegTest2Fail \n\t" \ " cmpwi 31, 131 \n\t" \ " bne RegTest2Fail \n\t" \ " \n\t" \ " mfspr 0, 256 #USPRG0 \n\t" \ " cmpwi 0, 300 \n\t" \ " bne RegTest2Fail \n\t" \ " mfspr 0, 8 #LR \n\t" \ " cmpwi 0, 500 \n\t" \ " bne RegTest2Fail \n\t" \ " mfspr 0, 1 #XER \n\t" \ " cmpwi 0, 4 \n\t" \ " bne RegTest2Fail \n\t" \ " \n\t" \ " bl prvRegTest2Pass \n\t" \ " b RegTest2Start \n\t" \ " \n\t" \ "RegTest2Fail: \n\t" \ " \n\t" \ " \n\t" \ " bl prvRegTestFail \n\t" \ " b RegTest2Start \n\t" \ ); } /*-----------------------------------------------------------*/ /* This hook function will get called if there is a suspected stack overflow. An overflow can cause the task name to be corrupted, in which case the task handle needs to be used to determine the offending task. */ void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ); void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { /* To prevent the optimiser removing the variables. */ volatile TaskHandle_t xTaskIn = xTask; volatile signed char *pcTaskNameIn = pcTaskName; /* Remove compiler warnings. */ ( void ) xTaskIn; ( void ) pcTaskNameIn; /* The following three calls are simply to stop compiler warnings about the functions not being used - they are called from the inline assembly. */ prvRegTest1Pass(); prvRegTest2Pass(); prvRegTestFail(); for( ;; ); }
RobsonRojas/frertos-udemy
FreeRTOSv9.0.0/FreeRTOS/Demo/PPC440_Xilinx_Virtex5_GCC/RTOSDemo/main.c
C
gpl-3.0
24,378
# Pacman We are two people, trying to program a game with GODOT.
MaximilianJugendForscht/Pacman
README.md
Markdown
gpl-3.0
66
# CMake generated Testfile for # Source directory: /home/zitouni/gnuradio-3.6.1/gr-uhd/grc # Build directory: /home/zitouni/gnuradio-3.6.1/build/gr-uhd/grc # # This file includes the relevent testing commands required for # testing this directory and lists subdirectories to be tested as well.
zitouni/gnuradio-3.6.1
build/gr-uhd/grc/CTestTestfile.cmake
CMake
gpl-3.0
297
-- -- Fix oracle syntax for psql -- set search_path = tm_cz, pg_catalog; DROP FUNCTION IF EXISTS tm_cz.bio_experiment_uid(character varying); \i ../../../ddl/postgres/tm_cz/functions/bio_experiment_uid.sql
transmart/transmart-data
updatedb/release-16.2/postgres/update-84g-tmcz-funcmod-bioexpuid.sql
SQL
gpl-3.0
211
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <getopt.h> #include "upgma.h" #include "utils.h" #include "seq_utils.h" #include "sequence.h" #include "seq_reader.h" #include "node.h" #include "tree.h" #include "tree_utils.h" UPGMA::UPGMA (std::istream* pios):num_taxa_(0), num_char_(0), newickstring_(""), tree_(nullptr) { std::string alphaName; // not used, but required by reader seqs_ = ingest_alignment(pios, alphaName); num_taxa_ = static_cast<int>(seqs_.size()); num_char_ = static_cast<int>(seqs_[0].get_length()); // check that it is aligned (doesn't make sense otherwise) if (!is_aligned(seqs_)) { std::cerr << "Error: sequences are not aligned. Exiting." << std::endl; exit(0); } names_ = collect_names(seqs_); full_distmatrix_ = build_matrix(); } std::vector< std::vector<double> > UPGMA::build_matrix () { // 1) skip self comparisons // 2) only calculate one half of matrix (i.e., no duplicate calcs) auto nt = static_cast<size_t>(num_taxa_); std::vector< std::vector<double> > distances(nt, std::vector<double>(nt, 0.0)); double tempScore = 0.0; for (size_t i = 0; i < nt; i++) { std::string seq1 = seqs_[i].get_sequence(); for (size_t j = (i + 1); j < nt; j++) { std::string seq2 = seqs_[j].get_sequence(); // get distance tempScore = static_cast<double>(calc_hamming_dist(seq1, seq2)); // put scale in terms of number of sites. original version did not do this tempScore /= static_cast<double>(num_char_); // put in both top and bottom of matrix, even though only top is used distances[i][j] = distances[j][i] = tempScore; } } // just for debugging /* std::cout << "\t"; for (unsigned int i = 0; i < names_.size(); i++) { std::cout << names_[i] << "\t"; } std::cout << std::endl; for (int i = 0; i < num_taxa_; i++) { std::cout << names_[i] << "\t"; for (int j = 0; j < num_taxa_; j++) { std::cout << distances[i][j] << "\t"; } std::cout << std::endl; } */ return distances; } // find smallest pairwise distance // will always find this on the top half of the matrix i.e., mini1 < mini2 double UPGMA::get_smallest_distance (const std::vector< std::vector<double> >& dmatrix, unsigned long& mini1, unsigned long& mini2) { // super large value double minD = 99999999999.99; size_t numseqs = dmatrix.size(); for (size_t i = 0; i < (numseqs - 1); i++) { auto idx = static_cast<size_t>(std::min_element(dmatrix[i].begin() + (i + 1), dmatrix[i].end()) - dmatrix[i].begin()); if (dmatrix[i][idx] < minD) { minD = dmatrix[i][idx]; mini1 = i; mini2 = idx; } } return minD; } void UPGMA::construct_tree () { // location of minimum distance (top half) unsigned long ind1 = 0; unsigned long ind2 = 0; // initialize std::vector< std::vector<double> > dMatrix = full_distmatrix_; Node * anc = nullptr; // new node, ancestor of 2 clusters Node * left = nullptr; Node * right = nullptr; auto nt = static_cast<size_t>(num_taxa_); size_t numClusters = nt; // keep list of nodes left to be clustered. initially all terminal nodes std::vector<Node *> nodes(nt); for (size_t i = 0; i < nt; i++) { auto * nd = new Node(); nd->setName(names_[i]); nd->setHeight(0.0); nodes[i] = nd; } while (numClusters > 1) { // 1. get smallest distance present in the matrix double minD = get_smallest_distance(dMatrix, ind1, ind2); left = nodes[ind1]; right = nodes[ind2]; // 2. create new ancestor node anc = new Node(); // 3. add nodes in new cluster above as children to new ancestor anc->addChild(*left); // addChild calls setParent anc->addChild(*right); // 4. compute edgelengths: half of the distance // edgelengths must subtract the existing height double newHeight = 0.5 * minD; left->setBL(newHeight - left->getHeight()); right->setBL(newHeight - right->getHeight()); // make sure to set the height of anc for the next iteration to use anc->setHeight(newHeight); // 5. compute new distance matrix (1 fewer rows & columns) // new distances are proportional averages (size of clusters) // new cluster is placed first (row & column) std::vector<double> avdists(numClusters, 0.0); double Lweight = left->isExternal() ? 1.0 : static_cast<double>(left->getChildCount()); double Rweight = right->isExternal() ? 1.0 : static_cast<double>(right->getChildCount()); for (unsigned long i = 0; i < numClusters; i++) { avdists[i] = ((dMatrix[ind1][i] * Lweight) + (dMatrix[ind2][i] * Rweight)) / (Lweight + Rweight); } numClusters--; std::vector< std::vector<double> > newDistances(numClusters, std::vector<double>(numClusters, 0.0)); // put in distances to new clusters first double tempDist = 0.0; unsigned long count = 0; for (size_t i = 0; i < nodes.size(); i++) { if (i != ind1 && i != ind2) { count++; tempDist = avdists[i]; newDistances[0][count] = tempDist; newDistances[count][0] = tempDist; } } // now, fill in remaining unsigned long icount = 1; auto ndsize = nodes.size(); for (size_t i = 0; i < ndsize; i++) { if (i != ind1 && i != ind2) { size_t jcount = 1; for (size_t j = 0; j < ndsize; j++) { if (j != ind1 && j != ind2) { newDistances[icount][jcount] = dMatrix[i][j]; newDistances[jcount][icount] = dMatrix[i][j]; jcount++; } } icount++; } } // replace distance matrix dMatrix = newDistances; // 6. finally, update node vector (1 shorter). new node always goes first) std::vector<Node *> newNodes(numClusters); newNodes[0] = anc; unsigned long counter = 1; for (unsigned long i = 0; i < ndsize; i++) { if (i != ind1 && i != ind2) { newNodes[counter] = nodes[i]; counter++; } } // replace node vector nodes = newNodes; } tree_ = new Tree(anc); tree_->setEdgeLengthsPresent(true); // used by newick writer } std::string UPGMA::get_newick () { if (newickstring_.empty()) { construct_tree(); } newickstring_ = getNewickString(tree_); return newickstring_; } std::vector< std::vector<double> > UPGMA::get_matrix () const { return full_distmatrix_; }
FePhyFoFum/phyx
src/upgma.cpp
C++
gpl-3.0
7,194
from .gaussian_process import RandomFeatureGaussianProcess, mean_field_logits from .spectral_normalization import SpectralNormalization
gagnonlg/explore-ml
sngp/tf_import/__init__.py
Python
gpl-3.0
136
/* * IIIFProducer * Copyright (C) 2017 Leipzig University Library <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package de.ubleipzig.iiifproducer.template; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import de.ubleipzig.iiif.vocabulary.IIIFEnum; /** * TemplateService. * * @author christopher-johnson */ @JsonPropertyOrder({"@context", "@id", "profile"}) public class TemplateService { @JsonProperty("@context") private String context = IIIFEnum.IMAGE_CONTEXT.IRIString(); @JsonProperty("@id") private String id; @JsonProperty private String profile = IIIFEnum.SERVICE_PROFILE.IRIString(); /** * @param id String */ public TemplateService(final String id) { this.id = id; } }
ubleipzig/iiif-producer
templates/src/main/java/de/ubleipzig/iiifproducer/template/TemplateService.java
Java
gpl-3.0
1,444
/****************************************************************************** * * Copyright 2010, Dream Chip Technologies GmbH. All rights reserved. * No part of this work may be reproduced, modified, distributed, transmitted, * transcribed, or translated into any language or computer format, in any form * or by any means without written permission of: * Dream Chip Technologies GmbH, Steinriede 10, 30827 Garbsen / Berenbostel, * Germany * *****************************************************************************/ /** * @file impexinfo.h * * @brief * Image info for import/export C++ API. * *****************************************************************************/ /** * * @mainpage Module Documentation * * * Doc-Id: xx-xxx-xxx-xxx (NAME Implementation Specification)\n * Author: NAME * * DESCRIBE_HERE * * * The manual is divided into the following sections: * * -@subpage module_name_api_page \n * -@subpage module_name_page \n * * @page module_name_api_page Module Name API * This module is the API for the NAME. DESCRIBE IN DETAIL / ADD USECASES... * * for a detailed list of api functions refer to: * - @ref module_name_api * * @defgroup module_name_api Module Name API * @{ */ #ifndef __IMPEXINFO_H__ #define __IMPEXINFO_H__ #include <string> #include <list> #include <map> class Tag { public: enum Type { TYPE_INVALID = 0, TYPE_BOOL = 1, TYPE_INT = 2, TYPE_UINT32 = 3, TYPE_FLOAT = 4, TYPE_STRING = 5 }; protected: Tag( Type type, const std::string& id ) : m_type (type), m_id (id) { } virtual ~Tag() { } public: Type type() const { return m_type; }; std::string id() const { return m_id; }; template<class T> bool getValue( T& value ) const; template<class T> bool setValue( const T& value ); virtual std::string toString() const= 0; virtual void fromString( const std::string& str ) = 0; private: friend class TagMap; Type m_type; std::string m_id; }; class TagMap { public: typedef std::list<Tag *>::const_iterator const_tag_iterator; typedef std::map<std::string, std::list<Tag *> >::const_iterator const_category_iterator; public: TagMap(); ~TagMap(); private: TagMap (const TagMap& other); TagMap& operator = (const TagMap& other); public: void clear(); bool containes( const std::string& id, const std::string& category = std::string() ) const; template<class T> void insert( const T& value, const std::string& id, const std::string& category = std::string() ); void remove( const std::string& id, const std::string& category = std::string() ); Tag *tag( const std::string& id, const std::string& category = std::string() ) const; const_category_iterator begin() const ; const_category_iterator end() const ; const_tag_iterator begin( const_category_iterator iter ) const ; const_tag_iterator end( const_category_iterator iter ) const ; private: typedef std::list<Tag *>::iterator tag_iterator; typedef std::map<std::string, std::list<Tag *> >::iterator category_iterator; std::map<std::string, std::list<Tag *> > m_data; }; /** * @brief ImageExportInfo class declaration. */ class ImageExportInfo : public TagMap { public: ImageExportInfo( const char *fileName ); ~ImageExportInfo(); public: const char *fileName() const; void write() const; private: std::string m_fileName; }; /* @} module_name_api*/ #endif /*__IMPEXINFO_H__*/
s20121035/rk3288_android5.1_repo
hardware/rockchip/camera/SiliconImage/include/isp_cam_api/cam_api/impexinfo.h
C
gpl-3.0
3,654
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using Hy.Common.Utility.Data; using System.Data.Common; using Hy.Check.Utility; namespace Hy.Check.UI.UC.Sundary { public class ResultDbOper { private IDbConnection m_ResultDbConn = null; public ResultDbOper(IDbConnection resultDb) { m_ResultDbConn = resultDb; } public DataTable GetAllResults() { DataTable res = new DataTable(); try { string strSql = string.Format("select RuleErrId,CheckType ,RuleInstID,RuleExeState,ErrorCount,TargetFeatClass1,GZBM,ErrorType from {0}", COMMONCONST.RESULT_TB_RESULT_ENTRY_RULE); return AdoDbHelper.GetDataTable(m_ResultDbConn, strSql); } catch { return res; } } public DataTable GetLayersResults() { DataTable res = new DataTable(); try { string strSql = string.Format("SELECT checkType,targetfeatclass1,sum(errorcount) as ErrCount,max(RuleErrID) as ruleId from {0} group by targetfeatclass1,checktype order by max(RuleErrID)", COMMONCONST.RESULT_TB_RESULT_ENTRY_RULE); return AdoDbHelper.GetDataTable(m_ResultDbConn, strSql); } catch { return res; } } public int GetResultsCount() { int count = 0; DbDataReader reader =null; try { string strSql = string.Format("select sum(errorcount) as cout from {0}", COMMONCONST.RESULT_TB_RESULT_ENTRY_RULE); reader = AdoDbHelper.GetQueryReader(m_ResultDbConn, strSql) as DbDataReader; if (reader.HasRows) { reader.Read(); count = int.Parse(reader[0].ToString()); } return count; } catch { return count; } finally { reader.Close(); reader.Dispose(); } } } }
hy1314200/HyDM
DataCheck/Hy.Check.UI/UC/Sundary/ResultDbOper.cs
C#
gpl-3.0
2,274
<?php namespace MikroOdeme\Enum; /** * Mikro Odeme library in PHP. * * @package mikro-odeme * @version 0.1.0 * @author Hüseyin Emre Özdemir <[email protected]> * @copyright Hüseyin Emre Özdemir <[email protected]> * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0 * @link https://github.com/ozdemirr/mikro-odeme */ class PaymentTypeId { CONST TEK_CEKIM = 1; CONST AYLIK_ABONELIK = 2; CONST HAFTALIK_ABONELIK = 3; CONST IKI_AYLIK_ABONELIK = 4; CONST UC_AYLIK_ABONELIK = 5; CONST ALTI_AYLIK_ABONELIK = 6; CONST AYLIK_DENEMELI = 7; CONST HAFTALIK_DENEMELI = 8; CONST IKI_HAFTALIK_DENEMELI = 9; CONST UC_AYLIK_DENEMELI = 10; CONST ALTI_AYLIK_DENEMELI = 11; CONST OTUZ_GUNLUK = 13; }
ozdemirr/mikro-odeme
lib/MikroOdeme/Enum/PaymentTypeId.php
PHP
gpl-3.0
802
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; namespace ChummerHub.Areas.Identity.Pages.Account.Manage { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel' public class DeletePersonalDataModel : PageModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel' { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly ILogger<DeletePersonalDataModel> _logger; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.DeletePersonalDataModel(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<DeletePersonalDataModel>)' public DeletePersonalDataModel( #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.DeletePersonalDataModel(UserManager<ApplicationUser>, SignInManager<ApplicationUser>, ILogger<DeletePersonalDataModel>)' UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<DeletePersonalDataModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.Input' public InputModel Input { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.Input' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel' public class InputModel #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel' { [Required] [DataType(DataType.Password)] #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel.Password' public string Password { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.InputModel.Password' } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.RequirePassword' public bool RequirePassword { get; set; } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.RequirePassword' #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnGet()' public async Task<IActionResult> OnGet() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnGet()' { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } RequirePassword = await _userManager.HasPasswordAsync(user); return Page(); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnPostAsync()' public async Task<IActionResult> OnPostAsync() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'DeletePersonalDataModel.OnPostAsync()' { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } RequirePassword = await _userManager.HasPasswordAsync(user); if (RequirePassword) { if (!await _userManager.CheckPasswordAsync(user, Input.Password)) { ModelState.AddModelError(string.Empty, "Password not correct."); return Page(); } } var result = await _userManager.DeleteAsync(user); var userId = await _userManager.GetUserIdAsync(user); if (!result.Succeeded) { throw new InvalidOperationException($"Unexpected error occurred deleteing user with ID '{userId}'."); } await _signInManager.SignOutAsync(); _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); return Redirect("~/"); } } }
chummer5a/chummer5a
ChummerHub/Areas/Identity/Pages/Account/Manage/DeletePersonalData.cshtml.cs
C#
gpl-3.0
4,994
namespace Grove.Artifical.TargetingRules { using System; using System.Collections.Generic; using System.Linq; using Gameplay; using Gameplay.Effects; using Gameplay.Misc; using Gameplay.Targeting; public abstract class TargetingRule : MachinePlayRule { public int? TargetLimit; public bool ConsiderTargetingSelf = true; public override void Process(Artifical.ActivationContext c) { var excludeSelf = ConsiderTargetingSelf ? null : c.Card; var candidates = c.Selector.GenerateCandidates(c.TriggerMessage, excludeSelf); var parameters = new TargetingRuleParameters(candidates, c, Game); var targetsCombinations = (TargetLimit.HasValue ? SelectTargets(parameters).Take(TargetLimit.Value) : SelectTargets(parameters)) .ToList(); if (targetsCombinations.Count == 0) { if (c.CanCancel) { c.CancelActivation = true; return; } targetsCombinations = ForceSelectTargets(parameters) .Take(Ai.Parameters.TargetCount) .ToList(); } c.SetPossibleTargets(targetsCombinations); } protected abstract IEnumerable<Targets> SelectTargets(TargetingRuleParameters p); protected virtual IEnumerable<Targets> ForceSelectTargets(TargetingRuleParameters p) { return SelectTargets(p); } protected IEnumerable<T> None<T>() { yield break; } protected IList<Targets> Group(IEnumerable<Card> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Player> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Effect> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { return Group(candidates.Cast<ITarget>().ToList(), minTargetCount, maxTargetCount, add); } protected IList<Targets> Group(IEnumerable<Card> candidates1, IEnumerable<Card> candidates2, Action<ITarget, Targets> add1 = null, Action<ITarget, Targets> add2 = null) { return Group(candidates1.Cast<ITarget>().ToList(), candidates2.Cast<ITarget>().ToList(), add1, add2); } protected IList<Targets> Group(IList<ITarget> candidates1, IList<ITarget> candidates2, Action<ITarget, Targets> add1 = null, Action<ITarget, Targets> add2 = null) { var results = new List<Targets>(); if (candidates1.Count == 0 || candidates2.Count == 0) return results; add1 = add1 ?? ((trg, trgts) => trgts.AddEffect(trg)); add2 = add2 ?? ((trg, trgts) => trgts.AddEffect(trg)); var index1 = 0; var index2 = 0; var groupCount = Math.Max(candidates1.Count, candidates2.Count); for (var i = 0; i < groupCount; i++) { // generate some options by mixing candidates // from 2 selectors var targets = new Targets(); add1(candidates1[index1], targets); add2(candidates2[index2], targets); index1++; index2++; if (index1 == candidates1.Count) index1 = 0; if (index2 == candidates2.Count) index2 = 0; results.Add(targets); } return results; } protected IList<Targets> Group(IList<ITarget> candidates, List<int> damageDistribution) { var result = new Targets(); foreach (var candidate in candidates) { result.AddEffect(candidate); } result.Distribution = damageDistribution; return new[] {result}; } protected IList<Targets> Group(IList<ITarget> candidates, int minTargetCount, int? maxTargetCount = null, Action<ITarget, Targets> add = null) { var results = new List<Targets>(); var targetCount = candidates.Count < maxTargetCount ? minTargetCount : maxTargetCount ?? minTargetCount; if (targetCount == 0) return results; if (candidates.Count < targetCount) return results; add = add ?? ((trg, trgts) => trgts.AddEffect(trg)); // generate possible groups by varying only the last element // since the number of different groups tried will be small // this is a reasonable approximation. var groupCount = candidates.Count - targetCount + 1; for (var i = 0; i < groupCount; i++) { var targets = new Targets(); // add first targetCount - 1 for (var j = 0; j < targetCount - 1; j++) { add(candidates[j], targets); } // add last add(candidates[targetCount - 1 + i], targets); results.Add(targets); } return results; } protected int CalculateAttackerScoreForThisTurn(Card attacker) { if (!attacker.CanAttack) return -1; return Combat.CouldBeBlockedByAny(attacker) ? 2 * attacker.Power.GetValueOrDefault() + attacker.Toughness.GetValueOrDefault() : 5 * attacker.CalculateCombatDamageAmount(singleDamageStep: false); } protected static int CalculateAttackingPotential(Card creature) { if (!creature.IsAbleToAttack) return 0; var damage = creature.CalculateCombatDamageAmount(singleDamageStep: false); if (creature.Has().AnyEvadingAbility) return 2 + damage; return damage; } protected int CalculateBlockerScore(Card card) { var count = Combat.CountHowManyThisCouldBlock(card); if (count > 0) { return count*10 + card.Toughness.GetValueOrDefault(); } return 0; } protected IEnumerable<Card> GetCandidatesForAttackerPowerToughnessIncrease(int? powerIncrease, int? toughnessIncrease, TargetingRuleParameters p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsAttacker) .Select( x => new { Card = x, Gain = QuickCombat.CalculateGainAttackerWouldGetIfPowerAndThoughnessWouldIncrease( attacker: x, blockers: Combat.GetBlockers(x), powerIncrease: powerIncrease.Value, toughnessIncrease: toughnessIncrease.Value) }) .Where(x => x.Gain > 0) .OrderByDescending(x => x.Gain) .Select(x => x.Card); } protected IEnumerable<Card> GetCandidatesForBlockerPowerToughnessIncrease(int? powerIncrease, int? toughnessIncrease, TargetingRuleParameters p) { return p.Candidates<Card>(ControlledBy.SpellOwner) .Where(x => x.IsBlocker) .Select( x => new { Card = x, Gain = QuickCombat.CalculateGainBlockerWouldGetIfPowerAndThougnessWouldIncrease( blocker: x, attacker: Combat.GetAttacker(x), powerIncrease: powerIncrease.Value, toughnessIncrease: toughnessIncrease.Value) }) .Where(x => x.Gain > 0) .OrderByDescending(x => x.Gain) .Select(x => x.Card); } protected IEnumerable<Card> GetCandidatesThatCanBeDestroyed(TargetingRuleParameters p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.SpellOwner, selector: selector) .Where(x => Stack.CanBeDestroyedByTopSpell(x.Card()) || Combat.CanBeDealtLeathalCombatDamage(x.Card())); } protected static IEnumerable<Card> GetBounceCandidates(TargetingRuleParameters p, Func<TargetsCandidates, IList<TargetCandidates>> selector = null) { return p.Candidates<Card>(ControlledBy.Opponent, selector: selector) .Select(x => new { Card = x, Score = x.Owner == p.Controller ? 2*x.Score : x.Score }) .OrderByDescending(x => x.Score) .Select(x => x.Card); } } }
sorab2142/sorabpithawala-magicgrove
source/Grove/Artifical/TargetingRules/TargetingRule.cs
C#
gpl-3.0
8,371
package com.pix.mind.controllers; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.pix.mind.PixMindGame; import com.pix.mind.box2d.bodies.PixGuy; public class KeyboardController extends PixGuyController { boolean movingLeft = false; boolean movingRight = false; public KeyboardController(PixGuy pixGuy, Stage stage) { super(pixGuy); stage.addListener(new InputListener(){ @Override public boolean keyDown(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingLeft = true; movingRight = false; } if (keycode == Keys.RIGHT) { movingRight = true; movingLeft = false; } return true; } @Override public boolean keyUp(InputEvent event, int keycode) { // TODO Auto-generated method stub if (keycode == Keys.LEFT) { movingRight = true; movingLeft = false; } if (keycode == Keys.RIGHT) { movingLeft = true; movingRight = false; } if (!Gdx.input.isKeyPressed(Keys.RIGHT)&& !Gdx.input.isKeyPressed(Keys.LEFT)) { movingRight = false; movingLeft = false; } return true; } }); } public void movements() { if (movingLeft) { pixGuy.moveLeft(Gdx.graphics.getDeltaTime()); } if (movingRight) { pixGuy.moveRight(Gdx.graphics.getDeltaTime()); } if(!movingLeft&&!movingRight){ // if it is not touched, set horizontal velocity to 0 to // eliminate inercy. pixGuy.body.setLinearVelocity(0, pixGuy.body.getLinearVelocity().y); } } }
tuxskar/pixmind
pixmind/src/com/pix/mind/controllers/KeyboardController.java
Java
gpl-3.0
1,788
#include "buttons.c"
jsoloPDX/Inductive-Proximity-MIDI-Controller-PSU-Capstone-Project-11
T11-firmware/buttons.h
C
gpl-3.0
21
import unittest from test import support import os import io import socket import urllib.request from urllib.request import Request, OpenerDirector # XXX # Request # CacheFTPHandler (hard to write) # parse_keqv_list, parse_http_list, HTTPDigestAuthHandler class TrivialTests(unittest.TestCase): def test_trivial(self): # A couple trivial tests self.assertRaises(ValueError, urllib.request.urlopen, 'bogus url') # XXX Name hacking to get this to work on Windows. fname = os.path.abspath(urllib.request.__file__).replace('\\', '/') # And more hacking to get it to work on MacOS. This assumes # urllib.pathname2url works, unfortunately... if os.name == 'mac': fname = '/' + fname.replace(':', '/') if os.name == 'nt': file_url = "file:///%s" % fname else: file_url = "file://%s" % fname f = urllib.request.urlopen(file_url) buf = f.read() f.close() def test_parse_http_list(self): tests = [ ('a,b,c', ['a', 'b', 'c']), ('path"o,l"og"i"cal, example', ['path"o,l"og"i"cal', 'example']), ('a, b, "c", "d", "e,f", g, h', ['a', 'b', '"c"', '"d"', '"e,f"', 'g', 'h']), ('a="b\\"c", d="e\\,f", g="h\\\\i"', ['a="b"c"', 'd="e,f"', 'g="h\\i"'])] for string, list in tests: self.assertEqual(urllib.request.parse_http_list(string), list) def test_request_headers_dict(): """ The Request.headers dictionary is not a documented interface. It should stay that way, because the complete set of headers are only accessible through the .get_header(), .has_header(), .header_items() interface. However, .headers pre-dates those methods, and so real code will be using the dictionary. The introduction in 2.4 of those methods was a mistake for the same reason: code that previously saw all (urllib2 user)-provided headers in .headers now sees only a subset (and the function interface is ugly and incomplete). A better change would have been to replace .headers dict with a dict subclass (or UserDict.DictMixin instance?) that preserved the .headers interface and also provided access to the "unredirected" headers. It's probably too late to fix that, though. Check .capitalize() case normalization: >>> url = "http://example.com" >>> Request(url, headers={"Spam-eggs": "blah"}).headers["Spam-eggs"] 'blah' >>> Request(url, headers={"spam-EggS": "blah"}).headers["Spam-eggs"] 'blah' Currently, Request(url, "Spam-eggs").headers["Spam-Eggs"] raises KeyError, but that could be changed in future. """ def test_request_headers_methods(): """ Note the case normalization of header names here, to .capitalize()-case. This should be preserved for backwards-compatibility. (In the HTTP case, normalization to .title()-case is done by urllib2 before sending headers to http.client). >>> url = "http://example.com" >>> r = Request(url, headers={"Spam-eggs": "blah"}) >>> r.has_header("Spam-eggs") True >>> r.header_items() [('Spam-eggs', 'blah')] >>> r.add_header("Foo-Bar", "baz") >>> items = sorted(r.header_items()) >>> items [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')] Note that e.g. r.has_header("spam-EggS") is currently False, and r.get_header("spam-EggS") returns None, but that could be changed in future. >>> r.has_header("Not-there") False >>> print(r.get_header("Not-there")) None >>> r.get_header("Not-there", "default") 'default' """ def test_password_manager(self): """ >>> mgr = urllib.request.HTTPPasswordMgr() >>> add = mgr.add_password >>> add("Some Realm", "http://example.com/", "joe", "password") >>> add("Some Realm", "http://example.com/ni", "ni", "ni") >>> add("c", "http://example.com/foo", "foo", "ni") >>> add("c", "http://example.com/bar", "bar", "nini") >>> add("b", "http://example.com/", "first", "blah") >>> add("b", "http://example.com/", "second", "spam") >>> add("a", "http://example.com", "1", "a") >>> add("Some Realm", "http://c.example.com:3128", "3", "c") >>> add("Some Realm", "d.example.com", "4", "d") >>> add("Some Realm", "e.example.com:3128", "5", "e") >>> mgr.find_user_password("Some Realm", "example.com") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com/") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com/spam") ('joe', 'password') >>> mgr.find_user_password("Some Realm", "http://example.com/spam/spam") ('joe', 'password') >>> mgr.find_user_password("c", "http://example.com/foo") ('foo', 'ni') >>> mgr.find_user_password("c", "http://example.com/bar") ('bar', 'nini') Actually, this is really undefined ATM ## Currently, we use the highest-level path where more than one match: ## >>> mgr.find_user_password("Some Realm", "http://example.com/ni") ## ('joe', 'password') Use latest add_password() in case of conflict: >>> mgr.find_user_password("b", "http://example.com/") ('second', 'spam') No special relationship between a.example.com and example.com: >>> mgr.find_user_password("a", "http://example.com/") ('1', 'a') >>> mgr.find_user_password("a", "http://a.example.com/") (None, None) Ports: >>> mgr.find_user_password("Some Realm", "c.example.com") (None, None) >>> mgr.find_user_password("Some Realm", "c.example.com:3128") ('3', 'c') >>> mgr.find_user_password("Some Realm", "http://c.example.com:3128") ('3', 'c') >>> mgr.find_user_password("Some Realm", "d.example.com") ('4', 'd') >>> mgr.find_user_password("Some Realm", "e.example.com:3128") ('5', 'e') """ pass def test_password_manager_default_port(self): """ >>> mgr = urllib.request.HTTPPasswordMgr() >>> add = mgr.add_password The point to note here is that we can't guess the default port if there's no scheme. This applies to both add_password and find_user_password. >>> add("f", "http://g.example.com:80", "10", "j") >>> add("g", "http://h.example.com", "11", "k") >>> add("h", "i.example.com:80", "12", "l") >>> add("i", "j.example.com", "13", "m") >>> mgr.find_user_password("f", "g.example.com:100") (None, None) >>> mgr.find_user_password("f", "g.example.com:80") ('10', 'j') >>> mgr.find_user_password("f", "g.example.com") (None, None) >>> mgr.find_user_password("f", "http://g.example.com:100") (None, None) >>> mgr.find_user_password("f", "http://g.example.com:80") ('10', 'j') >>> mgr.find_user_password("f", "http://g.example.com") ('10', 'j') >>> mgr.find_user_password("g", "h.example.com") ('11', 'k') >>> mgr.find_user_password("g", "h.example.com:80") ('11', 'k') >>> mgr.find_user_password("g", "http://h.example.com:80") ('11', 'k') >>> mgr.find_user_password("h", "i.example.com") (None, None) >>> mgr.find_user_password("h", "i.example.com:80") ('12', 'l') >>> mgr.find_user_password("h", "http://i.example.com:80") ('12', 'l') >>> mgr.find_user_password("i", "j.example.com") ('13', 'm') >>> mgr.find_user_password("i", "j.example.com:80") (None, None) >>> mgr.find_user_password("i", "http://j.example.com") ('13', 'm') >>> mgr.find_user_password("i", "http://j.example.com:80") (None, None) """ class MockOpener: addheaders = [] def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.req, self.data, self.timeout = req, data, timeout def error(self, proto, *args): self.proto, self.args = proto, args class MockFile: def read(self, count=None): pass def readline(self, count=None): pass def close(self): pass class MockHeaders(dict): def getheaders(self, name): return list(self.values()) class MockResponse(io.StringIO): def __init__(self, code, msg, headers, data, url=None): io.StringIO.__init__(self, data) self.code, self.msg, self.headers, self.url = code, msg, headers, url def info(self): return self.headers def geturl(self): return self.url class MockCookieJar: def add_cookie_header(self, request): self.ach_req = request def extract_cookies(self, response, request): self.ec_req, self.ec_r = request, response class FakeMethod: def __init__(self, meth_name, action, handle): self.meth_name = meth_name self.handle = handle self.action = action def __call__(self, *args): return self.handle(self.meth_name, self.action, *args) class MockHTTPResponse(io.IOBase): def __init__(self, fp, msg, status, reason): self.fp = fp self.msg = msg self.status = status self.reason = reason self.code = 200 def read(self): return '' def info(self): return {} def geturl(self): return self.url class MockHTTPClass: def __init__(self): self.level = 0 self.req_headers = [] self.data = None self.raise_on_endheaders = False self._tunnel_headers = {} def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.host = host self.timeout = timeout return self def set_debuglevel(self, level): self.level = level def _set_tunnel(self, host, port=None, headers=None): self._tunnel_host = host self._tunnel_port = port if headers: self._tunnel_headers = headers else: self._tunnel_headers.clear() def request(self, method, url, body=None, headers=None): self.method = method self.selector = url if headers is not None: self.req_headers += headers.items() self.req_headers.sort() if body: self.data = body if self.raise_on_endheaders: import socket raise socket.error() def getresponse(self): return MockHTTPResponse(MockFile(), {}, 200, "OK") class MockHandler: # useful for testing handler machinery # see add_ordered_mock_handlers() docstring handler_order = 500 def __init__(self, methods): self._define_methods(methods) def _define_methods(self, methods): for spec in methods: if len(spec) == 2: name, action = spec else: name, action = spec, None meth = FakeMethod(name, action, self.handle) setattr(self.__class__, name, meth) def handle(self, fn_name, action, *args, **kwds): self.parent.calls.append((self, fn_name, args, kwds)) if action is None: return None elif action == "return self": return self elif action == "return response": res = MockResponse(200, "OK", {}, "") return res elif action == "return request": return Request("http://blah/") elif action.startswith("error"): code = action[action.rfind(" ")+1:] try: code = int(code) except ValueError: pass res = MockResponse(200, "OK", {}, "") return self.parent.error("http", args[0], res, code, "", {}) elif action == "raise": raise urllib.error.URLError("blah") assert False def close(self): pass def add_parent(self, parent): self.parent = parent self.parent.calls = [] def __lt__(self, other): if not hasattr(other, "handler_order"): # No handler_order, leave in original order. Yuck. return True return self.handler_order < other.handler_order def add_ordered_mock_handlers(opener, meth_spec): """Create MockHandlers and add them to an OpenerDirector. meth_spec: list of lists of tuples and strings defining methods to define on handlers. eg: [["http_error", "ftp_open"], ["http_open"]] defines methods .http_error() and .ftp_open() on one handler, and .http_open() on another. These methods just record their arguments and return None. Using a tuple instead of a string causes the method to perform some action (see MockHandler.handle()), eg: [["http_error"], [("http_open", "return request")]] defines .http_error() on one handler (which simply returns None), and .http_open() on another handler, which returns a Request object. """ handlers = [] count = 0 for meths in meth_spec: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order += count h.add_parent(opener) count = count + 1 handlers.append(h) opener.add_handler(h) return handlers def build_test_opener(*handler_instances): opener = OpenerDirector() for h in handler_instances: opener.add_handler(h) return opener class MockHTTPHandler(urllib.request.BaseHandler): # useful for testing redirections and auth # sends supplied headers and code as first response # sends 200 OK as second response def __init__(self, code, headers): self.code = code self.headers = headers self.reset() def reset(self): self._count = 0 self.requests = [] def http_open(self, req): import email, http.client, copy from io import StringIO self.requests.append(copy.deepcopy(req)) if self._count == 0: self._count = self._count + 1 name = http.client.responses[self.code] msg = email.message_from_string(self.headers) return self.parent.error( "http", req, MockFile(), self.code, name, msg) else: self.req = req msg = email.message_from_string("\r\n\r\n") return MockResponse(200, "OK", msg, "", req.get_full_url()) class MockHTTPSHandler(urllib.request.AbstractHTTPHandler): # Useful for testing the Proxy-Authorization request by verifying the # properties of httpcon def __init__(self): urllib.request.AbstractHTTPHandler.__init__(self) self.httpconn = MockHTTPClass() def https_open(self, req): return self.do_open(self.httpconn, req) class MockPasswordManager: def add_password(self, realm, uri, user, password): self.realm = realm self.url = uri self.user = user self.password = password def find_user_password(self, realm, authuri): self.target_realm = realm self.target_url = authuri return self.user, self.password class OpenerDirectorTests(unittest.TestCase): def test_add_non_handler(self): class NonHandler(object): pass self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) def test_badly_named_methods(self): # test work-around for three methods that accidentally follow the # naming conventions for handler methods # (*_open() / *_request() / *_response()) # These used to call the accidentally-named methods, causing a # TypeError in real code; here, returning self from these mock # methods would either cause no exception, or AttributeError. from urllib.error import URLError o = OpenerDirector() meth_spec = [ [("do_open", "return self"), ("proxy_open", "return self")], [("redirect_request", "return self")], ] handlers = add_ordered_mock_handlers(o, meth_spec) o.add_handler(urllib.request.UnknownHandler()) for scheme in "do", "proxy", "redirect": self.assertRaises(URLError, o.open, scheme+"://example.com/") def test_handled(self): # handler returning non-None means no more handlers will be called o = OpenerDirector() meth_spec = [ ["http_open", "ftp_open", "http_error_302"], ["ftp_open"], [("http_open", "return self")], [("http_open", "return self")], ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://example.com/") r = o.open(req) # Second .http_open() gets called, third doesn't, since second returned # non-None. Handlers without .http_open() never get any methods called # on them. # In fact, second mock handler defining .http_open() returns self # (instead of response), which becomes the OpenerDirector's return # value. self.assertEqual(r, handlers[2]) calls = [(handlers[0], "http_open"), (handlers[2], "http_open")] for expected, got in zip(calls, o.calls): handler, name, args, kwds = got self.assertEqual((handler, name), expected) self.assertEqual(args, (req,)) def test_handler_order(self): o = OpenerDirector() handlers = [] for meths, handler_order in [ ([("http_open", "return self")], 500), (["http_open"], 0), ]: class MockHandlerSubclass(MockHandler): pass h = MockHandlerSubclass(meths) h.handler_order = handler_order handlers.append(h) o.add_handler(h) r = o.open("http://example.com/") # handlers called in reverse order, thanks to their sort order self.assertEqual(o.calls[0][0], handlers[1]) self.assertEqual(o.calls[1][0], handlers[0]) def test_raise(self): # raising URLError stops processing of request o = OpenerDirector() meth_spec = [ [("http_open", "raise")], [("http_open", "return self")], ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://example.com/") self.assertRaises(urllib.error.URLError, o.open, req) self.assertEqual(o.calls, [(handlers[0], "http_open", (req,), {})]) ## def test_error(self): ## # XXX this doesn't actually seem to be used in standard library, ## # but should really be tested anyway... def test_http_error(self): # XXX http_error_default # http errors are a special case o = OpenerDirector() meth_spec = [ [("http_open", "error 302")], [("http_error_400", "raise"), "http_open"], [("http_error_302", "return response"), "http_error_303", "http_error"], [("http_error_302")], ] handlers = add_ordered_mock_handlers(o, meth_spec) class Unknown: def __eq__(self, other): return True req = Request("http://example.com/") r = o.open(req) assert len(o.calls) == 2 calls = [(handlers[0], "http_open", (req,)), (handlers[2], "http_error_302", (req, Unknown(), 302, "", {}))] for expected, got in zip(calls, o.calls): handler, method_name, args = expected self.assertEqual((handler, method_name), got[:2]) self.assertEqual(args, got[2]) def test_processors(self): # *_request / *_response methods get called appropriately o = OpenerDirector() meth_spec = [ [("http_request", "return request"), ("http_response", "return response")], [("http_request", "return request"), ("http_response", "return response")], ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://example.com/") r = o.open(req) # processor methods are called on *all* handlers that define them, # not just the first handler that handles the request calls = [ (handlers[0], "http_request"), (handlers[1], "http_request"), (handlers[0], "http_response"), (handlers[1], "http_response")] for i, (handler, name, args, kwds) in enumerate(o.calls): if i < 2: # *_request self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 1) self.assertTrue(isinstance(args[0], Request)) else: # *_response self.assertEqual((handler, name), calls[i]) self.assertEqual(len(args), 2) self.assertTrue(isinstance(args[0], Request)) # response from opener.open is None, because there's no # handler that defines http_open to handle it self.assertTrue(args[1] is None or isinstance(args[1], MockResponse)) def sanepathname2url(path): urlpath = urllib.request.pathname2url(path) if os.name == "nt" and urlpath.startswith("///"): urlpath = urlpath[2:] # XXX don't ask me about the mac... return urlpath class HandlerTests(unittest.TestCase): def test_ftp(self): class MockFTPWrapper: def __init__(self, data): self.data = data def retrfile(self, filename, filetype): self.filename, self.filetype = filename, filetype return io.StringIO(self.data), len(self.data) class NullFTPHandler(urllib.request.FTPHandler): def __init__(self, data): self.data = data def connect_ftp(self, user, passwd, host, port, dirs, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): self.user, self.passwd = user, passwd self.host, self.port = host, port self.dirs = dirs self.ftpwrapper = MockFTPWrapper(self.data) return self.ftpwrapper import ftplib data = "rheum rhaponicum" h = NullFTPHandler(data) o = h.parent = MockOpener() for url, host, port, user, passwd, type_, dirs, filename, mimetype in [ ("ftp://localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://%25parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "%parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://%2542parrot@localhost/foo/bar/baz.html", "localhost", ftplib.FTP_PORT, "%42parrot", "", "I", ["foo", "bar"], "baz.html", "text/html"), ("ftp://localhost:80/foo/bar/", "localhost", 80, "", "", "D", ["foo", "bar"], "", None), ("ftp://localhost/baz.gif;type=a", "localhost", ftplib.FTP_PORT, "", "", "A", [], "baz.gif", None), # XXX really this should guess image/gif ]: req = Request(url) req.timeout = None r = h.ftp_open(req) # ftp authentication not yet implemented by FTPHandler self.assertEqual(h.user, user) self.assertEqual(h.passwd, passwd) self.assertEqual(h.host, socket.gethostbyname(host)) self.assertEqual(h.port, port) self.assertEqual(h.dirs, dirs) self.assertEqual(h.ftpwrapper.filename, filename) self.assertEqual(h.ftpwrapper.filetype, type_) headers = r.info() self.assertEqual(headers.get("Content-type"), mimetype) self.assertEqual(int(headers["Content-length"]), len(data)) def test_file(self): import email.utils, socket h = urllib.request.FileHandler() o = h.parent = MockOpener() TESTFN = support.TESTFN urlpath = sanepathname2url(os.path.abspath(TESTFN)) towrite = b"hello, world\n" urls = [ "file://localhost%s" % urlpath, "file://%s" % urlpath, "file://%s%s" % (socket.gethostbyname('localhost'), urlpath), ] try: localaddr = socket.gethostbyname(socket.gethostname()) except socket.gaierror: localaddr = '' if localaddr: urls.append("file://%s%s" % (localaddr, urlpath)) for url in urls: f = open(TESTFN, "wb") try: try: f.write(towrite) finally: f.close() r = h.file_open(Request(url)) try: data = r.read() headers = r.info() respurl = r.geturl() finally: r.close() stats = os.stat(TESTFN) modified = email.utils.formatdate(stats.st_mtime, usegmt=True) finally: os.remove(TESTFN) self.assertEqual(data, towrite) self.assertEqual(headers["Content-type"], "text/plain") self.assertEqual(headers["Content-length"], "13") self.assertEqual(headers["Last-modified"], modified) self.assertEqual(respurl, url) for url in [ "file://localhost:80%s" % urlpath, "file:///file_does_not_exist.txt", "file://%s:80%s/%s" % (socket.gethostbyname('localhost'), os.getcwd(), TESTFN), "file://somerandomhost.ontheinternet.com%s/%s" % (os.getcwd(), TESTFN), ]: try: f = open(TESTFN, "wb") try: f.write(towrite) finally: f.close() self.assertRaises(urllib.error.URLError, h.file_open, Request(url)) finally: os.remove(TESTFN) h = urllib.request.FileHandler() o = h.parent = MockOpener() # XXXX why does // mean ftp (and /// mean not ftp!), and where # is file: scheme specified? I think this is really a bug, and # what was intended was to distinguish between URLs like: # file:/blah.txt (a file) # file://localhost/blah.txt (a file) # file:///blah.txt (a file) # file://ftp.example.com/blah.txt (an ftp URL) for url, ftp in [ ("file://ftp.example.com//foo.txt", True), ("file://ftp.example.com///foo.txt", False), # XXXX bug: fails with OSError, should be URLError ("file://ftp.example.com/foo.txt", False), ("file://somehost//foo/something.txt", True), ("file://localhost//foo/something.txt", False), ]: req = Request(url) try: h.file_open(req) # XXXX remove OSError when bug fixed except (urllib.error.URLError, OSError): self.assertFalse(ftp) else: self.assertIs(o.req, req) self.assertEqual(req.type, "ftp") self.assertEqual(req.type is "ftp", ftp) def test_http(self): h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() url = "http://example.com/" for method, data in [("GET", None), ("POST", "blah")]: req = Request(url, data, {"Foo": "bar"}) req.timeout = None req.add_unredirected_header("Spam", "eggs") http = MockHTTPClass() r = h.do_open(http, req) # result attributes r.read; r.readline # wrapped MockFile methods r.info; r.geturl # addinfourl methods r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply() hdrs = r.info() hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply() self.assertEqual(r.geturl(), url) self.assertEqual(http.host, "example.com") self.assertEqual(http.level, 0) self.assertEqual(http.method, method) self.assertEqual(http.selector, "/") self.assertEqual(http.req_headers, [("Connection", "close"), ("Foo", "bar"), ("Spam", "eggs")]) self.assertEqual(http.data, data) # check socket.error converted to URLError http.raise_on_endheaders = True self.assertRaises(urllib.error.URLError, h.do_open, http, req) # check adding of standard headers o.addheaders = [("Spam", "eggs")] for data in "", None: # POST, GET req = Request("http://example.com/", data) r = MockResponse(200, "OK", {}, "") newreq = h.do_request_(req) if data is None: # GET self.assertTrue("Content-length" not in req.unredirected_hdrs) self.assertTrue("Content-type" not in req.unredirected_hdrs) else: # POST self.assertEqual(req.unredirected_hdrs["Content-length"], "0") self.assertEqual(req.unredirected_hdrs["Content-type"], "application/x-www-form-urlencoded") # XXX the details of Host could be better tested self.assertEqual(req.unredirected_hdrs["Host"], "example.com") self.assertEqual(req.unredirected_hdrs["Spam"], "eggs") # don't clobber existing headers req.add_unredirected_header("Content-length", "foo") req.add_unredirected_header("Content-type", "bar") req.add_unredirected_header("Host", "baz") req.add_unredirected_header("Spam", "foo") newreq = h.do_request_(req) self.assertEqual(req.unredirected_hdrs["Content-length"], "foo") self.assertEqual(req.unredirected_hdrs["Content-type"], "bar") self.assertEqual(req.unredirected_hdrs["Host"], "baz") self.assertEqual(req.unredirected_hdrs["Spam"], "foo") def test_http_doubleslash(self): # Checks the presence of any unnecessary double slash in url does not # break anything. Previously, a double slash directly after the host # could could cause incorrect parsing. h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() data = "" ds_urls = [ "http://example.com/foo/bar/baz.html", "http://example.com//foo/bar/baz.html", "http://example.com/foo//bar/baz.html", "http://example.com/foo/bar//baz.html" ] for ds_url in ds_urls: ds_req = Request(ds_url, data) # Check whether host is determined correctly if there is no proxy np_ds_req = h.do_request_(ds_req) self.assertEqual(np_ds_req.unredirected_hdrs["Host"],"example.com") # Check whether host is determined correctly if there is a proxy ds_req.set_proxy("someproxy:3128",None) p_ds_req = h.do_request_(ds_req) self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com") def test_fixpath_in_weirdurls(self): # Issue4493: urllib2 to supply '/' when to urls where path does not # start with'/' h = urllib.request.AbstractHTTPHandler() o = h.parent = MockOpener() weird_url = 'http://www.python.org?getspam' req = Request(weird_url) newreq = h.do_request_(req) self.assertEqual(newreq.host,'www.python.org') self.assertEqual(newreq.selector,'/?getspam') url_without_path = 'http://www.python.org' req = Request(url_without_path) newreq = h.do_request_(req) self.assertEqual(newreq.host,'www.python.org') self.assertEqual(newreq.selector,'') def test_errors(self): h = urllib.request.HTTPErrorProcessor() o = h.parent = MockOpener() url = "http://example.com/" req = Request(url) # all 2xx are passed through r = MockResponse(200, "OK", {}, "", url) newr = h.http_response(req, r) self.assertIs(r, newr) self.assertFalse(hasattr(o, "proto")) # o.error not called r = MockResponse(202, "Accepted", {}, "", url) newr = h.http_response(req, r) self.assertIs(r, newr) self.assertFalse(hasattr(o, "proto")) # o.error not called r = MockResponse(206, "Partial content", {}, "", url) newr = h.http_response(req, r) self.assertIs(r, newr) self.assertFalse(hasattr(o, "proto")) # o.error not called # anything else calls o.error (and MockOpener returns None, here) r = MockResponse(502, "Bad gateway", {}, "", url) self.assertIsNone(h.http_response(req, r)) self.assertEqual(o.proto, "http") # o.error called self.assertEqual(o.args, (req, r, 502, "Bad gateway", {})) def test_cookies(self): cj = MockCookieJar() h = urllib.request.HTTPCookieProcessor(cj) o = h.parent = MockOpener() req = Request("http://example.com/") r = MockResponse(200, "OK", {}, "") newreq = h.http_request(req) self.assertIs(cj.ach_req, req) self.assertIs(cj.ach_req, newreq) self.assertEqual(req.get_origin_req_host(), "example.com") self.assertFalse(req.is_unverifiable()) newr = h.http_response(req, r) self.assertIs(cj.ec_req, req) self.assertIs(cj.ec_r, r) self.assertIs(r, newr) def test_redirect(self): from_url = "http://example.com/a.html" to_url = "http://example.com/b.html" h = urllib.request.HTTPRedirectHandler() o = h.parent = MockOpener() # ordinary redirect behaviour for code in 301, 302, 303, 307: for data in None, "blah\nblah\n": method = getattr(h, "http_error_%s" % code) req = Request(from_url, data) req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT req.add_header("Nonsense", "viking=withhold") if data is not None: req.add_header("Content-Length", str(len(data))) req.add_unredirected_header("Spam", "spam") try: method(req, MockFile(), code, "Blah", MockHeaders({"location": to_url})) except urllib.error.HTTPError: # 307 in response to POST requires user OK self.assertTrue(code == 307 and data is not None) self.assertEqual(o.req.get_full_url(), to_url) try: self.assertEqual(o.req.get_method(), "GET") except AttributeError: self.assertFalse(o.req.has_data()) # now it's a GET, there should not be headers regarding content # (possibly dragged from before being a POST) headers = [x.lower() for x in o.req.headers] self.assertTrue("content-length" not in headers) self.assertTrue("content-type" not in headers) self.assertEqual(o.req.headers["Nonsense"], "viking=withhold") self.assertTrue("Spam" not in o.req.headers) self.assertTrue("Spam" not in o.req.unredirected_hdrs) # loop detection req = Request(from_url) req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT def redirect(h, req, url=to_url): h.http_error_302(req, MockFile(), 302, "Blah", MockHeaders({"location": url})) # Note that the *original* request shares the same record of # redirections with the sub-requests caused by the redirections. # detect infinite loop redirect of a URL to itself req = Request(from_url, origin_req_host="example.com") count = 0 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT try: while 1: redirect(h, req, "http://example.com/") count = count + 1 except urllib.error.HTTPError: # don't stop until max_repeats, because cookies may introduce state self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_repeats) # detect endless non-repeating chain of redirects req = Request(from_url, origin_req_host="example.com") count = 0 req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT try: while 1: redirect(h, req, "http://example.com/%d" % count) count = count + 1 except urllib.error.HTTPError: self.assertEqual(count, urllib.request.HTTPRedirectHandler.max_redirections) def test_cookie_redirect(self): # cookies shouldn't leak into redirected requests from http.cookiejar import CookieJar from test.test_http_cookiejar import interact_netscape cj = CookieJar() interact_netscape(cj, "http://www.example.com/", "spam=eggs") hh = MockHTTPHandler(302, "Location: http://www.cracker.com/\r\n\r\n") hdeh = urllib.request.HTTPDefaultErrorHandler() hrh = urllib.request.HTTPRedirectHandler() cp = urllib.request.HTTPCookieProcessor(cj) o = build_test_opener(hh, hdeh, hrh, cp) o.open("http://www.example.com/") self.assertFalse(hh.req.has_header("Cookie")) def test_proxy(self): o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) o.add_handler(ph) meth_spec = [ [("http_open", "return response")] ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("http://acme.example.com/") self.assertEqual(req.get_host(), "acme.example.com") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual([(handlers[0], "http_open")], [tup[0:2] for tup in o.calls]) def test_proxy_no_proxy(self): os.environ['no_proxy'] = 'python.org' o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com")) o.add_handler(ph) req = Request("http://www.perl.org/") self.assertEqual(req.get_host(), "www.perl.org") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com") req = Request("http://www.python.org") self.assertEqual(req.get_host(), "www.python.org") r = o.open(req) self.assertEqual(req.get_host(), "www.python.org") del os.environ['no_proxy'] def test_proxy_https(self): o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(https="proxy.example.com:3128")) o.add_handler(ph) meth_spec = [ [("https_open", "return response")] ] handlers = add_ordered_mock_handlers(o, meth_spec) req = Request("https://www.example.com/") self.assertEqual(req.get_host(), "www.example.com") r = o.open(req) self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual([(handlers[0], "https_open")], [tup[0:2] for tup in o.calls]) def test_proxy_https_proxy_authorization(self): o = OpenerDirector() ph = urllib.request.ProxyHandler(dict(https='proxy.example.com:3128')) o.add_handler(ph) https_handler = MockHTTPSHandler() o.add_handler(https_handler) req = Request("https://www.example.com/") req.add_header("Proxy-Authorization","FooBar") req.add_header("User-Agent","Grail") self.assertEqual(req.get_host(), "www.example.com") self.assertIsNone(req._tunnel_host) r = o.open(req) # Verify Proxy-Authorization gets tunneled to request. # httpsconn req_headers do not have the Proxy-Authorization header but # the req will have. self.assertFalse(("Proxy-Authorization","FooBar") in https_handler.httpconn.req_headers) self.assertTrue(("User-Agent","Grail") in https_handler.httpconn.req_headers) self.assertIsNotNone(req._tunnel_host) self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual(req.get_header("Proxy-authorization"),"FooBar") def test_basic_auth(self, quote_char='"'): opener = OpenerDirector() password_manager = MockPasswordManager() auth_handler = urllib.request.HTTPBasicAuthHandler(password_manager) realm = "ACME Widget Store" http_handler = MockHTTPHandler( 401, 'WWW-Authenticate: Basic realm=%s%s%s\r\n\r\n' % (quote_char, realm, quote_char) ) opener.add_handler(auth_handler) opener.add_handler(http_handler) self._test_basic_auth(opener, auth_handler, "Authorization", realm, http_handler, password_manager, "http://acme.example.com/protected", "http://acme.example.com/protected", ) def test_basic_auth_with_single_quoted_realm(self): self.test_basic_auth(quote_char="'") def test_proxy_basic_auth(self): opener = OpenerDirector() ph = urllib.request.ProxyHandler(dict(http="proxy.example.com:3128")) opener.add_handler(ph) password_manager = MockPasswordManager() auth_handler = urllib.request.ProxyBasicAuthHandler(password_manager) realm = "ACME Networks" http_handler = MockHTTPHandler( 407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm) opener.add_handler(auth_handler) opener.add_handler(http_handler) self._test_basic_auth(opener, auth_handler, "Proxy-authorization", realm, http_handler, password_manager, "http://acme.example.com:3128/protected", "proxy.example.com:3128", ) def test_basic_and_digest_auth_handlers(self): # HTTPDigestAuthHandler threw an exception if it couldn't handle a 40* # response (http://python.org/sf/1479302), where it should instead # return None to allow another handler (especially # HTTPBasicAuthHandler) to handle the response. # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must # try digest first (since it's the strongest auth scheme), so we record # order of calls here to check digest comes first: class RecordingOpenerDirector(OpenerDirector): def __init__(self): OpenerDirector.__init__(self) self.recorded = [] def record(self, info): self.recorded.append(info) class TestDigestAuthHandler(urllib.request.HTTPDigestAuthHandler): def http_error_401(self, *args, **kwds): self.parent.record("digest") urllib.request.HTTPDigestAuthHandler.http_error_401(self, *args, **kwds) class TestBasicAuthHandler(urllib.request.HTTPBasicAuthHandler): def http_error_401(self, *args, **kwds): self.parent.record("basic") urllib.request.HTTPBasicAuthHandler.http_error_401(self, *args, **kwds) opener = RecordingOpenerDirector() password_manager = MockPasswordManager() digest_handler = TestDigestAuthHandler(password_manager) basic_handler = TestBasicAuthHandler(password_manager) realm = "ACME Networks" http_handler = MockHTTPHandler( 401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm) opener.add_handler(basic_handler) opener.add_handler(digest_handler) opener.add_handler(http_handler) # check basic auth isn't blocked by digest handler failing self._test_basic_auth(opener, basic_handler, "Authorization", realm, http_handler, password_manager, "http://acme.example.com/protected", "http://acme.example.com/protected", ) # check digest was tried before basic (twice, because # _test_basic_auth called .open() twice) self.assertEqual(opener.recorded, ["digest", "basic"]*2) def _test_basic_auth(self, opener, auth_handler, auth_header, realm, http_handler, password_manager, request_url, protected_url): import base64 user, password = "wile", "coyote" # .add_password() fed through to password manager auth_handler.add_password(realm, request_url, user, password) self.assertEqual(realm, password_manager.realm) self.assertEqual(request_url, password_manager.url) self.assertEqual(user, password_manager.user) self.assertEqual(password, password_manager.password) r = opener.open(request_url) # should have asked the password manager for the username/password self.assertEqual(password_manager.target_realm, realm) self.assertEqual(password_manager.target_url, protected_url) # expect one request without authorization, then one with self.assertEqual(len(http_handler.requests), 2) self.assertFalse(http_handler.requests[0].has_header(auth_header)) userpass = bytes('%s:%s' % (user, password), "ascii") auth_hdr_value = ('Basic ' + base64.encodebytes(userpass).strip().decode()) self.assertEqual(http_handler.requests[1].get_header(auth_header), auth_hdr_value) self.assertEqual(http_handler.requests[1].unredirected_hdrs[auth_header], auth_hdr_value) # if the password manager can't find a password, the handler won't # handle the HTTP auth error password_manager.user = password_manager.password = None http_handler.reset() r = opener.open(request_url) self.assertEqual(len(http_handler.requests), 1) self.assertFalse(http_handler.requests[0].has_header(auth_header)) class MiscTests(unittest.TestCase): def test_build_opener(self): class MyHTTPHandler(urllib.request.HTTPHandler): pass class FooHandler(urllib.request.BaseHandler): def foo_open(self): pass class BarHandler(urllib.request.BaseHandler): def bar_open(self): pass build_opener = urllib.request.build_opener o = build_opener(FooHandler, BarHandler) self.opener_has_handler(o, FooHandler) self.opener_has_handler(o, BarHandler) # can take a mix of classes and instances o = build_opener(FooHandler, BarHandler()) self.opener_has_handler(o, FooHandler) self.opener_has_handler(o, BarHandler) # subclasses of default handlers override default handlers o = build_opener(MyHTTPHandler) self.opener_has_handler(o, MyHTTPHandler) # a particular case of overriding: default handlers can be passed # in explicitly o = build_opener() self.opener_has_handler(o, urllib.request.HTTPHandler) o = build_opener(urllib.request.HTTPHandler) self.opener_has_handler(o, urllib.request.HTTPHandler) o = build_opener(urllib.request.HTTPHandler()) self.opener_has_handler(o, urllib.request.HTTPHandler) # Issue2670: multiple handlers sharing the same base class class MyOtherHTTPHandler(urllib.request.HTTPHandler): pass o = build_opener(MyHTTPHandler, MyOtherHTTPHandler) self.opener_has_handler(o, MyHTTPHandler) self.opener_has_handler(o, MyOtherHTTPHandler) def opener_has_handler(self, opener, handler_class): self.assertTrue(any(h.__class__ == handler_class for h in opener.handlers)) class RequestTests(unittest.TestCase): def setUp(self): self.get = Request("http://www.python.org/~jeremy/") self.post = Request("http://www.python.org/~jeremy/", "data", headers={"X-Test": "test"}) def test_method(self): self.assertEqual("POST", self.post.get_method()) self.assertEqual("GET", self.get.get_method()) def test_add_data(self): self.assertFalse(self.get.has_data()) self.assertEqual("GET", self.get.get_method()) self.get.add_data("spam") self.assertTrue(self.get.has_data()) self.assertEqual("POST", self.get.get_method()) def test_get_full_url(self): self.assertEqual("http://www.python.org/~jeremy/", self.get.get_full_url()) def test_selector(self): self.assertEqual("/~jeremy/", self.get.get_selector()) req = Request("http://www.python.org/") self.assertEqual("/", req.get_selector()) def test_get_type(self): self.assertEqual("http", self.get.get_type()) def test_get_host(self): self.assertEqual("www.python.org", self.get.get_host()) def test_get_host_unquote(self): req = Request("http://www.%70ython.org/") self.assertEqual("www.python.org", req.get_host()) def test_proxy(self): self.assertFalse(self.get.has_proxy()) self.get.set_proxy("www.perl.org", "http") self.assertTrue(self.get.has_proxy()) self.assertEqual("www.python.org", self.get.get_origin_req_host()) self.assertEqual("www.perl.org", self.get.get_host()) def test_wrapped_url(self): req = Request("<URL:http://www.python.org>") self.assertEqual("www.python.org", req.get_host()) def test_urlwith_fragment(self): req = Request("http://www.python.org/?qs=query#fragment=true") self.assertEqual("/?qs=query", req.get_selector()) req = Request("http://www.python.org/#fun=true") self.assertEqual("/", req.get_selector()) def test_main(verbose=None): from test import test_urllib2 support.run_doctest(test_urllib2, verbose) support.run_doctest(urllib.request, verbose) tests = (TrivialTests, OpenerDirectorTests, HandlerTests, MiscTests, RequestTests) support.run_unittest(*tests) if __name__ == "__main__": test_main(verbose=True)
mancoast/CPythonPyc_test
fail/313_test_urllib2.py
Python
gpl-3.0
51,087
package com.wongsir.newsgathering.model.commons; import com.google.common.base.MoreObjects; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * @Description: TODO * @author Wongsir * @date 2017年1月4日 * */ public class Webpage { /** * 附件id列表 */ public List<String> attachmentList; /** * 图片ID列表 */ public List<String> imageList; /** * 正文 */ private String content; /** * 标题 */ private String title; /** * 链接 */ private String url; /** * 域名 */ private String domain; /** * 爬虫id,可以认为是taskid */ private String spiderUUID; /** * 模板id */ @SerializedName("spiderInfoId") private String spiderInfoId; /** * 分类 */ private String category; /** * 网页快照 */ private String rawHTML; /** * 关键词 */ private List<String> keywords; /** * 摘要 */ private List<String> summary; /** * 抓取时间 */ @SerializedName("gatherTime") private Date gathertime; /** * 网页id,es自动分配的 */ private String id; /** * 文章的发布时间 */ private Date publishTime; /** * 命名实体 */ private Map<String, Set<String>> namedEntity; /** * 动态字段 */ private Map<String, Object> dynamicFields; /** * 静态字段 */ private Map<String, Object> staticFields; /** * 本网页处理时长 */ private long processTime; public Map<String, Object> getStaticFields() { return staticFields; } public Webpage setStaticFields(Map<String, Object> staticFields) { this.staticFields = staticFields; return this; } public Map<String, Set<String>> getNamedEntity() { return namedEntity; } public Webpage setNamedEntity(Map<String, Set<String>> namedEntity) { this.namedEntity = namedEntity; return this; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getSpiderInfoId() { return spiderInfoId; } public void setSpiderInfoId(String spiderInfoId) { this.spiderInfoId = spiderInfoId; } public Date getGathertime() { return gathertime; } public void setGathertime(Date gathertime) { this.gathertime = gathertime; } public String getSpiderUUID() { return spiderUUID; } public void setSpiderUUID(String spiderUUID) { this.spiderUUID = spiderUUID; } public String getId() { return id; } public void setId(String id) { this.id = id; } public List<String> getKeywords() { return keywords; } public Webpage setKeywords(List<String> keywords) { this.keywords = keywords; return this; } public List<String> getSummary() { return summary; } public Webpage setSummary(List<String> summary) { this.summary = summary; return this; } public Date getPublishTime() { return publishTime; } public Webpage setPublishTime(Date publishTime) { this.publishTime = publishTime; return this; } public String getCategory() { return category; } public Webpage setCategory(String category) { this.category = category; return this; } public String getRawHTML() { return rawHTML; } public Webpage setRawHTML(String rawHTML) { this.rawHTML = rawHTML; return this; } public Map<String, Object> getDynamicFields() { return dynamicFields; } public Webpage setDynamicFields(Map<String, Object> dynamicFields) { this.dynamicFields = dynamicFields; return this; } public List<String> getAttachmentList() { return attachmentList; } public Webpage setAttachmentList(List<String> attachmentList) { this.attachmentList = attachmentList; return this; } public List<String> getImageList() { return imageList; } public Webpage setImageList(List<String> imageList) { this.imageList = imageList; return this; } public long getProcessTime() { return processTime; } public Webpage setProcessTime(long processTime) { this.processTime = processTime; return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("content", content) .add("title", title) .add("url", url) .add("domain", domain) .add("spiderUUID", spiderUUID) .add("spiderInfoId", spiderInfoId) .add("category", category) .add("rawHTML", rawHTML) .add("keywords", keywords) .add("summary", summary) .add("gathertime", gathertime) .add("id", id) .add("publishTime", publishTime) .add("namedEntity", namedEntity) .add("dynamicFields", dynamicFields) .add("staticFields", staticFields) .add("attachmentList", attachmentList) .add("imageList", imageList) .toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Webpage webpage = (Webpage) o; return new EqualsBuilder() .append(getContent(), webpage.getContent()) .append(getTitle(), webpage.getTitle()) .append(getUrl(), webpage.getUrl()) .append(getDomain(), webpage.getDomain()) .append(getSpiderUUID(), webpage.getSpiderUUID()) .append(getSpiderInfoId(), webpage.getSpiderInfoId()) .append(getCategory(), webpage.getCategory()) .append(getRawHTML(), webpage.getRawHTML()) .append(getKeywords(), webpage.getKeywords()) .append(getSummary(), webpage.getSummary()) .append(getGathertime(), webpage.getGathertime()) .append(getId(), webpage.getId()) .append(getPublishTime(), webpage.getPublishTime()) .append(getNamedEntity(), webpage.getNamedEntity()) .append(getDynamicFields(), webpage.getDynamicFields()) .append(getStaticFields(), webpage.getStaticFields()) .append(getAttachmentList(), webpage.getAttachmentList()) .append(getImageList(), webpage.getImageList()) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(getContent()) .append(getTitle()) .append(getUrl()) .append(getDomain()) .append(getSpiderUUID()) .append(getSpiderInfoId()) .append(getCategory()) .append(getRawHTML()) .append(getKeywords()) .append(getSummary()) .append(getGathertime()) .append(getId()) .append(getPublishTime()) .append(getNamedEntity()) .append(getDynamicFields()) .append(getStaticFields()) .append(getAttachmentList()) .append(getImageList()) .toHashCode(); } }
WongSir/JustGo
src/main/java/com/wongsir/newsgathering/model/commons/Webpage.java
Java
gpl-3.0
8,742
/* * Beautiful Capi generates beautiful C API wrappers for your C++ classes * Copyright (C) 2015 Petr Petrovich Petrov * * This file is part of Beautiful Capi. * * Beautiful Capi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Beautiful Capi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Beautiful Capi. If not, see <http://www.gnu.org/licenses/>. * */ /* * WARNING: This file was automatically generated by Beautiful Capi! * Do not edit this file! Please edit the source API description. */ #ifndef POINTSET_POINTS_DEFINITION_INCLUDED #define POINTSET_POINTS_DEFINITION_INCLUDED #include "PointSet/PointsDecl.h" #include "PointSet/Position.h" #ifdef __cplusplus inline PointSet::PointsPtr::PointsPtr() { SetObject(PointSet::PointsPtr(PointSet::PointsPtr::force_creating_from_raw_pointer, point_set_points_default(), false).Detach()); } inline size_t PointSet::PointsPtr::Size() const { return point_set_points_size_const(GetRawPointer()); } inline void PointSet::PointsPtr::Reserve(size_t capacity) { point_set_points_reserve(GetRawPointer(), capacity); } inline void PointSet::PointsPtr::Resize(size_t size, const PointSet::Position& default_value) { point_set_points_resize(GetRawPointer(), size, default_value.GetRawPointer()); } inline PointSet::Position PointSet::PointsPtr::GetElement(size_t index) const { return PointSet::Position(PointSet::Position::force_creating_from_raw_pointer, point_set_points_get_element_const(GetRawPointer(), index), false); } inline void PointSet::PointsPtr::SetElement(size_t index, const PointSet::Position& value) { point_set_points_set_element(GetRawPointer(), index, value.GetRawPointer()); } inline void PointSet::PointsPtr::PushBack(const PointSet::Position& value) { point_set_points_push_back(GetRawPointer(), value.GetRawPointer()); } inline void PointSet::PointsPtr::Clear() { point_set_points_clear(GetRawPointer()); } inline PointSet::PointsPtr::PointsPtr(const PointsPtr& other) { SetObject(other.GetRawPointer()); if (other.GetRawPointer()) { point_set_points_add_ref(other.GetRawPointer()); } } #ifdef POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES inline PointSet::PointsPtr::PointsPtr(PointsPtr&& other) { mObject = other.mObject; other.mObject = 0; } #endif /* POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES */ inline PointSet::PointsPtr::PointsPtr(PointSet::PointsPtr::ECreateFromRawPointer, void *object_pointer, bool add_ref_object) { SetObject(object_pointer); if (add_ref_object && object_pointer) { point_set_points_add_ref(object_pointer); } } inline PointSet::PointsPtr::~PointsPtr() { if (GetRawPointer()) { point_set_points_release(GetRawPointer()); SetObject(0); } } inline PointSet::PointsPtr& PointSet::PointsPtr::operator=(const PointSet::PointsPtr& other) { if (GetRawPointer() != other.GetRawPointer()) { if (GetRawPointer()) { point_set_points_release(GetRawPointer()); SetObject(0); } SetObject(other.GetRawPointer()); if (other.GetRawPointer()) { point_set_points_add_ref(other.GetRawPointer()); } } return *this; } #ifdef POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES inline PointSet::PointsPtr& PointSet::PointsPtr::operator=(PointSet::PointsPtr&& other) { if (GetRawPointer() != other.GetRawPointer()) { if (GetRawPointer()) { point_set_points_release(GetRawPointer()); SetObject(0); } mObject = other.mObject; other.mObject = 0; } return *this; } #endif /* POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES */ inline PointSet::PointsPtr PointSet::PointsPtr::Null() { return PointSet::PointsPtr(PointSet::PointsPtr::force_creating_from_raw_pointer, static_cast<void*>(0), false); } inline bool PointSet::PointsPtr::IsNull() const { return !GetRawPointer(); } inline bool PointSet::PointsPtr::IsNotNull() const { return GetRawPointer() != 0; } inline bool PointSet::PointsPtr::operator!() const { return !GetRawPointer(); } inline void* PointSet::PointsPtr::Detach() { void* result = GetRawPointer(); SetObject(0); return result; } inline void* PointSet::PointsPtr::GetRawPointer() const { return PointSet::PointsPtr::mObject ? mObject: 0; } inline PointSet::PointsPtr* PointSet::PointsPtr::operator->() { return this; } inline const PointSet::PointsPtr* PointSet::PointsPtr::operator->() const { return this; } inline void PointSet::PointsPtr::SetObject(void* object_pointer) { mObject = object_pointer; } #endif /* __cplusplus */ #endif /* POINTSET_POINTS_DEFINITION_INCLUDED */
PetrPPetrov/beautiful-capi
tests/current_backuped_results/point_set/include/PointSet/Points.h
C
gpl-3.0
5,198
package fr.hnit.babyname; /* The babyname app 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. The babyname app is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the TXM platform. If not, see http://www.gnu.org/licenses */ import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public static final String UPDATE_EXTRA = "update"; ListView namesListView; BabyNameAdapter adapter; public static BabyNameDatabase database = new BabyNameDatabase(); public static ArrayList<BabyNameProject> projects = new ArrayList<>(); Intent editIntent; Intent findIntent; Intent settingsIntent; Intent aboutIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (database.size() == 0) database.initialize(); namesListView = (ListView) findViewById(R.id.listView); registerForContextMenu(namesListView); namesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { BabyNameProject project = projects.get(i); if (project != null) { doFindName(project); } } }); adapter = new BabyNameAdapter(this, projects); namesListView.setAdapter(adapter); if (projects.size() == 0) { initializeProjects(); } editIntent = new Intent(MainActivity.this, EditActivity.class); findIntent = new Intent(MainActivity.this, FindActivity.class); settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); aboutIntent = new Intent(MainActivity.this, AboutActivity.class); } @Override public void onResume() { super.onResume(); // Always call the superclass method first adapter.notifyDataSetChanged(); for (BabyNameProject project : projects) { if (project.needSaving) { //Toast.makeText(this, "Saving changes of "+project+"... "+project, Toast.LENGTH_SHORT).show(); if (!BabyNameProject.storeProject(project, this)) { Toast.makeText(this, "Error: could not save changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } } } } private void initializeProjects() { //AppLogger.info("Initializing projects..."); for (String filename : this.fileList()) { if (filename.endsWith(".baby")) { //AppLogger.info("Restoring... "+filename); try { BabyNameProject project = BabyNameProject.readProject(filename, this); if (project != null) projects.add(project); else Toast.makeText(MainActivity.this, "Error: could not read baby name project from "+filename, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); if (adapter.getCount() <= info.position) return false; BabyNameProject project = adapter.getItem(info.position); if (project == null) return false; switch (item.getItemId()) { case R.id.action_reset_baby: doResetBaby(project); return true; case R.id.action_top_baby: doShowTop10(project); return true; case R.id.action_delete_baby: doDeleteBaby(project); return true; default: return super.onContextItemSelected(item); } } public void doResetBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.reset_question_title); builder.setMessage(R.string.reset_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { project.reset(); adapter.notifyDataSetChanged(); if (!BabyNameProject.storeProject(project, MainActivity.this)) { Toast.makeText(MainActivity.this, "Error: could not save reset changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // I do not need any action here you might dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public void doDeleteBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete_question_title); builder.setMessage(R.string.delete_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { projects.remove(project); MainActivity.this.deleteFile(project.getID()+".baby"); adapter.notifyDataSetChanged(); dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public String projectToString(BabyNameProject p) { String l1 = ""; if (p.genders.contains(NameData.F) && p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_or_girl_name); } else if (p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_name); } else { l1 +=getString( R.string.girl_name); } if (p.origins.size() == 1) { l1 += "\n\t "+String.format(getString(R.string.origin_is), p.origins.toArray()[0]); } else if (p.origins.size() > 1) { l1 += "\n\t "+String.format(getString(R.string.origin_are), p.origins); } else { l1 += "\n\t "+getString(R.string.no_origin); } if (p.pattern != null) { if (".*".equals(p.pattern.toString())) { l1 += "\n\t "+getString(R.string.no_pattern); } else { l1 += "\n\t "+String.format(getString(R.string.matches_with), p.pattern); } } if (p.nexts.size() == 1) { l1 += "\n\t"+getString(R.string.one_remaining_name); } else if (p.nexts.size() == 0) { int n = p.scores.size(); if (n > 11) n = n - 10; l1 += "\n\t"+String.format(getString(R.string.no_remaining_loop), p.loop, n); } else { l1 += "\n\t"+String.format(getString(R.string.remaining_names), p.nexts.size()); } if (p.scores.size() > 0 && p.getBest() != null) { l1 += "\n\n\t"+String.format(getString(R.string.bact_match_is), p.getBest()); } return l1; } public void doShowTop10(final BabyNameProject project) { List<Integer> names = project.getTop10(); final StringBuffer buffer = new StringBuffer(); int n = 0; for (Integer name : names) { buffer.append("\n"+MainActivity.database.get(name)+": "+project.scores.get(name)); } if (names.size() == 0) buffer.append(getString(R.string.no_name_rated)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.top_title); builder.setMessage(buffer.toString()); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (names.size() > 0) builder.setNegativeButton(R.string.copy, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("baby top10", buffer.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(MainActivity.this, R.string.text_copied, Toast.LENGTH_LONG).show(); } }); AlertDialog alert = builder.create(); alert.show(); //Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show(); } public void doFindName(BabyNameProject project) { //AppLogger.info("Open FindActivity with "+project+" index="+projects.indexOf(project)); findIntent.putExtra(FindActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(findIntent, 0); } private void openEditActivity(BabyNameProject project) { //AppLogger.info("Open EditActivity with "+project+" index="+projects.indexOf(project)); editIntent.putExtra(EditActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(editIntent, 0); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: this.startActivityForResult(settingsIntent, 0); return true; case R.id.action_about: this.startActivityForResult(aboutIntent, 0); return true; case R.id.action_new_baby: doNewBaby(); return true; default: return super.onOptionsItemSelected(item); } } public void doNewBaby() { Toast.makeText(this, R.string.new_baby, Toast.LENGTH_LONG).show(); BabyNameProject project = new BabyNameProject(); projects.add(project); openEditActivity(project); } }
mdecorde/BABYNAME
app/src/main/java/fr/hnit/babyname/MainActivity.java
Java
gpl-3.0
12,172
import { useState } from "react"; import { PropTypes } from "prop-types"; import { SaveOutlined, WarningOutlined } from "@ant-design/icons"; import { Button, Col, Form, Input, InputNumber, Row, Select, Switch, Typography, Space, } from "@nextgisweb/gui/antd"; import i18n from "@nextgisweb/pyramid/i18n!"; import { AddressGeocoderOptions, DegreeFormatOptions, UnitsAreaOptions, UnitsLengthOptions, } from "./select-options"; const { Title } = Typography; const INPUT_DEFAULT_WIDTH = { width: "100%" }; export const SettingsForm = ({ onFinish, initialValues, srsOptions, status, }) => { const [geocoder, setGeocoder] = useState( initialValues.address_geocoder || "nominatim" ); const onValuesChange = (changedValues, allValues) => { setGeocoder(allValues.address_geocoder); }; return ( <Form name="webmap_settings" className="webmap-settings-form" initialValues={initialValues} onFinish={onFinish} onValuesChange={onValuesChange} layout="vertical" > <Title level={4}>{i18n.gettext("Identify popup")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="popup_width" label={i18n.gettext("Width, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="popup_height" label={i18n.gettext("Height, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="identify_radius" label={i18n.gettext("Radius, px")} rules={[ { required: true, }, ]} > <InputNumber min="1" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="identify_attributes" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Show feature attributes")} </Space> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Measurement")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="units_length" label={i18n.gettext("Length units")} > <Select options={UnitsLengthOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="units_area" label={i18n.gettext("Area units")} > <Select options={UnitsAreaOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="degree_format" label={i18n.gettext("Degree format")} > <Select options={DegreeFormatOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item name="measurement_srid" label={i18n.gettext("Measurement SRID")} > <Select options={srsOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Address search")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_enabled" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Enable")} </Space> </Form.Item> </Col> <Col span={16}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_extent" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Limit by web map initial extent")} </Space> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="address_geocoder" label={i18n.gettext("Provider")} > <Select options={AddressGeocoderOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={16}> {geocoder == "nominatim" ? ( <Form.Item name="nominatim_countrycodes" label={i18n.gettext( "Limit search results to countries" )} rules={[ { pattern: new RegExp( /^(?:(?:[A-Za-z]+)(?:-[A-Za-z]+)?(?:,|$))+(?<!,)$/ ), message: ( <div> {i18n.gettext( "Invalid countries. For example ru or gb,de" )} </div> ), }, ]} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> ) : ( <Form.Item name="yandex_api_geocoder_key" label={i18n.gettext("Yandex.Maps API Geocoder Key")} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> )} </Col> </Row> <Row className="row-submit"> <Col> <Button htmlType="submit" type={"primary"} danger={status === "saved-error"} icon={ status === "saved-error" ? ( <WarningOutlined /> ) : ( <SaveOutlined /> ) } loading={status === "saving"} > {i18n.gettext("Save")} </Button> </Col> </Row> </Form> ); }; SettingsForm.propTypes = { initialValues: PropTypes.object, onFinish: PropTypes.func, srsOptions: PropTypes.array, status: PropTypes.string, };
nextgis/nextgisweb
nextgisweb/webmap/nodepkg/settings/SettingsForm.js
JavaScript
gpl-3.0
9,428
#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join()
jim-easterbrook/pyctools-demo
src/scripts/temporal_alias/stage_2.py
Python
gpl-3.0
2,808
# -*- coding: utf-8 -*- import itertools """ Languages | ShortCode | Wordnet Albanian | sq | als Arabic | ar | arb Bulgarian | bg | bul Catalan | ca | cat Chinese | zh | cmn Chinese (Taiwan) | qn | qcn Greek | el | ell Basque | eu | eus Persian | fa | fas Finish | fi | fin French | fr | fra Galician | gl | glg Hebrew | he | heb Croatian | hr | hrv Indonesian | id | ind Italian | it | ita Japanese | ja | jpn Norwegian NyNorsk | nn | nno Norwegian Bokmål | nb/no | nob Polish | pl | pol Portuguese | pt | por Slovenian | sl | slv Spanish | es | spa Swedish | sv | swe Thai | tt | tha Malay | ms | zsm """ """ Language short codes => Wordnet Code """ AVAILABLE_LANGUAGES = dict([('sq','als'), ('ar', 'arb'), ('bg', 'bul'), ('ca', 'cat'), ('da', 'dan'), ('zh', 'cmn'), ('el','ell'), ('eu', 'eus'), ('fa', 'fas'), ('fi', 'fin'), ('fr', 'fra'), ('gl','glg'), ('he', 'heb'), ('hr', 'hrv'), ('id', 'ind'), ('it', 'ita'), ('ja','jpn'), ('nn', 'nno'), ('nb', 'nob'), ('no', 'nob'), ('pl', 'pol'), ('pt', 'por'), ('qn','qcn'), ('sl', 'slv'), ('es', 'spa'), ('sv', 'swe'), ('tt', 'tha'), ('ms', 'zsm'), ('en', 'eng')]) """ Language names => Short Code """ AVAILABLE_LANGUAGES_NAMES = dict([ ('albanian', 'sq'), ('arabic', 'ar'),('bulgarian', 'bg'), ('catalan', 'cat'), ('danish', 'da'), ('chinese', 'zh'), ('basque', 'eu'), ('persian', 'fa'), ('finnish', 'fi'), ('france', 'fr'), ('galician', 'gl'), ('hebrew', 'he'), ('croatian', 'hr'), ('indonesian', 'id'), ('italian', 'it'), ('japanese', 'ja'), ('norwegian_nynorsk', 'nn'), ('norwegian', 'no'), ('norwegian_bokmal', 'nb'), ('polish', 'pl'), ('portuguese', 'pt'), ('slovenian', 'sl'), ('spanish', 'es'), ('swedish', 'sv'), ('thai', 'sv'), ('malay', 'ms'), ('english', 'en') ]) class WordnetManager(object): def __init__(self, language="en"): """ Constructor for the wordnet manager. It takes a main language. """ self.__language = language def __isLanguageAvailable(self, code=None, language_name=None): """ Check if a language is available """ if code is None and language_name is None: raise Exception("Error evaluating the correct language") if code is not None and code.lower() in AVAILABLE_LANGUAGES: return True if language_name is not None and language_name.lower() in AVAILABLE_LANGUAGES_NAMES: return True return False def __nameToWordnetCode(self, name): """ It returns the wordnet code for a given language name """ if not self.__isLanguageAvailable(language_name=name): raise Exception("Wordnet code not found for the language name %s " % name) name = name.lower() languageShortCode = AVAILABLE_LANGUAGES_NAMES[name] wordnetCode = self.__shortCodeToWordnetCode(code=languageShortCode) return wordnetCode def __shortCodeToWordnetCode(self, shortCode): """ It returns the wordnet code from a given language short code """ if not self.__isLanguageAvailable(code=shortCode): raise Exception("Wordnet code not found for the language short code %s " % shortCode) code = shortCode.lower() wordnetCode = AVAILABLE_LANGUAGES[code] return wordnetCode def __getSynsets(self, word, wordNetCode): """ It returns the synsets given both word and language code """ from nltk.corpus import wordnet as wn synsets = wn.synsets(word, lang=wordNetCode) return synsets def getLemmas(self, word, languageCode="en"): """ Get the lemmas for a given word :word: The word :languageCode: The language for a given lemma """ wnCode = self.__shortCodeToWordnetCode(shortCode=languageCode) synsets = self.__getSynsets(word, wnCode) #wn.synsets(word, lang=wnCode) lemmas = dict([('en', [])]) for synset in synsets: enLemmas = synset.lemma_names() lemmas['en'].extend(enLemmas) if languageCode != "en" and self.__isLanguageAvailable(code=languageCode): langLemmas = list(sorted(set(synset.lemma_names(lang=wnCode)))) lemmas[languageCode] = langLemmas lemmas['en'] = list(sorted(set(lemmas.get('en', [])))) return lemmas def getSynonyms(self, words=[], language_code="en"): """ Get the synonyms from a list of words. :words: A list of words :language_code: the language for the synonyms. """ if words is None or not isinstance(words, list) or list(words) <= 0: return [] if not self.__isLanguageAvailable(code=language_code): return [] wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: result[word] = dict([('lemmas', self.getLemmas(word,languageCode=language_code))]) return result def getHyponyms(self, words, language_code="en"): """ Get specific synsets from a given synset """ wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hyponyms = [hyp for synset in synonyms for hyp in synset.hyponyms()] engLemmas = [hyp.lemma_names() for hyp in hyponyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hyponyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result def getHypernyms(self, words, language_code="en"): """ Get general synsets from a given synset """ wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hypernyms = [hyp for synset in synonyms for hyp in synset.hypernyms()] engLemmas = [hyp.lemma_names() for hyp in hypernyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hypernyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result
domenicosolazzo/jroc
jroc/nlp/wordnet/WordnetManager.py
Python
gpl-3.0
8,043
package com.weatherapp.model.entities; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Location implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; public Location(String name) { this.name = name; } public Location() {} public String getName() { return name; } public void setName(String name) { this.name = name; } }
VoidDragonOfMars/pixelware
instantweatherapplication/src/main/java/com/weatherapp/model/entities/Location.java
Java
gpl-3.0
552
# Courses-Pick-Helper What this program will do is to constantly scan your shopping cart on your student centre account and help you enroll very fast !!! Basically help you with enrolling courses in your shopping cart of your student centre account when it's "OPEN". Note that this will succeed iff there is no conflict of this course with other courses you've enrolled in.
MichaelGuoXY/Courses-Pick-Helper
README.md
Markdown
gpl-3.0
378
package units.interfaces; public abstract interface Value<T> extends MyComparable<T> { // OPERATIONS default boolean invariant() { return true; } default void checkInvariant() { if(!invariant()) { System.exit(-1); } } public abstract T newInstance(double value); public abstract T abs(); public abstract T min(T value); public abstract T max(T value); public abstract T add(T value); public abstract T sub(T value); public abstract T mul(double value); public abstract T div(double value); public abstract double div(T value); }
MesutKoc/uni-haw
2. Semester/PR2/Aufgabe_2a_Igor/src/units/interfaces/Value.java
Java
gpl-3.0
686
############################################################################# # $HeadURL$ ############################################################################# """ ..mod: FTSRequest ================= Helper class to perform FTS job submission and monitoring. """ # # imports import sys import re import time # # from DIRAC from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Utilities.File import checkGuid from DIRAC.Core.Utilities.Adler import compareAdler, intAdlerToHex, hexAdlerToInt from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE from DIRAC.Core.Utilities.Time import dateTime from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Utilities.ReturnValues import returnSingleResult from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation from DIRAC.ConfigurationSystem.Client.Helpers.Resources import Resources from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.DataManagementSystem.Client.FTSJob import FTSJob from DIRAC.DataManagementSystem.Client.FTSFile import FTSFile # # RCSID __RCSID__ = "$Id$" class FTSRequest( object ): """ .. class:: FTSRequest Helper class for FTS job submission and monitoring. """ # # default checksum type __defaultCksmType = "ADLER32" # # flag to disablr/enable checksum test, default: disabled __cksmTest = False def __init__( self ): """c'tor :param self: self reference """ self.log = gLogger.getSubLogger( self.__class__.__name__, True ) # # final states tuple self.finalStates = ( 'Canceled', 'Failed', 'Hold', 'Finished', 'FinishedDirty' ) # # failed states tuple self.failedStates = ( 'Canceled', 'Failed', 'Hold', 'FinishedDirty' ) # # successful states tuple self.successfulStates = ( 'Finished', 'Done' ) # # all file states tuple self.fileStates = ( 'Done', 'Active', 'Pending', 'Ready', 'Canceled', 'Failed', 'Finishing', 'Finished', 'Submitted', 'Hold', 'Waiting' ) self.statusSummary = {} # # request status self.requestStatus = 'Unknown' # # dict for FTS job files self.fileDict = {} # # dict for replicas information self.catalogReplicas = {} # # dict for metadata information self.catalogMetadata = {} # # dict for files that failed to register self.failedRegistrations = {} # # placehoder for FileCatalog reference self.oCatalog = None # # submit timestamp self.submitTime = '' # # placeholder FTS job GUID self.ftsGUID = '' # # placeholder for FTS server URL self.ftsServer = '' # # flag marking FTS job completness self.isTerminal = False # # completness percentage self.percentageComplete = 0.0 # # source SE name self.sourceSE = '' # # flag marking source SE validity self.sourceValid = False # # source space token self.sourceToken = '' # # target SE name self.targetSE = '' # # flag marking target SE validity self.targetValid = False # # target space token self.targetToken = '' # # placeholder for target StorageElement self.oTargetSE = None # # placeholder for source StorageElement self.oSourceSE = None # # checksum type, set it to default self.__cksmType = self.__defaultCksmType # # disable checksum test by default self.__cksmTest = False # # statuses that prevent submitting to FTS self.noSubmitStatus = ( 'Failed', 'Done', 'Staging' ) # # were sources resolved? self.sourceResolved = False # # Number of file transfers actually submitted self.submittedFiles = 0 self.transferTime = 0 self.submitCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/SubmitCommand', 'glite-transfer-submit' ) self.monitorCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/MonitorCommand', 'glite-transfer-status' ) self.ftsJob = None self.ftsFiles = [] #################################################################### # # Methods for setting/getting/checking the SEs # def setSourceSE( self, se ): """ set SE for source :param self: self reference :param str se: source SE name """ if se == self.targetSE: return S_ERROR( "SourceSE is TargetSE" ) self.sourceSE = se self.oSourceSE = StorageElement( self.sourceSE ) return self.__checkSourceSE() def __checkSourceSE( self ): """ check source SE availability :param self: self reference """ if not self.sourceSE: return S_ERROR( "SourceSE not set" ) res = self.oSourceSE.isValid( 'Read' ) if not res['OK']: return S_ERROR( "SourceSE not available for reading" ) res = self.__getSESpaceToken( self.oSourceSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for SourceSE", res['Message'] ) return S_ERROR( "SourceSE does not support FTS transfers" ) if self.__cksmTest: res = self.oSourceSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for SourceSE", "%s: %s" % ( self.sourceSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at SourceSE %s, disabling checksum test" % ( cksmType, self.sourceSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.sourceToken = res['Value'] self.sourceValid = True return S_OK() def setTargetSE( self, se ): """ set target SE :param self: self reference :param str se: target SE name """ if se == self.sourceSE: return S_ERROR( "TargetSE is SourceSE" ) self.targetSE = se self.oTargetSE = StorageElement( self.targetSE ) return self.__checkTargetSE() def setTargetToken( self, token ): """ target space token setter :param self: self reference :param str token: target space token """ self.targetToken = token return S_OK() def __checkTargetSE( self ): """ check target SE availability :param self: self reference """ if not self.targetSE: return S_ERROR( "TargetSE not set" ) res = self.oTargetSE.isValid( 'Write' ) if not res['OK']: return S_ERROR( "TargetSE not available for writing" ) res = self.__getSESpaceToken( self.oTargetSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for TargetSE", res['Message'] ) return S_ERROR( "TargetSE does not support FTS transfers" ) # # check checksum types if self.__cksmTest: res = self.oTargetSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for TargetSE", "%s: %s" % ( self.targetSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at TargetSE %s, disabling checksum test" % ( cksmType, self.targetSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.targetToken = res['Value'] self.targetValid = True return S_OK() @staticmethod def __getSESpaceToken( oSE ): """ get space token from StorageElement instance :param self: self reference :param StorageElement oSE: StorageElement instance """ res = oSE.getStorageParameters( "SRM2" ) if not res['OK']: return res return S_OK( res['Value'].get( 'SpaceToken' ) ) #################################################################### # # Methods for setting/getting FTS request parameters # def setFTSGUID( self, guid ): """ FTS job GUID setter :param self: self reference :param str guid: string containg GUID """ if not checkGuid( guid ): return S_ERROR( "Incorrect GUID format" ) self.ftsGUID = guid return S_OK() def setFTSServer( self, server ): """ FTS server setter :param self: self reference :param str server: FTS server URL """ self.ftsServer = server return S_OK() def isRequestTerminal( self ): """ check if FTS job has terminated :param self: self reference """ if self.requestStatus in self.finalStates: self.isTerminal = True return S_OK( self.isTerminal ) def setCksmTest( self, cksmTest = False ): """ set cksm test :param self: self reference :param bool cksmTest: flag to enable/disable checksum test """ self.__cksmTest = bool( cksmTest ) return S_OK( self.__cksmTest ) #################################################################### # # Methods for setting/getting/checking files and their metadata # def setLFN( self, lfn ): """ add LFN :lfn: to :fileDict: :param self: self reference :param str lfn: LFN to add to """ self.fileDict.setdefault( lfn, {'Status':'Waiting'} ) return S_OK() def setSourceSURL( self, lfn, surl ): """ source SURL setter :param self: self reference :param str lfn: LFN :param str surl: source SURL """ target = self.fileDict[lfn].get( 'Target' ) if target == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Source', surl ) def getSourceSURL( self, lfn ): """ get source SURL for LFN :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Source' ) def setTargetSURL( self, lfn, surl ): """ set target SURL for LFN :lfn: :param self: self reference :param str lfn: LFN :param str surl: target SURL """ source = self.fileDict[lfn].get( 'Source' ) if source == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Target', surl ) def getFailReason( self, lfn ): """ get fail reason for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Reason' ) def getRetries( self, lfn ): """ get number of attepmts made to transfer file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Retries' ) def getTransferTime( self, lfn ): """ get duration of transfer for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Duration' ) def getFailed( self ): """ get list of wrongly transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.failedStates ] ) def getStaging( self ): """ get files set for prestaging """ return S_OK( [lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) == 'Staging'] ) def getDone( self ): """ get list of succesfully transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.successfulStates ] ) def __setFileParameter( self, lfn, paramName, paramValue ): """ set :paramName: to :paramValue: for :lfn: file :param self: self reference :param str lfn: LFN :param str paramName: parameter name :param mixed paramValue: a new parameter value """ self.setLFN( lfn ) self.fileDict[lfn][paramName] = paramValue return S_OK() def __getFileParameter( self, lfn, paramName ): """ get value of :paramName: for file :lfn: :param self: self reference :param str lfn: LFN :param str paramName: parameter name """ if lfn not in self.fileDict: return S_ERROR( "Supplied file not set" ) if paramName not in self.fileDict[lfn]: return S_ERROR( "%s not set for file" % paramName ) return S_OK( self.fileDict[lfn][paramName] ) #################################################################### # # Methods for submission # def submit( self, monitor = False, printOutput = True ): """ submit FTS job :param self: self reference :param bool monitor: flag to monitor progress of FTS job :param bool printOutput: flag to print output of execution to stdout """ res = self.__prepareForSubmission() if not res['OK']: return res res = self.__submitFTSTransfer() if not res['OK']: return res resDict = { 'ftsGUID' : self.ftsGUID, 'ftsServer' : self.ftsServer, 'submittedFiles' : self.submittedFiles } if monitor or printOutput: gLogger.always( "Submitted %s@%s" % ( self.ftsGUID, self.ftsServer ) ) if monitor: self.monitor( untilTerminal = True, printOutput = printOutput, full = False ) return S_OK( resDict ) def __prepareForSubmission( self ): """ check validity of job before submission :param self: self reference """ if not self.fileDict: return S_ERROR( "No files set" ) if not self.sourceValid: return S_ERROR( "SourceSE not valid" ) if not self.targetValid: return S_ERROR( "TargetSE not valid" ) if not self.ftsServer: res = self.__resolveFTSServer() if not res['OK']: return S_ERROR( "FTSServer not valid" ) self.resolveSource() self.resolveTarget() res = self.__filesToSubmit() if not res['OK']: return S_ERROR( "No files to submit" ) return S_OK() def __getCatalogObject( self ): """ CatalogInterface instance facade :param self: self reference """ try: if not self.oCatalog: self.oCatalog = FileCatalog() return S_OK() except: return S_ERROR() def __updateReplicaCache( self, lfns = None, overwrite = False ): """ update replica cache for list of :lfns: :param self: self reference :param mixed lfns: list of LFNs :param bool overwrite: flag to trigger cache clearing and updating """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if ( lfn not in self.catalogReplicas ) or overwrite ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getReplicas( toUpdate ) if not res['OK']: return S_ERROR( "Failed to update replica cache: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, replicas in res['Value']['Successful'].items(): self.catalogReplicas[lfn] = replicas return S_OK() def __updateMetadataCache( self, lfns = None ): """ update metadata cache for list of LFNs :param self: self reference :param list lnfs: list of LFNs """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if lfn not in self.catalogMetadata ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getFileMetadata( toUpdate ) if not res['OK']: return S_ERROR( "Failed to get source catalog metadata: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, metadata in res['Value']['Successful'].items(): self.catalogMetadata[lfn] = metadata return S_OK() def resolveSource( self ): """ resolve source SE eligible for submission :param self: self reference """ # Avoid resolving sources twice if self.sourceResolved: return S_OK() # Only resolve files that need a transfer toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( "Status", "" ) != "Failed" ] if not toResolve: return S_OK() res = self.__updateMetadataCache( toResolve ) if not res['OK']: return res res = self.__updateReplicaCache( toResolve ) if not res['OK']: return res # Define the source URLs for lfn in toResolve: replicas = self.catalogReplicas.get( lfn, {} ) if self.sourceSE not in replicas: gLogger.warn( "resolveSource: skipping %s - not replicas at SourceSE %s" % ( lfn, self.sourceSE ) ) self.__setFileParameter( lfn, 'Reason', "No replica at SourceSE" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = returnSingleResult( self.oSourceSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setSourceSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Source" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Source files" ) # Get metadata of the sources, to check for existance, availability and caching res = self.oSourceSE.getFileMetadata( toResolve ) if not res['OK']: return S_ERROR( "Failed to check source file metadata" ) for lfn, error in res['Value']['Failed'].items(): if re.search( 'File does not exist', error ): gLogger.warn( "resolveSource: skipping %s - source file does not exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file does not exist" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: gLogger.warn( "resolveSource: skipping %s - failed to get source metadata" % lfn ) self.__setFileParameter( lfn, 'Reason', "Failed to get Source metadata" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toStage = [] nbStagedFiles = 0 for lfn, metadata in res['Value']['Successful'].items(): lfnStatus = self.fileDict.get( lfn, {} ).get( 'Status' ) if metadata['Unavailable']: gLogger.warn( "resolveSource: skipping %s - source file unavailable" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Unavailable" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif metadata['Lost']: gLogger.warn( "resolveSource: skipping %s - source file lost" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Lost" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif not metadata['Cached']: if lfnStatus != 'Staging': toStage.append( lfn ) elif metadata['Size'] != self.catalogMetadata[lfn]['Size']: gLogger.warn( "resolveSource: skipping %s - source file size mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source size mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif self.catalogMetadata[lfn]['Checksum'] and metadata['Checksum'] and \ not compareAdler( metadata['Checksum'], self.catalogMetadata[lfn]['Checksum'] ): gLogger.warn( "resolveSource: skipping %s - source file checksum mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source checksum mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif lfnStatus == 'Staging': # file that was staging is now cached self.__setFileParameter( lfn, 'Status', 'Waiting' ) nbStagedFiles += 1 # Some files were being staged if nbStagedFiles: self.log.info( 'resolveSource: %d files have been staged' % nbStagedFiles ) # Launching staging of files not in cache if toStage: gLogger.warn( "resolveSource: %s source files not cached, prestaging..." % len( toStage ) ) stage = self.oSourceSE.prestageFile( toStage ) if not stage["OK"]: gLogger.error( "resolveSource: error is prestaging", stage["Message"] ) for lfn in toStage: self.__setFileParameter( lfn, 'Reason', stage["Message"] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: for lfn in toStage: if lfn in stage['Value']['Successful']: self.__setFileParameter( lfn, 'Status', 'Staging' ) elif lfn in stage['Value']['Failed']: self.__setFileParameter( lfn, 'Reason', stage['Value']['Failed'][lfn] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) self.sourceResolved = True return S_OK() def resolveTarget( self ): """ find target SE eligible for submission :param self: self reference """ toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status' ) not in self.noSubmitStatus ] if not toResolve: return S_OK() res = self.__updateReplicaCache( toResolve ) if not res['OK']: return res for lfn in toResolve: res = returnSingleResult( self.oTargetSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: reason = res.get( 'Message', res['Message'] ) gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, reason ) ) self.__setFileParameter( lfn, 'Reason', reason ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setTargetSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Target" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Target files" ) res = self.oTargetSE.exists( toResolve ) if not res['OK']: return S_ERROR( "Failed to check target existence" ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toRemove = [] for lfn, exists in res['Value']['Successful'].items(): if exists: res = self.getSourceSURL( lfn ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - target exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Target exists" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif res['Value'] == self.fileDict[lfn]['Target']: gLogger.warn( "resolveTarget: skipping %s - source and target pfns are the same" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source and Target the same" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRemove.append( lfn ) if toRemove: self.oTargetSE.removeFile( toRemove ) return S_OK() def __filesToSubmit( self ): """ check if there is at least one file to submit :return: S_OK if at least one file is present, S_ERROR otherwise """ for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) source = self.fileDict[lfn].get( 'Source' ) target = self.fileDict[lfn].get( 'Target' ) if lfnStatus not in self.noSubmitStatus and source and target: return S_OK() return S_ERROR() def __createFTSFiles( self ): """ create LFNs file for glite-transfer-submit command This file consists one line for each fiel to be transferred: sourceSURL targetSURL [CHECKSUMTYPE:CHECKSUM] :param self: self reference """ self.__updateMetadataCache() for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) if lfnStatus not in self.noSubmitStatus: cksmStr = "" # # add chsmType:cksm only if cksmType is specified, else let FTS decide by itself if self.__cksmTest and self.__cksmType: checkSum = self.catalogMetadata.get( lfn, {} ).get( 'Checksum' ) if checkSum: cksmStr = " %s:%s" % ( self.__cksmType, intAdlerToHex( hexAdlerToInt( checkSum ) ) ) ftsFile = FTSFile() ftsFile.LFN = lfn ftsFile.SourceSURL = self.fileDict[lfn].get( 'Source' ) ftsFile.TargetSURL = self.fileDict[lfn].get( 'Target' ) ftsFile.SourceSE = self.sourceSE ftsFile.TargetSE = self.targetSE ftsFile.Status = self.fileDict[lfn].get( 'Status' ) ftsFile.Checksum = cksmStr ftsFile.Size = self.catalogMetadata.get( lfn, {} ).get( 'Size' ) self.ftsFiles.append( ftsFile ) self.submittedFiles += 1 return S_OK() def __createFTSJob( self, guid = None ): self.__createFTSFiles() ftsJob = FTSJob() ftsJob.RequestID = 0 ftsJob.OperationID = 0 ftsJob.SourceSE = self.sourceSE ftsJob.TargetSE = self.targetSE ftsJob.SourceToken = self.sourceToken ftsJob.TargetToken = self.targetToken ftsJob.FTSServer = self.ftsServer if guid: ftsJob.FTSGUID = guid for ftsFile in self.ftsFiles: ftsFile.Attempt += 1 ftsFile.Error = "" ftsJob.addFile( ftsFile ) self.ftsJob = ftsJob def __submitFTSTransfer( self ): """ create and execute glite-transfer-submit CLI command :param self: self reference """ log = gLogger.getSubLogger( 'Submit' ) self.__createFTSJob() submit = self.ftsJob.submitFTS2( command = self.submitCommand ) if not submit["OK"]: log.error( "unable to submit FTSJob: %s" % submit["Message"] ) return submit log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) # # update statuses for job files for ftsFile in self.ftsJob: ftsFile.FTSGUID = self.ftsJob.FTSGUID ftsFile.Status = "Submitted" ftsFile.Attempt += 1 log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) self.ftsGUID = self.ftsJob.FTSGUID return S_OK() def __resolveFTSServer( self ): """ resolve FTS server to use, it should be the closest one from target SE :param self: self reference """ from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTSServersForSites if not self.targetSE: return S_ERROR( "Target SE not set" ) res = getSitesForSE( self.targetSE ) if not res['OK'] or not res['Value']: return S_ERROR( "Could not determine target site" ) targetSites = res['Value'] targetSite = '' for targetSite in targetSites: targetFTS = getFTSServersForSites( [targetSite] ) if targetFTS['OK']: ftsTarget = targetFTS['Value'][targetSite] if ftsTarget: self.ftsServer = ftsTarget return S_OK( self.ftsServer ) else: return targetFTS return S_ERROR( 'No FTS server found for %s' % targetSite ) #################################################################### # # Methods for monitoring # def summary( self, untilTerminal = False, printOutput = False ): """ summary of FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ res = self.__isSummaryValid() if not res['OK']: return res while not self.isTerminal: res = self.__parseOutput( full = True ) if not res['OK']: return res if untilTerminal: self.__print() self.isRequestTerminal() if res['Value'] or ( not untilTerminal ): break time.sleep( 1 ) if untilTerminal: print "" if printOutput and ( not untilTerminal ): return self.dumpSummary( printOutput = printOutput ) return S_OK() def monitor( self, untilTerminal = False, printOutput = False, full = True ): """ monitor FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ if not self.ftsJob: self.resolveSource() self.__createFTSJob( self.ftsGUID ) res = self.__isSummaryValid() if not res['OK']: return res if untilTerminal: res = self.summary( untilTerminal = untilTerminal, printOutput = printOutput ) if not res['OK']: return res res = self.__parseOutput( full = full ) if not res['OK']: return res if untilTerminal: self.finalize() if printOutput: self.dump() return res def dumpSummary( self, printOutput = False ): """ get FTS job summary as str :param self: self reference :param bool printOutput: print summary to stdout """ outStr = '' for status in sorted( self.statusSummary ): if self.statusSummary[status]: outStr = '%s\t%-10s : %-10s\n' % ( outStr, status, str( self.statusSummary[status] ) ) outStr = outStr.rstrip( '\n' ) if printOutput: print outStr return S_OK( outStr ) def __print( self ): """ print progress bar of FTS job completeness to stdout :param self: self reference """ width = 100 bits = int( ( width * self.percentageComplete ) / 100 ) outStr = "|%s>%s| %.1f%s %s %s" % ( "="*bits, " "*( width - bits ), self.percentageComplete, "%", self.requestStatus, " "*10 ) sys.stdout.write( "%s\r" % ( outStr ) ) sys.stdout.flush() def dump( self ): """ print FTS job parameters and files to stdout :param self: self reference """ print "%-10s : %-10s" % ( "Status", self.requestStatus ) print "%-10s : %-10s" % ( "Source", self.sourceSE ) print "%-10s : %-10s" % ( "Target", self.targetSE ) print "%-10s : %-128s" % ( "Server", self.ftsServer ) print "%-10s : %-128s" % ( "GUID", self.ftsGUID ) for lfn in sorted( self.fileDict ): print "\n %-15s : %-128s" % ( 'LFN', lfn ) for key in ['Source', 'Target', 'Status', 'Reason', 'Duration']: print " %-15s : %-128s" % ( key, str( self.fileDict[lfn].get( key ) ) ) return S_OK() def __isSummaryValid( self ): """ check validity of FTS job summary report :param self: self reference """ if not self.ftsServer: return S_ERROR( "FTSServer not set" ) if not self.ftsGUID: return S_ERROR( "FTSGUID not set" ) return S_OK() def __parseOutput( self, full = False ): """ execute glite-transfer-status command and parse its output :param self: self reference :param bool full: glite-transfer-status verbosity level, when set, collect information of files as well """ monitor = self.ftsJob.monitorFTS2( command = self.monitorCommand, full = full ) if not monitor['OK']: return monitor self.percentageComplete = self.ftsJob.Completeness self.requestStatus = self.ftsJob.Status self.submitTime = self.ftsJob.SubmitTime statusSummary = monitor['Value'] if statusSummary: for state in statusSummary: self.statusSummary[state] = statusSummary[state] self.transferTime = 0 for ftsFile in self.ftsJob: lfn = ftsFile.LFN self.__setFileParameter( lfn, 'Status', ftsFile.Status ) self.__setFileParameter( lfn, 'Reason', ftsFile.Error ) self.__setFileParameter( lfn, 'Duration', ftsFile._duration ) targetURL = self.__getFileParameter( lfn, 'Target' ) if not targetURL['OK']: self.__setFileParameter( lfn, 'Target', ftsFile.TargetSURL ) self.transferTime += int( ftsFile._duration ) return S_OK() #################################################################### # # Methods for finalization # def finalize( self ): """ finalize FTS job :param self: self reference """ self.__updateMetadataCache() transEndTime = dateTime() regStartTime = time.time() res = self.getTransferStatistics() transDict = res['Value'] res = self.__registerSuccessful( transDict['transLFNs'] ) regSuc, regTotal = res['Value'] regTime = time.time() - regStartTime if self.sourceSE and self.targetSE: self.__sendAccounting( regSuc, regTotal, regTime, transEndTime, transDict ) return S_OK() def getTransferStatistics( self ): """ collect information of Transfers that can be used by Accounting :param self: self reference """ transDict = { 'transTotal': len( self.fileDict ), 'transLFNs': [], 'transOK': 0, 'transSize': 0 } for lfn in self.fileDict: if self.fileDict[lfn].get( 'Status' ) in self.successfulStates: if self.fileDict[lfn].get( 'Duration', 0 ): transDict['transLFNs'].append( lfn ) transDict['transOK'] += 1 if lfn in self.catalogMetadata: transDict['transSize'] += self.catalogMetadata[lfn].get( 'Size', 0 ) return S_OK( transDict ) def getFailedRegistrations( self ): """ get failed registrations dict :param self: self reference """ return S_OK( self.failedRegistrations ) def __registerSuccessful( self, transLFNs ): """ register successfully transferred files to the catalogs, fill failedRegistrations dict for files that failed to register :param self: self reference :param list transLFNs: LFNs in FTS job """ self.failedRegistrations = {} toRegister = {} for lfn in transLFNs: res = returnSingleResult( self.oTargetSE.getURL( self.fileDict[lfn].get( 'Target' ), protocol = 'srm' ) ) if not res['OK']: self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRegister[lfn] = { 'PFN' : res['Value'], 'SE' : self.targetSE } if not toRegister: return S_OK( ( 0, 0 ) ) res = self.__getCatalogObject() if not res['OK']: for lfn in toRegister: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) res = self.oCatalog.addReplica( toRegister ) if not res['OK']: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) for lfn, error in res['Value']['Failed'].items(): self.failedRegistrations[lfn] = toRegister[lfn] self.log.error( 'Registration of Replica failed', '%s : %s' % ( lfn, str( error ) ) ) return S_OK( ( len( res['Value']['Successful'] ), len( toRegister ) ) ) def __sendAccounting( self, regSuc, regTotal, regTime, transEndTime, transDict ): """ send accounting record :param self: self reference :param regSuc: number of files successfully registered :param regTotal: number of files attepted to register :param regTime: time stamp at the end of registration :param transEndTime: time stamp at the end of FTS job :param dict transDict: dict holding couters for files being transerred, their sizes and successfull transfers """ oAccounting = DataOperation() oAccounting.setEndTime( transEndTime ) oAccounting.setStartTime( self.submitTime ) accountingDict = {} accountingDict['OperationType'] = 'replicateAndRegister' result = getProxyInfo() if not result['OK']: userName = 'system' else: userName = result['Value'].get( 'username', 'unknown' ) accountingDict['User'] = userName accountingDict['Protocol'] = 'FTS' if 'fts3' not in self.ftsServer else 'FTS3' accountingDict['RegistrationTime'] = regTime accountingDict['RegistrationOK'] = regSuc accountingDict['RegistrationTotal'] = regTotal accountingDict['TransferOK'] = transDict['transOK'] accountingDict['TransferTotal'] = transDict['transTotal'] accountingDict['TransferSize'] = transDict['transSize'] accountingDict['FinalStatus'] = self.requestStatus accountingDict['Source'] = self.sourceSE accountingDict['Destination'] = self.targetSE accountingDict['TransferTime'] = self.transferTime oAccounting.setValuesFromDict( accountingDict ) self.log.verbose( "Attempting to commit accounting message..." ) oAccounting.commit() self.log.verbose( "...committed." ) return S_OK()
miloszz/DIRAC
DataManagementSystem/Client/FTSRequest.py
Python
gpl-3.0
37,261
<?php namespace de\chilan\WebsiteBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class WebsiteBundle extends Bundle { }
Mirar85/chilan
src/de/chilan/WebsiteBundle/WebsiteBundle.php
PHP
gpl-3.0
131
var _ = require("lodash"); module.exports = { // ensure client accepts json json_request: function(req, res, next){ if(req.accepts("application/json")) return next(); res.stash.code = 406; _.last(req.route.stack).handle(req, res, next); }, // init response init_response: function(req, res, next){ res.stash = {}; res.response_start = new Date(); return next(); }, // respond to client handle_response: function(req, res, next){ res.setHeader("X-Navigator-Response-Time", new Date() - res.response_start); res.stash = _.defaults(res.stash, { code: 404 }); if(_.has(res.stash, "body")) res.status(res.stash.code).json(res.stash.body); else res.sendStatus(res.stash.code); } }
normanjoyner/containership.plugin.navigator
lib/middleware.js
JavaScript
gpl-3.0
854
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html 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. =========================================================================*/ // .NAME vtkPVKeyFrameAnimationCue // .SECTION Description // vtkPVKeyFrameAnimationCue is a specialization of vtkPVAnimationCue that uses // the vtkPVKeyFrameCueManipulator as the manipulator. #ifndef vtkPVKeyFrameAnimationCue_h #define vtkPVKeyFrameAnimationCue_h #include "vtkPVAnimationCue.h" class vtkPVKeyFrame; class vtkPVKeyFrameCueManipulator; class VTKPVANIMATION_EXPORT vtkPVKeyFrameAnimationCue : public vtkPVAnimationCue { public: vtkTypeMacro(vtkPVKeyFrameAnimationCue, vtkPVAnimationCue); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Forwarded to the internal vtkPVKeyFrameCueManipulator. int AddKeyFrame (vtkPVKeyFrame* keyframe); int GetLastAddedKeyFrameIndex(); void RemoveKeyFrame(vtkPVKeyFrame*); void RemoveAllKeyFrames(); //BTX protected: vtkPVKeyFrameAnimationCue(); ~vtkPVKeyFrameAnimationCue(); vtkPVKeyFrameCueManipulator* GetKeyFrameManipulator(); private: vtkPVKeyFrameAnimationCue(const vtkPVKeyFrameAnimationCue&); // Not implemented void operator=(const vtkPVKeyFrameAnimationCue&); // Not implemented //ETX }; #endif
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/ParaViewCore/Animation/vtkPVKeyFrameAnimationCue.h
C
gpl-3.0
1,649
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/tupi.css"> <title></title> </head><body class="tupi_background3"> <p class="title">Vexamos como está a quedar</p> <p class="paragraph">Perfecto, xa temos a metade dos fotogramas do noso proxecto rematados. Chegou o momento de aprender a utilizar o <b>Módulo de reprodución</b>. É necesario aclarar que non hai unha regra xeral sobre cuantos fotogramas debes crear antes de facer unha vista previa do teu proxecto, esta é outra habilidade que desenvolveras a partir da práctica, noutras palabras: ti escolles. </p> <center> <table> <tbody> <tr> <td> <center><img src="./images/preview01.png"></center> </td> </tr> <tr> <td> <img src="./images/preview02.png"> </td> </tr> </tbody> </table> <p class="paragraph"> <b>Fig. 57</b> Vista previa do proxecto desde o Modulo de reprodución</p> </center><p class="paragraph">Debes ter tamén en en conta que facer unha vista previa da túa animación non afecta ao proxecto en absoluto, polo tanto, poderás entrar neste módulo tantas veces como queiras, o verdadeiramente importante é que o aproveites para comprobar como de satisfeito estás co resultado final e que poidas corrixir a tempo os erros que descubras. <br>A interface de vista previa é moi doada, así que no hai nada do que preocuparse. O panel de control conten todos os botóns necesarios para reproducir a túa animación, paso a paso o de xeito continuo. </p> <center> <img src="./images/preview03.png"> <p class="paragraph"> <b>Fig. 58</b> Panel de control do Modulo de reprodución</p></center> <p class="paragraph">Se observas a parte inferior do panel, atoparas máis información sobre o proxecto: o <i>nome da escena</i>, o <i>número total de fotogramas</i> e o <i>número de fotogramas por segundo (FPS)</i>, esta última opción é editábel e permitirache axustar a velocidade á que queres reproducir a túa animación. Canto máis grande sexa o valor, máis rápido se verá e canto máis pequeno, máis lento.</p> <p class="paragraph"> <b>Consello:</b> A opción <i>Repetir</i> é moi útil se tes poucos fotogramas e queres ter unha apreciación máis precisa sobre a fluidez do teu proxecto. Podes activala ou desactivala sempre que queiras. </p> <center> <img src="../images/preview04.png"> <p class="paragraph"> <b>Fig. 59</b> Opción «Repetir» do Modulo de reprodución&gt;</p></center><p class="paragraph">Agora toca continuar debuxando novos fotogramas ata cumprir con todo o recorrido proposto no guión. Volve á sección anterior, e remata con todos os gráficos pendentes. É probábel que che apareza moi canso ter que debuxar as mesmas partes de certos obxectos ou personaxes unha e outra vez, e estamos de acordo contigo. É por iso que estamos a traballar unha funcionalidade chamada "«Interpolación» (Tweening), que serve para aforrarche moito tempo no momento de ilustrar e que agardamos ter rematada moi cedo. </p> <p class="paragraph">Xa remataches de crear todos os fotogramas? Gústache o que ves no <b>Módulo de reprodución</b>? Moi ben, é hora de crear o teu primeiro <a href="video_file.html">ficheiro de vídeo</a>!</p> </body></html>
xtingray/tupi.win
src/components/help/help/gl/preview_time.html
HTML
gpl-3.0
3,499
// Decompiled with JetBrains decompiler // Type: System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection // Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll using System; using System.Collections; using System.ComponentModel; using System.Drawing.Design; using System.Runtime; namespace System.Web.UI.WebControls.WebParts { /// <summary> /// Contains a collection of static <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects, which is used when the connections are declared in content pages and the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartManager"/> control is declared in a master page. This class cannot be inherited. /// </summary> [Editor("System.ComponentModel.Design.CollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))] public sealed class ProxyWebPartConnectionCollection : CollectionBase { private WebPartManager _webPartManager; /// <summary> /// Gets a value indicating whether <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects can be added to the collection. /// </summary> /// /// <returns> /// true if connection objects cannot be added to the collection; otherwise, false. /// </returns> public bool IsReadOnly { get { if (this._webPartManager != null) return this._webPartManager.StaticConnections.IsReadOnly; return false; } } /// <summary> /// Gets or sets a connection item within the collection, based on an index number indicating the item's location in the collection. /// </summary> /// /// <returns> /// A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> at the specified index in the collection. /// </returns> /// <param name="index">An integer that indicates the index of a member of the collection. </param> public WebPartConnection this[int index] { get { return (WebPartConnection) this.List[index]; } set { this.List[index] = (object) value; } } /// <summary> /// Returns a specific member of the collection according to a unique identifier. /// </summary> /// /// <returns> /// The first <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> whose ID matches the value of the <paramref name="id"/> parameter. Returns null if no match is found. /// </returns> /// <param name="id">A string that contains the ID of a particular connection in the collection. </param> public WebPartConnection this[string id] { get { foreach (WebPartConnection webPartConnection in (IEnumerable) this.List) { if (webPartConnection != null && string.Equals(webPartConnection.ID, id, StringComparison.OrdinalIgnoreCase)) return webPartConnection; } return (WebPartConnection) null; } } /// <summary> /// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection"/> class. /// </summary> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public ProxyWebPartConnectionCollection() { } /// <summary> /// Adds a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object to the collection. /// </summary> /// /// <returns> /// An integer value that indicates where the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> was inserted into the collection. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to add to the collection. </param> public int Add(WebPartConnection value) { return this.List.Add((object) value); } /// <summary> /// Returns a value indicating whether a particular <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object exists in the collection. /// </summary> /// /// <returns> /// true if <paramref name="value"/> exists in the collection; otherwise, false. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> being checked for its existence in a collection. </param> public bool Contains(WebPartConnection value) { return this.List.Contains((object) value); } /// <summary> /// Copies the collection to an array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects. /// </summary> /// <param name="array">An array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects to contain the copied collection. </param><param name="index">An integer that indicates the starting point in the array at which to place the collection contents. </param> public void CopyTo(WebPartConnection[] array, int index) { this.List.CopyTo((Array) array, index); } /// <summary> /// Returns the position of a particular member of the collection. /// </summary> /// /// <returns> /// An integer that indicates the position of a particular object in the collection. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> that is a member of the collection. </param> public int IndexOf(WebPartConnection value) { return this.List.IndexOf((object) value); } /// <summary> /// Inserts a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object into the collection at the specified index. /// </summary> /// <param name="index">An integer indicating the ordinal position in the collection at which a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> should be inserted. </param><param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to insert into the collection. </param> public void Insert(int index, WebPartConnection value) { this.List.Insert(index, (object) value); } protected override void OnClear() { this.CheckReadOnly(); if (this._webPartManager != null) { foreach (WebPartConnection webPartConnection in (CollectionBase) this) this._webPartManager.StaticConnections.Remove(webPartConnection); } base.OnClear(); } protected override void OnInsert(int index, object value) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections.Insert(index, (WebPartConnection) value); base.OnInsert(index, value); } protected override void OnRemove(int index, object value) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections.Remove((WebPartConnection) value); base.OnRemove(index, value); } protected override void OnSet(int index, object oldValue, object newValue) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections[this._webPartManager.StaticConnections.IndexOf((WebPartConnection) oldValue)] = (WebPartConnection) newValue; base.OnSet(index, oldValue, newValue); } protected override void OnValidate(object value) { base.OnValidate(value); if (value == null) throw new ArgumentNullException("value", System.Web.SR.GetString("Collection_CantAddNull")); if (!(value is WebPartConnection)) throw new ArgumentException(System.Web.SR.GetString("Collection_InvalidType", new object[1] { (object) "WebPartConnection" })); } /// <summary> /// Removes the specified <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object from the collection. /// </summary> /// <param name="value">The <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to be removed. </param> public void Remove(WebPartConnection value) { this.List.Remove((object) value); } internal void SetWebPartManager(WebPartManager webPartManager) { this._webPartManager = webPartManager; foreach (WebPartConnection webPartConnection in (CollectionBase) this) this._webPartManager.StaticConnections.Add(webPartConnection); } private void CheckReadOnly() { if (this.IsReadOnly) throw new InvalidOperationException(System.Web.SR.GetString("ProxyWebPartConnectionCollection_ReadOnly")); } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/WebControls/WebParts/ProxyWebPartConnectionCollection.cs
C#
gpl-3.0
8,862
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Created by GNU Texinfo 5.1, http://www.gnu.org/software/texinfo/ --> <!-- This file redirects to the location of a node or anchor --> <head> <title>GNU Octave: XREFbicgstab</title> <meta name="description" content="GNU Octave: XREFbicgstab"> <meta name="keywords" content="GNU Octave: XREFbicgstab"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.indentedblock {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smallindentedblock {margin-left: 3.2em; font-size: smaller} div.smalllisp {margin-left: 3.2em} kbd {font-style:oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:nowrap} span.nolinebreak {white-space:nowrap} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> <meta http-equiv="Refresh" content="0; url=Specialized-Solvers.html#XREFbicgstab"> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <p>The node you are looking for is at <a href="Specialized-Solvers.html#XREFbicgstab">XREFbicgstab</a>.</p> </body>
dac922/octave-pkg-octave
doc/interpreter/octave.html/XREFbicgstab.html
HTML
gpl-3.0
1,952
// Copyright (c) The University of Dundee 2018-2019 // This file is part of the Research Data Management Platform (RDMP). // RDMP is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. // RDMP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with RDMP. If not, see <https://www.gnu.org/licenses/>. using System.Windows.Forms; using MapsDirectlyToDatabaseTable; namespace Rdmp.UI.Refreshing { /// <summary> /// <see cref="IRefreshBusSubscriber"/> for <see cref="Control"/> classes which want their lifetime to be linked to a single /// <see cref="IMapsDirectlyToDatabaseTable"/> object. This grants notifications of publish events about the object and ensures /// your <see cref="Control"/> is closed when/if the object is deleted. /// /// <para>See <see cref="RefreshBus.EstablishLifetimeSubscription"/></para> /// </summary> public interface ILifetimeSubscriber:IContainerControl,IRefreshBusSubscriber { } }
HicServices/RDMP
Rdmp.UI/Refreshing/ILifetimeSubscriber.cs
C#
gpl-3.0
1,369
import sys, os, urllib, time, socket, mt, ssl from dlmanager.NZB import NZBParser from dlmanager.NZB.nntplib2 import NNTP_SSL,NNTPError,NNTP, NNTPReplyError from dlmanager.NZB.Decoder import ArticleDecoder class StatusReport(object): def __init__(self): self.message = "Downloading.." self.total_bytes = 0 self.current_bytes = 0 self.completed = False self.error_occured = False self.start_time = 0 self.file_name = "" self.kbps = 0 self.assembly = False self.assembly_percent = 0 class NZBClient(): def __init__(self, nzbFile, save_to, nntpServer, nntpPort, nntpUser=None, nntpPassword=None, nntpSSL=False, nntpConnections=5, cache_path=""): # Settings self.save_to = save_to self.nntpServer = nntpServer self.nntpUser = nntpUser self.nntpPort = nntpPort self.nntpPassword = nntpPassword self.nntpSSL = nntpSSL self.nntpConnections = nntpConnections self.threads = [] self.running = False # setup our cache folder. self.cache_path = cache_path if ( self.cache_path == "" ): self.cache_path = "packages/dlmanager/cache/" self.clearCache() # ensure both directorys exist mt.utils.mkdir(self.save_to) mt.utils.mkdir(self.cache_path) # Open the NZB, get this show started. realFile = urllib.urlopen(nzbFile) self.nzb = NZBParser.parse(realFile) self.all_decoded = False self.connection_count = 0 # used to track status. self.status = StatusReport() self.status.file_name = nzbFile self.status.total_bytes = self.nzb.size # Segment tracking. self.cache = [] self.segment_list = [] self.segments_finished = [] self.segments_aborted = [] # Queues. self.segment_queue = [] self.failed_queue = [] # Used to track the speed. self.speedTime = 0 self.speedCounter = 0 def start(self): # keep track of running time. self.status.start_time = time.time() self.running = True # Generate a list of segments and build our queue. for file in self.nzb.files: for seg in file.segments: self.segment_list.append(seg.msgid) self.segment_queue.append(seg) # start the connections. for a in range(0, self.nntpConnections): thread = NNTPConnection(a, self.nntpServer, self.nntpPort, self.nntpUser, self.nntpPassword, self.nntpSSL, self.nextSeg, self.segComplete, self.segFailed, self.threadStopped) self.threads.append(thread) self.connection_count += 1 thread.start() # start the article decoder. self.articleDecoder = ArticleDecoder(self.decodeNextSeg, self.save_to, self.cache_path, self.decodeFinished, self.decodeSuccess, self.decodeFailed, self.assemblyStatus) self.articleDecoder.start() def getStatus(self): return self.status # Article Decoder - Next segment. def decodeNextSeg(self): # if we're not running send an instant kill switch. if ( not self.running ): return -1 # try to grab a segment from the cache to decode. seg = None try: seg = self.cache.pop() except: pass if ( seg == None ) and ( self.all_decoded ): return -1 return seg # Article Decoder - Decoded all segments. def decodeFinished(self): self.status.completed = True # Article Decoder - Decode success. def decodeSuccess(self, seg): self.status.current_bytes += seg.size self.segments_finished.append(seg.msgid) if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ): self.all_decoded = True # Article Decoder - Decode failed. def decodeFailed(self, seg): if ( seg == None ): return mt.log.debug("Segment failed to decode: " + seg.msgid) self.segFailed(seg) # Article Decoder - Assembly Status. def assemblyStatus(self, percent): self.status.assembly = True self.status.assembly_percent = percent # NNTP Connection - Thread stopped. def threadStopped(self, thread_num): self.connection_count -= 1 # NNTP Connection - Segment completed. def segComplete(self, seg): if ( seg == None ): return if ( seg.data ): data_size = len("".join(seg.data)) current_time = time.time() if ( (current_time - self.speedTime) > 1 ): self.status.kbps = self.speedCounter self.speedCounter = 0 self.speedTime = current_time else: self.speedCounter += (data_size/1024) self.cache.append(seg) #mt.log.debug("Segment Complete: " + seg.msgid) # NNTP Connection - Download of segment failed. def segFailed(self, seg): if ( seg == None ): return if ( seg.aborted() ): mt.log.error("Segment Aborted: " + seg.msgid + " after " + str(seg.retries) + " attempts.") self.segments_aborted.append(seg.msgid) seg.data = [] if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ): self.all_decoded = True return seg.retries += 1 mt.log.error("Segment Failed: " + seg.msgid + " Attempt #" + str(seg.retries) + ".") self.failed_queue.append(seg) # NNTP Connection - Next Segment def nextSeg(self): # if we're not running send an instant kill switch. if ( not self.running ): return -1 # try to get a segment from main queue or failed queue. queue_empty = False seg = None try: seg = self.segment_queue.pop() except: try: seg = self.failed_queue.pop() except: queue_empty = True pass pass # We're all outta segments, if they're done decoding, kill the threads. if ( queue_empty ) and ( self.all_decoded ): return -1 return seg # empty the cache of any files. def clearCache(self): mt.utils.rmdir(self.cache_path) def stop(self): self.running = False self.articleDecoder.stop() for thread in self.threads: thread.stop() self.clearCache() class NNTPConnection(mt.threads.Thread): def __init__(self, connection_number, server, port, username, password, ssl, nextSegFunc, onSegComplete = None, onSegFailed = None, onThreadStop = None): mt.threads.Thread.__init__(self) # Settings self.connection = None self.connection_number = connection_number self.server = server self.port = port self.username = username self.password = password self.ssl = ssl # Events. self.nextSegFunc = nextSegFunc self.onSegComplete = onSegComplete self.onSegFailed = onSegFailed self.onThreadStop = onThreadStop def connect(self): # Open either an SSL or regular NNTP connection. try: if ( self.ssl ): self.connection = NNTP_SSL(self.server, self.port, self.username, self.password, False, True, timeout=15) else: self.connection = NNTP(self.server, self.port, self.username, self.password, False, True, timeout=15) except: pass if ( self.connection ): return True return False def disconnect(self): if ( self.connection ): try: self.connection.quit() except: pass self.connection = None def run(self): connection = None seg = None # Thread has started. mt.log.debug("Thread " + str(self.connection_number) + " started.") start_time = time.time() while(self.running): seg = None connected = self.connect() if ( connected ): while(self.running): seg = self.nextSegFunc() # Out of segments, sleep for a bit and see if we get anymore. if ( seg == None ): self.sleep(0.1) continue # Download complete, bail. if ( seg == -1 ): self.running = False seg = None break # Attempt to grab a segment. try: resp, nr, id, data = self.connection.body("<%s>" % seg.msgid) if resp[0] == "2": seg.data = data if ( self.onSegComplete ): self.onSegComplete(seg) seg = None except ssl.SSLError: break except NNTPError as e: mt.log.error("Error getting segment: " + e.response) pass except: mt.log.error("Error getting segment.") pass if ( seg and self.onSegFailed ): self.onSegFailed(seg) seg = None # Disconnect when we're finished. if ( seg and self.onSegFailed ): self.onSegFailed(seg) self.disconnect() else: mt.log.error("Connection error. Reconnecting in 3 seconds.") self.sleep(3) # Thread has ended. self.disconnect() # just to be safe. end_time = time.time() mt.log.debug("Thread " + str(self.connection_number) + " stopped after " + str(end_time-start_time) + " seconds.") if ( self.onThreadStop ): self.onThreadStop(self.connection_number)
andr3wmac/metaTower
packages/dlmanager/NZB/NZBClient.py
Python
gpl-3.0
10,499
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0
schesis/fix
tests/decorators/test_with_fixture.py
Python
gpl-3.0
3,536
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] )
espressopp/espressopp
src/integrator/CapForce.py
Python
gpl-3.0
2,764
#!/bin/bash gnuplot temp/TermodinamicalStat_L=14_PP=4/*.plot gnuplot temp/DensityStat_L=14_PP=4/*.plot
nlare/Landau-Wang-omp
plot_graph_L=14_PP=4.sh
Shell
gpl-3.0
103
# @author Peter Kappelt # @author Clemens Bergmann # @version 1.16.dev-cf.9 package main; use strict; use warnings; use Data::Dumper; use JSON; use TradfriUtils; sub TradfriGroup_Initialize($) { my ($hash) = @_; $hash->{DefFn} = 'Tradfri_Define'; $hash->{UndefFn} = 'Tradfri_Undef'; $hash->{SetFn} = 'Tradfri_Set'; $hash->{GetFn} = 'Tradfri_Get'; $hash->{AttrFn} = 'Tradfri_Attr'; $hash->{ReadFn} = 'Tradfri_Read'; $hash->{ParseFn} = 'TradfriGroup_Parse'; $hash->{Match} = '(^subscribedGroupUpdate::)|(^moodList::)'; $hash->{AttrList} = "usePercentDimming:1,0 " . $readingFnAttributes; } #messages look like this: (without newlines) # subscribedGroupUpdate::group-id::{ # "createdAt":1494088484, # "mood":198884, # "groupid":173540, # "members":[ # { # "name":"Fenster Links", # "deviceid":65537 # }, # { # "deviceid":65536 # }, # { # "name":"Fenster Rechts", # "deviceid":65538 # } # ], # "name":"Wohnzimmer", # "dimvalue":200, # "onoff":0 # } sub TradfriGroup_Parse($$){ my ($io_hash, $message) = @_; my @parts = split('::', $message); if(int(@parts) < 3){ #expecting at least three parts return undef; } my $messageID = $parts[1]; #check if group with the id exists if(my $hash = $modules{'TradfriGroup'}{defptr}{$messageID}) { #parse the JSON data my $jsonData = eval{ JSON->new->utf8->decode($parts[2]) }; if($@){ return undef; #the string was probably not valid JSON } if('subscribedGroupUpdate' eq $parts[0]){ my $createdAt = FmtDateTimeRFC1123($jsonData->{'createdAt'} || ''); my $name = $jsonData->{'name'} || ''; my $members = JSON->new->pretty->encode($jsonData->{'members'}); #dimvalue is in range 0 - 254 my $dimvalue = $jsonData->{'dimvalue'} || '0'; #dimpercent is always in range 0 - 100 my $dimpercent = int($dimvalue / 2.54 + 0.5); $dimpercent = 1 if($dimvalue == 1); $dimvalue = $dimpercent if (AttrVal($hash->{name}, 'usePercentDimming', 0) == 1); my $state = 'off'; if($jsonData->{'onoff'} eq '0'){ $dimpercent = 0; }else{ $state = Tradfri_stateString($dimpercent); } my $onoff = ($jsonData->{'onoff'} || '0') ? 'on':'off'; readingsBeginUpdate($hash); readingsBulkUpdateIfChanged($hash, 'createdAt', $createdAt, 1); readingsBulkUpdateIfChanged($hash, 'name', $name, 1); readingsBulkUpdateIfChanged($hash, 'members', $members, 1); readingsBulkUpdateIfChanged($hash, 'dimvalue', $dimvalue, 1); readingsBulkUpdateIfChanged($hash, 'pct', $dimpercent, 1); readingsBulkUpdateIfChanged($hash, 'onoff', $onoff, 1) ; readingsBulkUpdateIfChanged($hash, 'state', $state, 1); readingsEndUpdate($hash, 1); }elsif('moodList' eq $parts[0]){ #update of mood list readingsSingleUpdate($hash, 'moods', JSON->new->pretty->encode($jsonData), 1); $hash->{helper}{moods} = undef; foreach (@{$jsonData}){ $hash->{helper}{moods}->{$_->{name}} = $_; } } #$attr{$hash->{NAME}}{webCmd} = 'pct:toggle:on:off'; #$attr{$hash->{NAME}}{devStateIcon} = '{(Tradfri_devStateIcon($name),"toggle")}' if( !defined( $attr{$hash->{name}}{devStateIcon} ) ); #return the appropriate group's name return $hash->{NAME}; } return undef; } 1; =pod =item device =item summary controls an IKEA Trådfri lighting group =item summary_DE steuert eine IKEA Trådfri Beleuchtungsgruppe =begin html <a name="TradfriGroup"></a> <h3>TradfriGroup</h3> <ul> <i>TradfriGroup</i> is a module for controlling an IKEA Trådfri lighting group. You currently need a gateway for the connection. See TradfriGateway. <br><br> <a name="TradfriGroupdefine"></a> <b>Define</b> <ul> <code>define &lt;name&gt; TradfriGroup &lt;group-address&gt;</code> <br><br> Example: <code>define trGroupOne TradfriGroup 193768</code> <br><br> You can get the ID of the lighting groups by calling "get TradfriGW groupList" on the gateway device </ul> <br> <a name="TradfriGroupset"></a> <b>Set</b><br> <ul> <code>set &lt;name&gt; &lt;option&gt; [&lt;value&gt;]</code> <br><br> You can set the following options. See <a href="http://fhem.de/commandref.html#set">commandref#set</a> for more info about the set command. <br><br> Options: <ul> <li><i>on</i><br> Turns all devices in the group on.<br>The brightness is the one, before the devices were turned off</li> <li><i>off</i><br> Turn all devices in the group off.</li> <li><i>dimvalue</i><br> Set the brightness of all devices in the group.<br> You need to specify the brightness value as an integer between 0 and 100/254.<br> The largest value depends on the attribute "usePercentDimming".<br> If this attribute is set, the largest value will be 100.<br> By default, it isn't set, so the largest value is 254.<br> A brightness value of 0 turns the devices off.<br> If the devices are off, and you set a value greater than 0, they'll turn on.</li> <li><i>mood</i><br> Set the mood of the group.<br> Moods are preconfigured color temperatures, brightnesses and states for each device of the group<br> In order to set the mood, you need a mood ID or the mood's name.<br> You can list the moods that are available for this group by running "get moods".<br> Note, that the mood's name isn't necessarily the same that you've defined in the IKEA app. This module is currently unable to handle whitespaces in mood names, so whitespaces get removed internally. Check the reading "moods" after running "get moods" in order to get the names, that you may use with this module.<br> Mood names are case-sensitive. Mood names, that are only made out of numbers are not supported.</li> </ul> </ul> <br> <a name="TradfriGroupget"></a> <b>Get</b><br> <ul> <code>get &lt;name&gt; &lt;option&gt;</code> <br><br> You can get the following information about the group. See <a href="http://fhem.de/commandref.html#get">commandref#get</a> for more info about the get command. <br><br> Options: <ul> <li><i>moods</i><br> Get all moods (their name and their ID) that are configured for this group<br> The JSON-formatted result is stored in the Reading "moods"</br> Please note, that the mood IDs may differ between different groups (though they are the same moods) -> check them for each group</li> </ul> </ul> <br> <a name="TradfriGroupreadings"></a> <b>Readings</b><br> <ul> The following readings are displayed for a group. Once there is a change and the connection to the gateway is made, they get updated automatically. <br><br> Readings: <ul> <li><i>createdAt</i><br> A timestamp string, like "Sat, 15 Apr 2017 18:29:24 GMT", that indicates, when the group was created in the gateway.</li> <li><i>dimvalue</i><br> The brightness that is set for this group. It is a integer in the range of 0 to 100/ 254.<br> The greatest dimvalue depends on the attribute "usePercentDimming", see below.</li> <li><i>pct</i><br> The brightness that is set for this device in percent.</li> <li><i>members</i><br> JSON-String that contains all member-IDs and their names.</li> <li><i>moods</i><br> JSON info of all moods and their names, e.g.:<br> [ { "groupid" : 173540, "moodid" : 198884, "name" : "EVERYDAY" }, { "moodid" : 213983, "name" : "RELAX", "groupid" : 173540 }, { "groupid" : 173540, "name" : "FOCUS", "moodid" : 206399 } ]<br> This reading isn't updated automatically, you've to call "get moods" in order to refresh them.</li> <li><i>name</i><br> The name of the group that you've set in the app.</li> <li><i>onoff</i><br> Indicates whether the device is on or off, can be the strings 'on' or 'off'</li> <li><i>state</i><br> Indicates, whether the group is on or off. Thus, the reading's value is either "on" or "off", too.</li> </ul> </ul> <br> <a name="TradfriGroupattr"></a> <b>Attributes</b> <ul> <code>attr &lt;name&gt; &lt;attribute&gt; &lt;value&gt;</code> <br><br> See <a href="http://fhem.de/commandref.html#attr">commandref#attr</a> for more info about the attr command. <br><br> Attributes: <ul> <li><i>usePercentDimming</i> 0/1<br> If this attribute is one, the largest value for "set dimvalue" will be 100.<br> Otherwise, the largest value is 254.<br> This attribute is useful, if you need to control the brightness in percent (0-100%)<br> For backward compatibility, it is disabled by default, so the largest dimvalue is 254 by default. </li> </ul> </ul> </ul> =end html =cut
peterkappelt/Tradfri-FHEM
src/FHEM/31_TradfriGroup.pm
Perl
gpl-3.0
9,629
/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ #include "demandmodel.h" #include "Elements/junction.h" #include <cmath> #include <algorithm> using namespace std; //----------------------------------------------------------------------------- // Parent constructor and destructor //----------------------------------------------------------------------------- DemandModel::DemandModel() : expon(0.0) {} DemandModel::DemandModel(double expon_) : expon(expon_) {} DemandModel::~DemandModel() {} //----------------------------------------------------------------------------- // Demand model factory //----------------------------------------------------------------------------- DemandModel* DemandModel::factory(const string model, const double expon_) { if ( model == "FIXED" ) return new FixedDemandModel(); else if ( model == "CONSTRAINED" ) return new ConstrainedDemandModel(); else if ( model == "POWER" ) return new PowerDemandModel(expon_); else if ( model == "LOGISTIC" ) return new LogisticDemandModel(expon_); else return nullptr; } //----------------------------------------------------------------------------- // Default functions //----------------------------------------------------------------------------- double DemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->fullDemand; } //----------------------------------------------------------------------------- /// Fixed Demand Model //----------------------------------------------------------------------------- FixedDemandModel::FixedDemandModel() {} //----------------------------------------------------------------------------- /// Constrained Demand Model //----------------------------------------------------------------------------- ConstrainedDemandModel::ConstrainedDemandModel() {} bool ConstrainedDemandModel::isPressureDeficient(Junction* junc) { //if ( junc->fixedGrade || // ... return false if normal full demand is non-positive if (junc->fullDemand <= 0.0 ) return false; double hMin = junc->elev + junc->pMin; if ( junc->head < hMin ) { junc->fixedGrade = true; junc->head = hMin; return true; } return false; } double ConstrainedDemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->actualDemand; } //----------------------------------------------------------------------------- /// Power Demand Model //----------------------------------------------------------------------------- PowerDemandModel::PowerDemandModel(double expon_) : DemandModel(expon_) {} double PowerDemandModel::findDemand(Junction* junc, double p, double& dqdh) { // ... initialize demand and demand derivative double qFull = junc->fullDemand; double q = qFull; dqdh = 0.0; // ... check for positive demand and pressure range double pRange = junc->pFull - junc->pMin; if ( qFull > 0.0 && pRange > 0.0) { // ... find fraction of full pressure met (f) double factor = 0.0; double f = (p - junc->pMin) / pRange; // ... apply power function if (f <= 0.0) factor = 0.0; else if (f >= 1.0) factor = 1.0; else { factor = pow(f, expon); dqdh = expon / pRange * factor / f; } // ... update total demand and its derivative q = qFull * factor; dqdh = qFull * dqdh; } return q; } //----------------------------------------------------------------------------- /// Logistic Demand Model //----------------------------------------------------------------------------- LogisticDemandModel::LogisticDemandModel(double expon_) : DemandModel(expon_), a(0.0), b(0.0) {} double LogisticDemandModel::findDemand(Junction* junc, double p, double& dqdh) { double f = 1.0; // fraction of full demand double q = junc->fullDemand; // demand flow (cfs) double arg; // argument of exponential term double dfdh; // gradient of f w.r.t. pressure head // ... initialize derivative dqdh = 0.0; // ... check for positive demand and pressure range if ( junc->fullDemand > 0.0 && junc->pFull > junc->pMin ) { // ... find logistic function coeffs. a & b setCoeffs(junc->pMin, junc->pFull); // ... prevent against numerical over/underflow arg = a + b*p; if (arg < -100.) arg = -100.0; else if (arg > 100.0) arg = 100.0; // ... find fraction of full demand (f) and its derivative (dfdh) f = exp(arg); f = f / (1.0 + f); f = max(0.0, min(1.0, f)); dfdh = b * f * (1.0 - f); // ... evaluate demand and its derivative q = junc->fullDemand * f; dqdh = junc->fullDemand * dfdh; } return q; } void LogisticDemandModel::setCoeffs(double pMin, double pFull) { // ... computes logistic function coefficients // assuming 99.9% of full demand at full pressure // and 1% of full demand at minimum pressure. double pRange = pFull - pMin; a = (-4.595 * pFull - 6.907 * pMin) / pRange; b = 11.502 / pRange; }
jeffrey-newman/ENLink
OWA_EN3/src/Models/demandmodel.cpp
C++
gpl-3.0
5,340
// <osiris_sps_source_header> // This file is part of Osiris Serverless Portal System. // Copyright (C)2005-2012 Osiris Team ([email protected]) / http://www.osiris-sps.org ) // // Osiris Serverless Portal System is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Osiris Serverless Portal System is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Osiris Serverless Portal System. If not, see <http://www.gnu.org/licenses/>. // </osiris_sps_source_header> #ifndef _OS_ENGINE_IDEPICKERCOMPONENT_H #define _OS_ENGINE_IDEPICKERCOMPONENT_H #include "ideportalcontrol.h" #include "idepickerselect.h" #include "entitiesentities.h" ////////////////////////////////////////////////////////////////////// OS_NAMESPACE_BEGIN() ////////////////////////////////////////////////////////////////////// class IExtensionsComponent; ////////////////////////////////////////////////////////////////////// class EngineExport IdePickerComponent : public IdePickerSelect { typedef IdePickerSelect ControlBase; // Construction public: IdePickerComponent(); virtual ~IdePickerComponent(); // Attributes public: // Events private: // Operations private: void addComponent(shared_ptr<IExtensionsComponent> component); // IControl interface public: virtual void onLoad(); virtual void onPreRender(); protected: }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// OS_NAMESPACE_END() ////////////////////////////////////////////////////////////////////// #endif // _OS_ENGINE_IDEPICKERCOMPONENT_H
OsirisSPS/osiris-sps
client/src/engine/idepickercomponent.h
C
gpl-3.0
2,053
class AddVersionDone < ActiveRecord::Migration def up add_column :versions, :is_done, :boolean end def down remove_column :versions, :is_done end end
nmeylan/RORganize
db/migrate/20140623191731_add_version_done.rb
Ruby
gpl-3.0
167
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hometask 7-8</title> <link rel="stylesheet" href="сss/reset.css"> <link rel="stylesheet" href="сss/style.css"> <link rel="stylesheet" media="screen and (min-width:0px) and (max-width:480px)" href="сss/style_320px.css" /> <link rel="stylesheet" media="screen and (min-width:480px) and (max-width:768px)" href="сss/style_480px.css" /> <link rel="stylesheet" media="screen and (min-width:768px) and (max-width:960px)" href="сss/style_768px.css" /> </head> <body> <div class="background background__top"> <header> <div class="wrapper top__bar"> <div class="logo"><img src="img/logo.png" alt="PINGBULLER"></div> <ul class="menu"> <li><a href="#" class="menu__item">HOME</a></li> <li><a href="#" class="menu__item">ABOUT</a></li> <li><a href="#" class="menu__item">BLOG</a></li> <li><a href="#" class="menu__item">PRODUCTS</a></li> <li><a href="#" class="menu__item">LOREM IPSUM</a></li> <li><a href="#" class="menu__item">DOLOR SIT AMET</a></li> </ul> </div> <div class="clearfix" style="clear: both;"></div> <div class="banner"> <div class="banner__inner"> <div class="wrapper banner_content"> <div class="iphone"><img src="img/iphone.png" alt=""></div> <div class="content_text"> <h1>Lorem Ipsum Dolor</h1> <h3>IT WILL MAKE ALL OF YOUR DREAMS COME <span class="invisible invisible_320">TRUE</span></h3> <p>Semper sollicitudin gravida eget, vestibulum sit amet sapien. Nunc dignissim tincidunt est, et auctor turpis ornare a. Nam venenatis hendrerit est <span class="invisible">at volutpat. Morbi elementum euismod lacus id semper. In odio nunc, imperdiet eget aliquam quis, euismod id lectus. Nulla interdum arcu et felis aliquam a tempus lectus lobortis.</span></p> </div> <div class="arrows"> <div class="arrow__right"><a href="#"><img src="img/arrow_r.png" alt=""></a></div> <div class="arrow__left"><a href="#"><img src="img/arrow_l.png" alt=""></a></div> </div> <div class="slider_circles"> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> </div> </div> </div> </div> </header> </div> <div class="background background__articles"> <div class="wrapper articles"> <div class="articles__item"> <div class="sprite icon__1"></div> <h2>ABOUT OUR COMPANY</h2> <p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus<span class="invisible_320"> ultrices posuere. Pellentesque vel lacus <span class="invisible"> eget nisi convallis auctor. Nam</span></span></p> <a href="#">READ MORE</a> </div> <div class="articles__item"> <div class="sprite icon__2"></div> <h2>ABOUT OUR COMPANY</h2> <p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus<span class="invisible_320"> ultrices posuere. Pellentesque vel lacus <span class="invisible"> eget nisi convallis auctor. Nam</span></span></p> <a href="#">READ MORE</a> </div> <div class="articles__item"> <div class="sprite icon__3"></div> <h2>ABOUT OUR COMPANY</h2> <p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus<span class="invisible_320"> ultrices posuere. Pellentesque vel lacus <span class="invisible"> eget nisi convallis auctor. Nam</span></span></p> <a href="#">READ MORE</a> </div> </div> </div> <div class="background background__content"> <div class="wrapper content"> <div class="starts_back"> <div class="starts_content"> <img src="img/muzgik.png" alt="Какой-то мужик"> <h2>PINGBULLER <span>STARTS HERE</span></h2> <p>“Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices po- suere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae<span class="invisible_320"> lectus eu libero pellentesque pulvinar<span class="invisible"> urna risus, mattis pulvinar bibendum in, venenatis quis neque. Mauris nec metus ultricies erat consequat dignissim non eu nisl.”</span></span></p> </div> <div class="starts_circles"> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> </div> </div> <div class="updates"> <h2>RECENT UPDATES</h2> <div class="updates__item update1"> <h4>Nunc turpis neque<span class="invisible_320"> feugiat eget </span></h4> <p>Posted by Admin on March 13<span class="invisible_320"> 2012 <span class="invisible">in Recent News</span></span></p> </div> <div class="updates__item update2"> <h4>Nunc turpis neque <span class="invisible_320"> feugiat eget </span></h4> <p>Posted by Admin on March 13<span class="invisible_320"> 2012<span class="invisible"> in Category</span></span></p> </div> <div class="updates__item update3"> <h4>Nunc turpis neque <span class="invisible_320"> feugiat eget </span></h4> <p>Posted by Admin on March 13<span class="invisible_320"> 2012<span class="invisible"> in Blog Updates</span></span></p> </div> <a href="">READ MORE HERE</a> </div> </div> </div> <div class="background background_logos"> <div class="wrapper logos"> </div> </div> <div class="background content__bottom_background"> <div class="wrapper content__bottom"> <div class="content__bottom_item pigbull"> <h2>PIGBULL<span>ER</span></h2> <div class="copyright">Copyright 2013, Pingbull AS</div> <div class="visible"> <h3>NEWS CATEGORIES</h3> <p class="">Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque <span class="invisible"> pulvinar. Quisque urna risus, mattis pulvinar bibendum in, venenatis quis</span></p> </div> <div class="invisible"><p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque pul</p></div> </div> <div class="content__bottom_item"> <h3>RECENT COMMENTS</h3> <p class="">Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque <span class="invisible"> pulvinar. Quisque urna risus, mattis pulvinar bibendum in, venenatis quis</span></p> </div> <div class="content__bottom_item"> <h3>NEWS CATEGORIES</h3> <p class="">Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque <span class="invisible"> pulvinar. Quisque urna risus, mattis pulvinar bibendum in, venenatis quis</span></p> </div> </div> </div> <div class="background footer__background"> <div class="wrapper footer"> <div class="footer_menu"> <a href="#" class="footer_menu__item">HOME</a> <a href="#" class="footer_menu__item">ABOUT</a> <a href="#" class="footer_menu__item">BLOG</a> <a href="#" class="footer_menu__item">PRODUCTS</a> <a href="#" class="footer_menu__item">LOREM IPSUM</a> <a href="#" class="footer_menu__item">DOLOR SIT AMET</a> </div> <div class="design"> <p>Designed by <span>Pingbull AS</span></p> </div> </div> </div> </body> </html>
yassisme/Hometasks
7-8 DZ/index.html
HTML
gpl-3.0
7,687
var struct_m_s_vehicle_1_1_lane_q = [ [ "allowsContinuation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a1491a03d3e914ce9f78fe892c6f8594b", null ], [ "bestContinuations", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a2fc7b1df76210eff08026dbd53c13312", null ], [ "bestLaneOffset", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#aa7f926a77c7d33c071c620ae7e9d0ac1", null ], [ "lane", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a3df6bd9b94a7e3e4795547feddf68bf2", null ], [ "length", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a637a05a2b120bacaf781181febc5b3bb", null ], [ "nextOccupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#acf8243e1febeb75b139a8b10bb679107", null ], [ "occupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a51e793a9c0bfda3e315c62f579089f82", null ] ];
cathyyul/sumo-0.18
docs/doxygen/d3/d89/struct_m_s_vehicle_1_1_lane_q.js
JavaScript
gpl-3.0
801
############################################################################## # Build global options # NOTE: Can be overridden externally. # # Compiler options here. ifeq ($(USE_OPT),) USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16 endif # C specific options here (added to USE_OPT). ifeq ($(USE_COPT),) USE_COPT = endif # C++ specific options here (added to USE_OPT). ifeq ($(USE_CPPOPT),) USE_CPPOPT = -fno-rtti endif # Enable this if you want the linker to remove unused code and data ifeq ($(USE_LINK_GC),) USE_LINK_GC = yes endif # Linker extra options here. ifeq ($(USE_LDOPT),) USE_LDOPT = endif # Enable this if you want link time optimizations (LTO) ifeq ($(USE_LTO),) USE_LTO = yes endif # If enabled, this option allows to compile the application in THUMB mode. ifeq ($(USE_THUMB),) USE_THUMB = yes endif # Enable this if you want to see the full log while compiling. ifeq ($(USE_VERBOSE_COMPILE),) USE_VERBOSE_COMPILE = no endif # If enabled, this option makes the build process faster by not compiling # modules not used in the current configuration. ifeq ($(USE_SMART_BUILD),) USE_SMART_BUILD = yes endif # # Build global options ############################################################################## ############################################################################## # Architecture or project specific options # # Stack size to be allocated to the Cortex-M process stack. This stack is # the stack used by the main() thread. ifeq ($(USE_PROCESS_STACKSIZE),) USE_PROCESS_STACKSIZE = 0x400 endif # Stack size to the allocated to the Cortex-M main/exceptions stack. This # stack is used for processing interrupts and exceptions. ifeq ($(USE_EXCEPTIONS_STACKSIZE),) USE_EXCEPTIONS_STACKSIZE = 0x400 endif # Enables the use of FPU (no, softfp, hard). ifeq ($(USE_FPU),) USE_FPU = no endif # # Architecture or project specific options ############################################################################## ############################################################################## # Project, sources and paths # # Define project name here PROJECT = ch # Imported source files and paths CHIBIOS = ../../../.. # Startup files. include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f3xx.mk # HAL-OSAL files (optional). include $(CHIBIOS)/os/hal/hal.mk include $(CHIBIOS)/os/hal/ports/STM32/STM32F37x/platform.mk include $(CHIBIOS)/os/hal/boards/ST_STM32373C_EVAL/board.mk include $(CHIBIOS)/os/hal/osal/rt/osal.mk # RTOS files (optional). include $(CHIBIOS)/os/rt/rt.mk include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/port_v7m.mk # Other files (optional). include $(CHIBIOS)/test/lib/test.mk include $(CHIBIOS)/test/rt/rt_test.mk include $(CHIBIOS)/test/oslib/oslib_test.mk include $(CHIBIOS)/os/hal/lib/streams/streams.mk include $(CHIBIOS)/os/various/shell/shell.mk # Define linker script file here LDSCRIPT= $(STARTUPLD)/STM32F373xC.ld # C sources that can be compiled in ARM or THUMB mode depending on the global # setting. CSRC = $(STARTUPSRC) \ $(KERNSRC) \ $(PORTSRC) \ $(OSALSRC) \ $(HALSRC) \ $(PLATFORMSRC) \ $(BOARDSRC) \ $(TESTSRC) \ $(STREAMSSRC) \ $(SHELLSRC) \ usbcfg.c main.c # C++ sources that can be compiled in ARM or THUMB mode depending on the global # setting. CPPSRC = # C sources to be compiled in ARM mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. ACSRC = # C++ sources to be compiled in ARM mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. ACPPSRC = # C sources to be compiled in THUMB mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. TCSRC = # C sources to be compiled in THUMB mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. TCPPSRC = # List ASM source files here ASMSRC = ASMXSRC = $(STARTUPASM) $(PORTASM) $(OSALASM) INCDIR = $(CHIBIOS)/os/license \ $(STARTUPINC) $(KERNINC) $(PORTINC) $(OSALINC) \ $(HALINC) $(PLATFORMINC) $(BOARDINC) $(TESTINC) \ $(STREAMSINC) $(SHELLINC) # # Project, sources and paths ############################################################################## ############################################################################## # Compiler settings # MCU = cortex-m4 #TRGT = arm-elf- TRGT = arm-none-eabi- CC = $(TRGT)gcc CPPC = $(TRGT)g++ # Enable loading with g++ only if you need C++ runtime support. # NOTE: You can use C++ even without C++ support if you are careful. C++ # runtime support makes code size explode. LD = $(TRGT)gcc #LD = $(TRGT)g++ CP = $(TRGT)objcopy AS = $(TRGT)gcc -x assembler-with-cpp AR = $(TRGT)ar OD = $(TRGT)objdump SZ = $(TRGT)size HEX = $(CP) -O ihex BIN = $(CP) -O binary # ARM-specific options here AOPT = # THUMB-specific options here TOPT = -mthumb -DTHUMB # Define C warning options here CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes # Define C++ warning options here CPPWARN = -Wall -Wextra -Wundef # # Compiler settings ############################################################################## ############################################################################## # Start of user section # # List all user C define here, like -D_DEBUG=1 UDEFS = # Define ASM defines here UADEFS = # List all user directories here UINCDIR = # List the user directory to look for the libraries here ULIBDIR = # List all user libraries here ULIBS = # # End of user defines ############################################################################## RULESPATH = $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC include $(RULESPATH)/rules.mk
mabl/ChibiOS
testhal/STM32/STM32F37x/USB_CDC/Makefile
Makefile
gpl-3.0
6,386
/*------------------------------------------------------------------------- * * wparser.c * Standard interface to word parser * * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group * * * IDENTIFICATION * src/backend/tsearch/wparser.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "funcapi.h" #include "catalog/namespace.h" #include "catalog/pg_type.h" #include "commands/defrem.h" #include "tsearch/ts_cache.h" #include "tsearch/ts_utils.h" #include "utils/builtins.h" #include "utils/jsonapi.h" #include "utils/varlena.h" /******sql-level interface******/ typedef struct { int cur; LexDescr *list; } TSTokenTypeStorage; /* state for ts_headline_json_* */ typedef struct HeadlineJsonState { HeadlineParsedText *prs; TSConfigCacheEntry *cfg; TSParserCacheEntry *prsobj; TSQuery query; List *prsoptions; bool transformed; } HeadlineJsonState; static text *headline_json_value(void *_state, char *elem_value, int elem_len); static void tt_setup_firstcall(FuncCallContext *funcctx, Oid prsid) { TupleDesc tupdesc; MemoryContext oldcontext; TSTokenTypeStorage *st; TSParserCacheEntry *prs = lookup_ts_parser_cache(prsid); if (!OidIsValid(prs->lextypeOid)) elog(ERROR, "method lextype isn't defined for text search parser %u", prsid); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); st = (TSTokenTypeStorage *) palloc(sizeof(TSTokenTypeStorage)); st->cur = 0; /* lextype takes one dummy argument */ st->list = (LexDescr *) DatumGetPointer(OidFunctionCall1(prs->lextypeOid, (Datum) 0)); funcctx->user_fctx = (void *) st; tupdesc = CreateTemplateTupleDesc(3, false); TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber) 2, "alias", TEXTOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description", TEXTOID, -1, 0); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); MemoryContextSwitchTo(oldcontext); } static Datum tt_process_call(FuncCallContext *funcctx) { TSTokenTypeStorage *st; st = (TSTokenTypeStorage *) funcctx->user_fctx; if (st->list && st->list[st->cur].lexid) { Datum result; char *values[3]; char txtid[16]; HeapTuple tuple; sprintf(txtid, "%d", st->list[st->cur].lexid); values[0] = txtid; values[1] = st->list[st->cur].alias; values[2] = st->list[st->cur].descr; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = HeapTupleGetDatum(tuple); pfree(values[1]); pfree(values[2]); st->cur++; return result; } if (st->list) pfree(st->list); pfree(st); return (Datum) 0; } Datum ts_token_type_byid(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { funcctx = SRF_FIRSTCALL_INIT(); tt_setup_firstcall(funcctx, PG_GETARG_OID(0)); } funcctx = SRF_PERCALL_SETUP(); if ((result = tt_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } Datum ts_token_type_byname(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { text *prsname = PG_GETARG_TEXT_PP(0); Oid prsId; funcctx = SRF_FIRSTCALL_INIT(); prsId = get_ts_parser_oid(textToQualifiedNameList(prsname), false); tt_setup_firstcall(funcctx, prsId); } funcctx = SRF_PERCALL_SETUP(); if ((result = tt_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } typedef struct { int type; char *lexeme; } LexemeEntry; typedef struct { int cur; int len; LexemeEntry *list; } PrsStorage; static void prs_setup_firstcall(FuncCallContext *funcctx, Oid prsid, text *txt) { TupleDesc tupdesc; MemoryContext oldcontext; PrsStorage *st; TSParserCacheEntry *prs = lookup_ts_parser_cache(prsid); char *lex = NULL; int llen = 0, type = 0; void *prsdata; oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); st = (PrsStorage *) palloc(sizeof(PrsStorage)); st->cur = 0; st->len = 16; st->list = (LexemeEntry *) palloc(sizeof(LexemeEntry) * st->len); prsdata = (void *) DatumGetPointer(FunctionCall2(&prs->prsstart, PointerGetDatum(VARDATA_ANY(txt)), Int32GetDatum(VARSIZE_ANY_EXHDR(txt)))); while ((type = DatumGetInt32(FunctionCall3(&prs->prstoken, PointerGetDatum(prsdata), PointerGetDatum(&lex), PointerGetDatum(&llen)))) != 0) { if (st->cur >= st->len) { st->len = 2 * st->len; st->list = (LexemeEntry *) repalloc(st->list, sizeof(LexemeEntry) * st->len); } st->list[st->cur].lexeme = palloc(llen + 1); memcpy(st->list[st->cur].lexeme, lex, llen); st->list[st->cur].lexeme[llen] = '\0'; st->list[st->cur].type = type; st->cur++; } FunctionCall1(&prs->prsend, PointerGetDatum(prsdata)); st->len = st->cur; st->cur = 0; funcctx->user_fctx = (void *) st; tupdesc = CreateTemplateTupleDesc(2, false); TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber) 2, "token", TEXTOID, -1, 0); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); MemoryContextSwitchTo(oldcontext); } static Datum prs_process_call(FuncCallContext *funcctx) { PrsStorage *st; st = (PrsStorage *) funcctx->user_fctx; if (st->cur < st->len) { Datum result; char *values[2]; char tid[16]; HeapTuple tuple; values[0] = tid; sprintf(tid, "%d", st->list[st->cur].type); values[1] = st->list[st->cur].lexeme; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = HeapTupleGetDatum(tuple); pfree(values[1]); st->cur++; return result; } else { if (st->list) pfree(st->list); pfree(st); } return (Datum) 0; } Datum ts_parse_byid(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { text *txt = PG_GETARG_TEXT_PP(1); funcctx = SRF_FIRSTCALL_INIT(); prs_setup_firstcall(funcctx, PG_GETARG_OID(0), txt); PG_FREE_IF_COPY(txt, 1); } funcctx = SRF_PERCALL_SETUP(); if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } Datum ts_parse_byname(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { text *prsname = PG_GETARG_TEXT_PP(0); text *txt = PG_GETARG_TEXT_PP(1); Oid prsId; funcctx = SRF_FIRSTCALL_INIT(); prsId = get_ts_parser_oid(textToQualifiedNameList(prsname), false); prs_setup_firstcall(funcctx, prsId, txt); } funcctx = SRF_PERCALL_SETUP(); if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } Datum ts_headline_byid_opt(PG_FUNCTION_ARGS) { Oid tsconfig = PG_GETARG_OID(0); text *in = PG_GETARG_TEXT_PP(1); TSQuery query = PG_GETARG_TSQUERY(2); text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_PP(3) : NULL; HeadlineParsedText prs; List *prsoptions; text *out; TSConfigCacheEntry *cfg; TSParserCacheEntry *prsobj; cfg = lookup_ts_config_cache(tsconfig); prsobj = lookup_ts_parser_cache(cfg->prsId); if (!OidIsValid(prsobj->headlineOid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("text search parser does not support headline creation"))); memset(&prs, 0, sizeof(HeadlineParsedText)); prs.lenwords = 32; prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords); hlparsetext(cfg->cfgId, &prs, query, VARDATA_ANY(in), VARSIZE_ANY_EXHDR(in)); if (opt) prsoptions = deserialize_deflist(PointerGetDatum(opt)); else prsoptions = NIL; FunctionCall3(&(prsobj->prsheadline), PointerGetDatum(&prs), PointerGetDatum(prsoptions), PointerGetDatum(query)); out = generateHeadline(&prs); PG_FREE_IF_COPY(in, 1); PG_FREE_IF_COPY(query, 2); if (opt) PG_FREE_IF_COPY(opt, 3); pfree(prs.words); pfree(prs.startsel); pfree(prs.stopsel); PG_RETURN_POINTER(out); } Datum ts_headline_byid(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_byid_opt, PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); } Datum ts_headline_opt(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_jsonb_byid_opt(PG_FUNCTION_ARGS) { Oid tsconfig = PG_GETARG_OID(0); Jsonb *jb = PG_GETARG_JSONB_P(1); TSQuery query = PG_GETARG_TSQUERY(2); text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL; Jsonb *out; JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value; HeadlineParsedText prs; HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState)); memset(&prs, 0, sizeof(HeadlineParsedText)); prs.lenwords = 32; prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords); state->prs = &prs; state->cfg = lookup_ts_config_cache(tsconfig); state->prsobj = lookup_ts_parser_cache(state->cfg->prsId); state->query = query; if (opt) state->prsoptions = deserialize_deflist(PointerGetDatum(opt)); else state->prsoptions = NIL; if (!OidIsValid(state->prsobj->headlineOid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("text search parser does not support headline creation"))); out = transform_jsonb_string_values(jb, state, action); PG_FREE_IF_COPY(jb, 1); PG_FREE_IF_COPY(query, 2); if (opt) PG_FREE_IF_COPY(opt, 3); pfree(prs.words); if (state->transformed) { pfree(prs.startsel); pfree(prs.stopsel); } PG_RETURN_JSONB_P(out); } Datum ts_headline_jsonb(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_jsonb_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); } Datum ts_headline_jsonb_byid(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_jsonb_byid_opt, PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_jsonb_opt(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_jsonb_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_json_byid_opt(PG_FUNCTION_ARGS) { Oid tsconfig = PG_GETARG_OID(0); text *json = PG_GETARG_TEXT_P(1); TSQuery query = PG_GETARG_TSQUERY(2); text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL; text *out; JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value; HeadlineParsedText prs; HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState)); memset(&prs, 0, sizeof(HeadlineParsedText)); prs.lenwords = 32; prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords); state->prs = &prs; state->cfg = lookup_ts_config_cache(tsconfig); state->prsobj = lookup_ts_parser_cache(state->cfg->prsId); state->query = query; if (opt) state->prsoptions = deserialize_deflist(PointerGetDatum(opt)); else state->prsoptions = NIL; if (!OidIsValid(state->prsobj->headlineOid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("text search parser does not support headline creation"))); out = transform_json_string_values(json, state, action); PG_FREE_IF_COPY(json, 1); PG_FREE_IF_COPY(query, 2); if (opt) PG_FREE_IF_COPY(opt, 3); pfree(prs.words); if (state->transformed) { pfree(prs.startsel); pfree(prs.stopsel); } PG_RETURN_TEXT_P(out); } Datum ts_headline_json(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_json_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); } Datum ts_headline_json_byid(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_json_byid_opt, PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_json_opt(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_json_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } /* * Return headline in text from, generated from a json(b) element */ static text * headline_json_value(void *_state, char *elem_value, int elem_len) { HeadlineJsonState *state = (HeadlineJsonState *) _state; HeadlineParsedText *prs = state->prs; TSConfigCacheEntry *cfg = state->cfg; TSParserCacheEntry *prsobj = state->prsobj; TSQuery query = state->query; List *prsoptions = state->prsoptions; prs->curwords = 0; hlparsetext(cfg->cfgId, prs, query, elem_value, elem_len); FunctionCall3(&(prsobj->prsheadline), PointerGetDatum(prs), PointerGetDatum(prsoptions), PointerGetDatum(query)); state->transformed = true; return generateHeadline(prs); }
robins/postgres
src/backend/tsearch/wparser.c
C
gpl-3.0
13,513
/* * This file is part of JGCGen. * * JGCGen is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JGCGen is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with JGCGen. If not, see <http://www.gnu.org/licenses/>. */ package org.luolamies.jgcgen.text; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.luolamies.jgcgen.RenderException; public class Fonts { private final File workdir; public Fonts(File workdir) { this.workdir = workdir; } public Font get(String name) { String type; if(name.endsWith(".jhf")) type = "Hershey"; else throw new RenderException("Can't figure out font type from filename! Use $fonts.get(\"file\", \"type\")"); return get(name, type); } @SuppressWarnings("unchecked") public Font get(String name, String type) { Class<? extends Font> fclass; try { fclass = (Class<? extends Font>) Class.forName(getClass().getPackage().getName() + "." + type + "Font"); } catch (ClassNotFoundException e1) { throw new RenderException("Font type \"" + type + "\" not supported!"); } InputStream in; File file = new File(workdir, name); if(file.isFile()) { try { in = new FileInputStream(file); } catch (FileNotFoundException e) { in = null; } } else in = getClass().getResourceAsStream("/fonts/" + name); if(in==null) throw new RenderException("Can't find font: " + name); try { return fclass.getConstructor(InputStream.class).newInstance(in); } catch(Exception e) { throw new RenderException("Error while trying to construct handler for font \"" + type + "\": " + e.getMessage(), e); } finally { try { in.close(); } catch (IOException e) { } } } }
callaa/JGCGen
src/org/luolamies/jgcgen/text/Fonts.java
Java
gpl-3.0
2,230
#!/bin/bash -f # Vivado (TM) v2015.4.2 (64-bit) # # Filename : design_TEST.sh # Simulator : Cadence Incisive Enterprise Simulator # Description : Simulation script for compiling, elaborating and verifying the project source files. # The script will automatically create the design libraries sub-directories in the run # directory, add the library logical mappings in the simulator setup file, create default # 'do/prj' file, execute compilation, elaboration and simulation steps. # # Generated by Vivado on Thu Sep 01 17:23:17 +0200 2016 # IP Build 1491208 on Wed Feb 24 03:25:39 MST 2016 # # usage: design_TEST.sh [-help] # usage: design_TEST.sh [-lib_map_path] # usage: design_TEST.sh [-noclean_files] # usage: design_TEST.sh [-reset_run] # # Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the # 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the # Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch # that points to these libraries and rerun export_simulation. For more information about this switch please # type 'export_simulation -help' in the Tcl shell. # # You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this # script with the compiled library directory path or specify this path with the '-lib_map_path' switch when # executing this script. Please type 'design_TEST.sh -help' for more information. # # Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)' # # ******************************************************************************************************** # Script info echo -e "design_TEST.sh - Script generated by export_simulation (Vivado v2015.4.2 (64-bit)-id)\n" # Script usage usage() { msg="Usage: design_TEST.sh [-help]\n\ Usage: design_TEST.sh [-lib_map_path]\n\ Usage: design_TEST.sh [-reset_run]\n\ Usage: design_TEST.sh [-noclean_files]\n\n\ [-help] -- Print help information for this script\n\n\ [-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\ using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\ [-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\ from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\ -noclean_files switch.\n\n\ [-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n" echo -e $msg exit 1 } if [[ ($# == 1 ) && ($1 != "-lib_map_path" && $1 != "-noclean_files" && $1 != "-reset_run" && $1 != "-help" && $1 != "-h") ]]; then echo -e "ERROR: Unknown option specified '$1' (type \"./design_TEST.sh -help\" for more information)\n" exit 1 fi if [[ ($1 == "-help" || $1 == "-h") ]]; then usage fi # STEP: setup setup() { case $1 in "-lib_map_path" ) if [[ ($2 == "") ]]; then echo -e "ERROR: Simulation library directory path not specified (type \"./design_TEST.sh -help\" for more information)\n" exit 1 fi # precompiled simulation library directory path create_lib_mappings $2 touch hdl.var ;; "-reset_run" ) reset_run echo -e "INFO: Simulation run files deleted.\n" exit 0 ;; "-noclean_files" ) # do not remove previous data ;; * ) create_lib_mappings $2 touch hdl.var esac # Add any setup/initialization commands here:- # <user specific commands> } # Remove generated data from the previous run and re-create setup files/library mappings reset_run() { files_to_remove=(ncsim.key irun.key ncvlog.log ncvhdl.log compile.log elaborate.log simulate.log run.log waves.shm INCA_libs) for (( i=0; i<${#files_to_remove[*]}; i++ )); do file="${files_to_remove[i]}" if [[ -e $file ]]; then rm -rf $file fi done } # Main steps run() { setup $1 $2 compile elaborate simulate } # Create design library directory paths and define design library mappings in cds.lib create_lib_mappings() { libs=(xil_defaultlib lib_pkg_v1_0_2 fifo_generator_v13_0_1 lib_fifo_v1_0_4 lib_srl_fifo_v1_0_2 lib_cdc_v1_0_2 axi_datamover_v5_1_9 axi_sg_v4_1_2 axi_dma_v7_1_8 proc_sys_reset_v5_0_8 generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_7 axi_data_fifo_v2_1_6 axi_crossbar_v2_1_8 axi_protocol_converter_v2_1_7) file="cds.lib" dir="ies" if [[ -e $file ]]; then rm -f $file fi if [[ -e $dir ]]; then rm -rf $dir fi touch $file lib_map_path="<SPECIFY_COMPILED_LIB_PATH>" if [[ ($1 != "" && -e $1) ]]; then lib_map_path="$1" else echo -e "ERROR: Compiled simulation library directory path not specified or does not exist (type "./top.sh -help" for more information)\n" fi incl_ref="INCLUDE $lib_map_path/cds.lib" echo $incl_ref >> $file for (( i=0; i<${#libs[*]}; i++ )); do lib="${libs[i]}" lib_dir="$dir/$lib" if [[ ! -e $lib_dir ]]; then mkdir -p $lib_dir mapping="DEFINE $lib $dir/$lib" echo $mapping >> $file fi done } # RUN_STEP: <compile> compile() { # Directory path for design sources and include directories (if any) wrt this path ref_dir="." # Command line options opts_ver="-64bit -messages -logfile ncvlog.log -append_log" opts_vhd="-64bit -V93 -RELAX -logfile ncvhdl.log -append_log" # Compile design files ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_wr.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_rd.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_wr_4.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_rd_4.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_hp2_3.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_hp0_1.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ssw_hp.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_sparse_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_reg_map.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ocm_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_intr_wr_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_intr_rd_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_fmsw_gp.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_regc.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ocmc.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_interconnect_model.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_gen_reset.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_gen_clock.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ddrc.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_axi_slave.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_axi_master.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_afi_slave.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_processing_system7_bfm.v" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_processing_system7_0_0/sim/design_TEST_processing_system7_0_0.v" \ ncvhdl -work lib_pkg_v1_0_2 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_pkg_v1_0/hdl/src/vhdl/lib_pkg.vhd" \ ncvhdl -work fifo_generator_v13_0_1 $opts_vhd \ "$ref_dir/../../../ipstatic/fifo_generator_v13_0/simulation/fifo_generator_vhdl_beh.vhd" \ "$ref_dir/../../../ipstatic/fifo_generator_v13_0/hdl/fifo_generator_v13_0_rfs.vhd" \ ncvhdl -work lib_fifo_v1_0_4 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_fifo_v1_0/hdl/src/vhdl/async_fifo_fg.vhd" \ "$ref_dir/../../../ipstatic/lib_fifo_v1_0/hdl/src/vhdl/sync_fifo_fg.vhd" \ ncvhdl -work lib_srl_fifo_v1_0_2 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/cntr_incr_decr_addn_f.vhd" \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/dynshreg_f.vhd" \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/srl_fifo_rbu_f.vhd" \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/srl_fifo_f.vhd" \ ncvhdl -work lib_cdc_v1_0_2 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_cdc_v1_0/hdl/src/vhdl/cdc_sync.vhd" \ ncvhdl -work axi_datamover_v5_1_9 $opts_vhd \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_reset.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_afifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_sfifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_fifo.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_cmd_status.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_scc.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_strb_gen2.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_pcc.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_addr_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rdmux.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rddata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rd_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_demux.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wrdata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_skid2mm_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rd_sf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_sf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_stbs_set.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_stbs_set_nodre.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_ibttcc.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_indet_btt.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_dre_mux2_1_x_n.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_dre_mux4_1_x_n.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_dre_mux8_1_x_n.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_dre.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_dre.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_ms_strb_set.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mssai_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_slice.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_scatter.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_realign.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_omit_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_full_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_omit_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_full_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover.vhd" \ ncvhdl -work axi_sg_v4_1_2 $opts_vhd \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_pkg.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_reset.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_sfifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_afifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_fifo.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_cmd_status.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rdmux.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_addr_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rddata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rd_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_scc.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wr_demux.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_scc_wr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_skid2mm_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wrdata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wr_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_mm2s_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_s2mm_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_datamover.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_pntr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_cntrl_strm.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_queue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_noqueue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_q_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_queue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_noqueue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_q_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_intrpt.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg.vhd" \ ncvhdl -work axi_dma_v7_1_8 $opts_vhd \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_pkg.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_reset.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_rst_module.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_lite_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_register.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_register_s2mm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_reg_module.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_afifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_sofeof_gen.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_smple_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sg_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sts_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_cntrl_strm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sg_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sts_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sts_strm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_cmd_split.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma.vhd" \ ncvhdl -work xil_defaultlib $opts_vhd \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_axi_dma_0_0/sim/design_TEST_axi_dma_0_0.vhd" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_axi_dma_1_0/sim/design_TEST_axi_dma_1_0.vhd" \ ncvhdl -work proc_sys_reset_v5_0_8 $opts_vhd \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/upcnt_n.vhd" \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/sequence_psr.vhd" \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/lpf.vhd" \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/proc_sys_reset.vhd" \ ncvhdl -work xil_defaultlib $opts_vhd \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_rst_processing_system7_0_100M_0/sim/design_TEST_rst_processing_system7_0_100M_0.vhd" \ ncvlog -work generic_baseblocks_v2_1_0 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_and.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_latch_and.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_latch_or.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_or.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_command_fifo.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_mask_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_mask.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel_mask_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel_mask.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_mux_enc.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_mux.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_nto1_mux.v" \ ncvlog -work axi_infrastructure_v1_1_0 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog/axi_infrastructure_v1_1_axi2vector.v" \ "$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog/axi_infrastructure_v1_1_axic_srl_fifo.v" \ "$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog/axi_infrastructure_v1_1_vector2axi.v" \ ncvlog -work axi_register_slice_v2_1_7 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_register_slice_v2_1/hdl/verilog/axi_register_slice_v2_1_axic_register_slice.v" \ "$ref_dir/../../../ipstatic/axi_register_slice_v2_1/hdl/verilog/axi_register_slice_v2_1_axi_register_slice.v" \ ncvlog -work axi_data_fifo_v2_1_6 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axic_fifo.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_fifo_gen.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axic_srl_fifo.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axic_reg_srl_fifo.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_ndeep_srl.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axi_data_fifo.v" \ ncvlog -work axi_crossbar_v2_1_8 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_addr_arbiter_sasd.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_addr_arbiter.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_addr_decoder.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_arbiter_resp.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_crossbar_sasd.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_crossbar.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_decerr_slave.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_si_transactor.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_splitter.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_wdata_mux.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_wdata_router.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_axi_crossbar.v" \ ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_xbar_0/sim/design_TEST_xbar_0.v" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_xbar_1/sim/design_TEST_xbar_1.v" \ ncvlog -work axi_protocol_converter_v2_1_7 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_a_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_axilite_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_r_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_w_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b_downsizer.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_decerr_slave.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_simple_fifo.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_wrap_cmd.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_incr_cmd.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_wr_cmd_fsm.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_rd_cmd_fsm.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_cmd_translator.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_b_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_r_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_aw_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_ar_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_axi_protocol_converter.v" \ ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_auto_pc_0/sim/design_TEST_auto_pc_0.v" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_auto_pc_1/sim/design_TEST_auto_pc_1.v" \ ncvhdl -work xil_defaultlib $opts_vhd \ "$ref_dir/../../../bd/design_TEST/hdl/design_TEST.vhd" \ ncvlog $opts_ver -work xil_defaultlib \ "glbl.v" } # RUN_STEP: <elaborate> elaborate() { opts="-loadvpi "C:/Xilinx/Vivado/2015.4/lib/win64.o/libxil_ncsim.dll:xilinx_register_systf" -64bit -relax -access +rwc -messages -logfile elaborate.log -timescale 1ps/1ps" libs="-libname unisims_ver -libname unimacro_ver -libname secureip -libname xil_defaultlib -libname lib_pkg_v1_0_2 -libname fifo_generator_v13_0_1 -libname lib_fifo_v1_0_4 -libname lib_srl_fifo_v1_0_2 -libname lib_cdc_v1_0_2 -libname axi_datamover_v5_1_9 -libname axi_sg_v4_1_2 -libname axi_dma_v7_1_8 -libname proc_sys_reset_v5_0_8 -libname generic_baseblocks_v2_1_0 -libname axi_infrastructure_v1_1_0 -libname axi_register_slice_v2_1_7 -libname axi_data_fifo_v2_1_6 -libname axi_crossbar_v2_1_8 -libname axi_protocol_converter_v2_1_7" ncelab $opts xil_defaultlib.design_TEST xil_defaultlib.glbl $libs } # RUN_STEP: <simulate> simulate() { opts="-64bit -logfile simulate.log" ncsim $opts xil_defaultlib.design_TEST -input simulate.do } # Script usage usage() { msg="Usage: design_TEST.sh [-help]\n\ Usage: design_TEST.sh [-lib_map_path]\n\ Usage: design_TEST.sh [-reset_run]\n\ Usage: design_TEST.sh [-noclean_files]\n\n\ [-help] -- Print help information for this script\n\n\ [-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\ using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\ [-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\ from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\ -noclean_files switch.\n\n\ [-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n" echo -e $msg exit 1 } # Launch script run $1 $2
pemsac/ANN_project
ANN_project.ip_user_files/sim_scripts/design_TEST/ies/design_TEST.sh
Shell
gpl-3.0
29,644
\subsection{Instruction Working Set Signature} An instruction working set (IWS)~\cite{Dhodapkar:2002:MMH} is the set of instructions touched over a fixed interval of time. The relative working set distance between intervals $i$ and $i-1$ is defined as \begin{center} $\delta_{i,i-1} = \frac{||W_i \bigcup W_{i-1}||-||W_i \bigcap W_{i-1}||}{||W_i \bigcup W_{i-1}||}$ \end{center} where $W_i$ is the working set for interval $i$. A working set signature is a lossy-compressed representation of a working set. The program counter is sampled over a fixed interval of instructions. A hashing function is applied to the sample to set a bit in an $n$-bit vector, which represents the signature (See Figure~\ref{fig:signature}). Phase changes are detected by computing the relative signature distance between intervals and comparing the distance against some pre-determined threshold. The hardware complexity of this technique is dependent on the working set size. \begin{figure}[htbp] \begin{center} \includegraphics[width=0.60\columnwidth]{figs/workingsetsignature} \end{center} \caption{Generating the working set signature.} \label{fig:signature} \end{figure}
arcade-lab/uarch-phases
doc/paper/iws.tex
TeX
gpl-3.0
1,170
// -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et: // $Id$ /* MetaTweet * Hub system for micro-blog communication services * SqlServerStorage * MetaTweet Storage module which is provided by Microsoft SQL Server RDBMS. * Part of MetaTweet * Copyright © 2008-2011 Takeshi KIRIYA (aka takeshik) <[email protected]> * All rights reserved. * * This file is part of SqlServerStorage. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>, * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Data.EntityClient; using System.Data.Objects; using System.Reflection; namespace XSpect.MetaTweet.Objects { public class StorageObjectContext : ObjectContext { public const String ContainerName = "StorageObjectContext"; private ObjectSet<Account> _accounts; private ObjectSet<Activity> _activities; private ObjectSet<Advertisement> _advertisements; public StorageObjectContext(String connectionString) : base(connectionString, ContainerName) { this.ContextOptions.LazyLoadingEnabled = false; this.ContextOptions.ProxyCreationEnabled = false; } public StorageObjectContext(EntityConnection connection) : base(connection, ContainerName) { this.ContextOptions.LazyLoadingEnabled = false; this.ContextOptions.ProxyCreationEnabled = false; } public ObjectSet<Account> Accounts { get { return this._accounts ?? (this._accounts = this.CreateObjectSet<Account>("Accounts")); } } public ObjectSet<Activity> Activities { get { return this._activities ?? (this._activities = this.CreateObjectSet<Activity>("Activities")); } } public ObjectSet<Advertisement> Advertisements { get { return this._advertisements ?? (this._advertisements = this.CreateObjectSet<Advertisement>("Advertisements")); } } public Boolean IsDisposed { get { // HACK: Depends on internal structure, accessing non-public field return typeof(ObjectContext) .GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(this) == null; } } public ObjectSet<TObject> GetObjectSet<TObject>() where TObject : StorageObject { return (ObjectSet<TObject>) (typeof(TObject) == typeof(Account) ? (Object) this.Accounts : typeof(TObject) == typeof(Activity) ? (Object) this.Activities : this.Advertisements ); } public String GetEntitySetName<TObject>() where TObject : StorageObject { return typeof(TObject) == typeof(Account) ? ContainerName + ".Accounts" : typeof(TObject) == typeof(Activity) ? ContainerName + ".Activities" : ContainerName + ".Advertisements"; } public String GetEntitySetName(StorageObject obj) { return obj is Account ? ContainerName + ".Accounts" : obj is Activity ? ContainerName + ".Activities" : ContainerName + ".Advertisements"; } } }
takeshik/metatweet-old
SqlServerStorage/StorageObjectContext.cs
C#
gpl-3.0
4,365
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qpieseries.cpp --> <title>PieSeries QML Type | Qt Charts 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtcharts-index.html">Qt Charts</a></td><td ><a href="qtcharts-qmlmodule.html">QML Types</a></td><td >PieSeries QML Type</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#properties">Properties</a></li> <li class="level1"><a href="#signals">Signals</a></li> <li class="level1"><a href="#methods">Methods</a></li> <li class="level1"><a href="#details">Detailed Description</a></li> </ul> </div> <div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">PieSeries QML Type</h1> <span class="subtitle"></span> <!-- $$$PieSeries-brief --> <p>The <a href="qml-qtcharts-pieseries.html">PieSeries</a> type is used for making pie charts. <a href="#details">More...</a></p> <!-- @@@PieSeries --> <div class="table"><table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> Import Statement:</td><td class="memItemRight bottomAlign"> import QtCharts 2.1</td></tr><tr><td class="memItemLeft rightAlign topAlign"> Instantiates:</td><td class="memItemRight bottomAlign"> <a href="qml-qtcharts-pieseries.html"><a href="qpieseries.html">QPieSeries</a></td></tr><tr><td class="memItemLeft rightAlign topAlign"> Inherits:</td><td class="memItemRight bottomAlign"> <p><a href="qml-qtcharts-abstractseries.html">AbstractSeries</a></p> </td></tr></table></div><ul> <li><a href="qml-qtcharts-pieseries-members.html">List of all members, including inherited members</a></li> </ul> <a name="properties"></a> <h2 id="properties">Properties</h2> <ul> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#count-prop">count</a></b></b> : int</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#endAngle-prop">endAngle</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#holeSize-prop">holeSize</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#horizontalPosition-prop">horizontalPosition</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#size-prop">size</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#startAngle-prop">startAngle</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#sum-prop">sum</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#verticalPosition-prop">verticalPosition</a></b></b> : real</li> </ul> <a name="signals"></a> <h2 id="signals">Signals</h2> <ul> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onAdded-signal">onAdded</a></b></b>(list&lt;PieSlice&gt; <i>slices</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onClicked-signal">onClicked</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onCountChanged-signal">onCountChanged</a></b></b>()</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onDoubleClicked-signal">onDoubleClicked</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onHovered-signal">onHovered</a></b></b>(PieSlice <i>slice</i>, bool <i>state</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onPressed-signal">onPressed</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onReleased-signal">onReleased</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onRemoved-signal">onRemoved</a></b></b>(list&lt;PieSlice&gt; <i>slices</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onSliceAdded-signal">onSliceAdded</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onSliceRemoved-signal">onSliceRemoved</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onSumChanged-signal">onSumChanged</a></b></b>()</li> </ul> <a name="methods"></a> <h2 id="methods">Methods</h2> <ul> <li class="fn">PieSlice <b><b><a href="qml-qtcharts-pieseries.html#append-method">append</a></b></b>(string <i>label</i>, real <i>value</i>)</li> <li class="fn">PieSlice <b><b><a href="qml-qtcharts-pieseries.html#at-method">at</a></b></b>(int <i>index</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#clear-method">clear</a></b></b>()</li> <li class="fn">PieSlice <b><b><a href="qml-qtcharts-pieseries.html#find-method">find</a></b></b>(string <i>label</i>)</li> <li class="fn">bool <b><b><a href="qml-qtcharts-pieseries.html#remove-method">remove</a></b></b>(PieSlice <i>slice</i>)</li> </ul> <!-- $$$PieSeries-description --> <a name="details"></a> <h2 id="details">Detailed Description</h2> </p> <p>The following QML shows how to create a simple pie chart.</p> <pre class="qml"> <span class="type"><a href="qml-qtcharts-chartview.html">ChartView</a></span> { <span class="name">id</span>: <span class="name">chart</span> <span class="name">title</span>: <span class="string">&quot;Top-5 car brand shares in Finland&quot;</span> <span class="name">anchors</span>.fill: <span class="name">parent</span> <span class="name">legend</span>.alignment: <span class="name">Qt</span>.<span class="name">AlignBottom</span> <span class="name">antialiasing</span>: <span class="number">true</span> <span class="type"><a href="qml-qtcharts-pieseries.html">PieSeries</a></span> { <span class="name">id</span>: <span class="name">pieSeries</span> <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Volkswagen&quot;</span>; <span class="name">value</span>: <span class="number">13.5</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Toyota&quot;</span>; <span class="name">value</span>: <span class="number">10.9</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Ford&quot;</span>; <span class="name">value</span>: <span class="number">8.6</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Skoda&quot;</span>; <span class="name">value</span>: <span class="number">8.2</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Volvo&quot;</span>; <span class="name">value</span>: <span class="number">6.8</span> } } } <span class="name">Component</span>.onCompleted: { <span class="comment">// You can also manipulate slices dynamically</span> <span class="name">othersSlice</span> <span class="operator">=</span> <span class="name">pieSeries</span>.<span class="name">append</span>(<span class="string">&quot;Others&quot;</span>, <span class="number">52.0</span>); <span class="name">pieSeries</span>.<span class="name">find</span>(<span class="string">&quot;Volkswagen&quot;</span>).<span class="name">exploded</span> <span class="operator">=</span> <span class="number">true</span>; } </pre> <div style="float: left; margin-right: 2em"><p class="centerAlign"><img src="images/examples_qmlchart1.png" alt="" /></p></div><br style="clear: both" /><!-- @@@PieSeries --> <h2>Property Documentation</h2> <!-- $$$count --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="count-prop"> <td class="tblQmlPropNode"><p> <a name="count-prop"></a><span class="name">count</span> : <span class="type">int</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Number of slices in the series.</p> </div></div><!-- @@@count --> <br/> <!-- $$$endAngle --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="endAngle-prop"> <td class="tblQmlPropNode"><p> <a name="endAngle-prop"></a><span class="name">endAngle</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the ending angle of the pie.</p> <p>Full pie is 360 degrees where 0 degrees is at 12 a'clock.</p> <p>Default is value is 360.</p> </div></div><!-- @@@endAngle --> <br/> <!-- $$$holeSize --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="holeSize-prop"> <td class="tblQmlPropNode"><p> <a name="holeSize-prop"></a><span class="name">holeSize</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the donut hole size.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the minimum size (full pie drawn, without any hole inside).</li> <li>1.0 is the maximum size that can fit the chart. (donut has no width)</li> </ul> <p>When setting this property the size property is adjusted if necessary, to ensure that the inner size is not greater than the outer size.</p> <p>Default value is 0.0&#x2e;</p> </div></div><!-- @@@holeSize --> <br/> <!-- $$$horizontalPosition --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="horizontalPosition-prop"> <td class="tblQmlPropNode"><p> <a name="horizontalPosition-prop"></a><span class="name">horizontalPosition</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the horizontal position of the pie.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the absolute left.</li> <li>1.0 is the absolute right.</li> </ul> <p>Default value is 0.5 (center).</p> <p><b>See also </b><a href="qml-qtcharts-pieseries.html#verticalPosition-prop">verticalPosition</a>.</p> </div></div><!-- @@@horizontalPosition --> <br/> <!-- $$$size --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="size-prop"> <td class="tblQmlPropNode"><p> <a name="size-prop"></a><span class="name">size</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the pie size.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the minimum size (pie not drawn).</li> <li>1.0 is the maximum size that can fit the chart.</li> </ul> <p>Default value is 0.7&#x2e;</p> </div></div><!-- @@@size --> <br/> <!-- $$$startAngle --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="startAngle-prop"> <td class="tblQmlPropNode"><p> <a name="startAngle-prop"></a><span class="name">startAngle</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the starting angle of the pie.</p> <p>Full pie is 360 degrees where 0 degrees is at 12 a'clock.</p> <p>Default is value is 0.</p> </div></div><!-- @@@startAngle --> <br/> <!-- $$$sum --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="sum-prop"> <td class="tblQmlPropNode"><p> <a name="sum-prop"></a><span class="name">sum</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Sum of all slices.</p> <p>The series keeps track of the sum of all slices it holds.</p> </div></div><!-- @@@sum --> <br/> <!-- $$$verticalPosition --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="verticalPosition-prop"> <td class="tblQmlPropNode"><p> <a name="verticalPosition-prop"></a><span class="name">verticalPosition</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the vertical position of the pie.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the absolute top.</li> <li>1.0 is the absolute bottom.</li> </ul> <p>Default value is 0.5 (center).</p> <p><b>See also </b><a href="qml-qtcharts-pieseries.html#horizontalPosition-prop">horizontalPosition</a>.</p> </div></div><!-- @@@verticalPosition --> <br/> <h2>Signal Documentation</h2> <!-- $$$onAdded --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onAdded-signal"> <td class="tblQmlFuncNode"><p> <a name="onAdded-signal"></a><span class="name">onAdded</span>(<span class="type">list</span>&lt;<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span>&gt; <i>slices</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slices</i> have been added to the series.</p> </div></div><!-- @@@onAdded --> <br/> <!-- $$$onClicked --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onClicked-signal"> <td class="tblQmlFuncNode"><p> <a name="onClicked-signal"></a><span class="name">onClicked</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been clicked.</p> </div></div><!-- @@@onClicked --> <br/> <!-- $$$onCountChanged --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onCountChanged-signal"> <td class="tblQmlFuncNode"><p> <a name="onCountChanged-signal"></a><span class="name">onCountChanged</span>()</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when the slice count has changed.</p> </div></div><!-- @@@onCountChanged --> <br/> <!-- $$$onDoubleClicked --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onDoubleClicked-signal"> <td class="tblQmlFuncNode"><p> <a name="onDoubleClicked-signal"></a><span class="name">onDoubleClicked</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been doubleClicked.</p> </div></div><!-- @@@onDoubleClicked --> <br/> <!-- $$$onHovered --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onHovered-signal"> <td class="tblQmlFuncNode"><p> <a name="onHovered-signal"></a><span class="name">onHovered</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>, <span class="type">bool</span> <i>state</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when user has hovered over or away from the <i>slice</i>. <i>state</i> is true when user has hovered over the slice and false when hover has moved away from the slice.</p> </div></div><!-- @@@onHovered --> <br/> <!-- $$$onPressed --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onPressed-signal"> <td class="tblQmlFuncNode"><p> <a name="onPressed-signal"></a><span class="name">onPressed</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been pressed.</p> </div></div><!-- @@@onPressed --> <br/> <!-- $$$onReleased --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onReleased-signal"> <td class="tblQmlFuncNode"><p> <a name="onReleased-signal"></a><span class="name">onReleased</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been released.</p> </div></div><!-- @@@onReleased --> <br/> <!-- $$$onRemoved --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onRemoved-signal"> <td class="tblQmlFuncNode"><p> <a name="onRemoved-signal"></a><span class="name">onRemoved</span>(<span class="type">list</span>&lt;<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span>&gt; <i>slices</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slices</i> have been removed from the series.</p> </div></div><!-- @@@onRemoved --> <br/> <!-- $$$onSliceAdded --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onSliceAdded-signal"> <td class="tblQmlFuncNode"><p> <a name="onSliceAdded-signal"></a><span class="name">onSliceAdded</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slice</i> has been added to the series.</p> </div></div><!-- @@@onSliceAdded --> <br/> <!-- $$$onSliceRemoved --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onSliceRemoved-signal"> <td class="tblQmlFuncNode"><p> <a name="onSliceRemoved-signal"></a><span class="name">onSliceRemoved</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slice</i> has been removed from the series.</p> </div></div><!-- @@@onSliceRemoved --> <br/> <!-- $$$onSumChanged --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onSumChanged-signal"> <td class="tblQmlFuncNode"><p> <a name="onSumChanged-signal"></a><span class="name">onSumChanged</span>()</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when the sum of all slices has changed. This may happen for example if you add or remove slices, or if you change value of a slice.</p> </div></div><!-- @@@onSumChanged --> <br/> <h2>Method Documentation</h2> <!-- $$$append --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="append-method"> <td class="tblQmlFuncNode"><p> <a name="append-method"></a><span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <span class="name">append</span>(<span class="type">string</span> <i>label</i>, <span class="type">real</span> <i>value</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Adds a new slice with <i>label</i> and <i>value</i> to the pie.</p> </div></div><!-- @@@append --> <br/> <!-- $$$at --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="at-method"> <td class="tblQmlFuncNode"><p> <a name="at-method"></a><span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <span class="name">at</span>(<span class="type">int</span> <i>index</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Returns slice at <i>index</i>. Returns null if the index is not valid.</p> </div></div><!-- @@@at --> <br/> <!-- $$$clear --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="clear-method"> <td class="tblQmlFuncNode"><p> <a name="clear-method"></a><span class="name">clear</span>()</p></td></tr> </table></div> </div><div class="qmldoc"><p>Removes all slices from the pie.</p> </div></div><!-- @@@clear --> <br/> <!-- $$$find --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="find-method"> <td class="tblQmlFuncNode"><p> <a name="find-method"></a><span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <span class="name">find</span>(<span class="type">string</span> <i>label</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Returns the first slice with <i>label</i>. Returns null if the index is not valid.</p> </div></div><!-- @@@find --> <br/> <!-- $$$remove --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="remove-method"> <td class="tblQmlFuncNode"><p> <a name="remove-method"></a><span class="type">bool</span> <span class="name">remove</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Removes the <i>slice</i> from the pie. Returns true if the removal was successful, false otherwise.</p> </div></div><!-- @@@remove --> <br/> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
angeloprudentino/QtNets
Doc/qtcharts/qml-qtcharts-pieseries.html
HTML
gpl-3.0
22,505
# -*- coding: utf-8 -*- """proyectoP4 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url, patterns from django.contrib import admin from Workinout import views from django.conf import settings urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^Workinout/', include('Workinout.urls')), # ADD THIS NEW TUPLE!media/(?P<path>.*) ] if settings.DEBUG: urlpatterns += patterns( 'django.views.static', (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}), ) else: urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}), )
jesmorc/Workinout
proyectoP4/urls.py
Python
gpl-3.0
1,273
#region using directives using POGOProtos.Enums; using POGOProtos.Settings.Master.Pokemon; #endregion namespace PoGo.PokeMobBot.Logic.Event.Pokemon { public class BaseNewPokemonEvent : IEvent { public int Cp; public ulong Uid; public PokemonId Id; public double Perfection; public PokemonFamilyId Family; public int Candy; public double Level; public PokemonMove Move1; public PokemonMove Move2; public PokemonType Type1; public PokemonType Type2; public StatsAttributes Stats; public int MaxCp; public int Stamina; public int IvSta; public int PossibleCp; public int CandyToEvolve; public int IvAtk; public int IvDef; public float Cpm; public float Weight; public int StaminaMax; public PokemonId[] Evolutions; public double Latitude; public double Longitude; } }
Lunat1q/Catchem-PoGo
Source/PoGo.PokeMobBot.Logic/Event/Pokemon/BaseNewPokemonEvent.cs
C#
gpl-3.0
982
#!/usr/bin/python # This programs is intended to manage patches and apply them automatically # through email in an automated fashion. # # Copyright (C) 2008 Imran M Yousuf ([email protected]) # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import poplib, email, re, sys, xmlConfigs, utils; class ReferenceNode : def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")): self.node = node self.children = dict(children) self.references = references[:] self.slotted = slotted self.emailMessage = emailMessage def get_node(self): return self.node def get_children(self): return self.children def set_node(self, node): self.node = node def set_children(self, children): self.children = children def get_references(self): return self.references def is_slotted(self): return self.slotted def set_slotted(self, slotted): self.slotted = slotted def get_message(self): return self.emailMessage def __repr__(self): return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n" def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode): for reference in referencesToCheck[:] : if reference in referenceNodeNow.get_children() : referencesToCheck.remove(reference) return patchMessageReferenceNode[reference] if len(referencesToCheck) == 0 : referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction def makeChildren(patchMessageReferenceNode) : ref_keys = patchMessageReferenceNode.keys() ref_keys.sort() for messageId in ref_keys: referenceNode = patchMessageReferenceNode[messageId] utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node()) referenceIds = referenceNode.get_references() referenceIdsClone = referenceIds[:] utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone) if len(referenceIds) > 0 : nextNode = patchMessageReferenceNode[referenceIdsClone[0]] referenceIdsClone.remove(referenceIdsClone[0]) while nextNode != None : utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node()) utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node()) utils.verboseOutput(verbose, "REF: ", referenceIdsClone) nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode) if __name__ == "__main__": arguments = sys.argv verbose = "false" pseudoArgs = arguments[:] while len(pseudoArgs) > 1 : argument = pseudoArgs[1] if argument == "-v" or argument == "--verbose" : verbose = "true" pseudoArgs.remove(argument) utils.verboseOutput(verbose, "Checking POP3 for gmail") try: emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml") myPop = emailConfig.get_pop3_connection() numMessages = len(myPop.list()[1]) patchMessages = dict() for i in range(numMessages): utils.verboseOutput(verbose, "Index: ", i) totalContent = "" for content in myPop.retr(i+1)[1]: totalContent += content + '\n' msg = email.message_from_string(totalContent) if 'subject' in msg : subject = msg['subject'] subjectPattern = "^\[.*PATCH.*\].+" subjectMatch = re.match(subjectPattern, subject) utils.verboseOutput(verbose, "Checking subject: ", subject) if subjectMatch == None : continue else : continue messageId = "" if 'message-id' in msg: messageId = re.search("<(.*)>", msg['message-id']).group(1) utils.verboseOutput(verbose, 'Message-ID:', messageId) referenceIds = [] if 'references' in msg: references = msg['references'] referenceIds = re.findall("<(.*)>", references) utils.verboseOutput(verbose, "References: ", referenceIds) currentNode = ReferenceNode(messageId, msg, referenceIds) patchMessages[messageId] = currentNode currentNode.set_slotted(bool("false")) utils.verboseOutput(verbose, "**************Make Children**************") makeChildren(patchMessages) utils.verboseOutput(verbose, "--------------RESULT--------------") utils.verboseOutput(verbose, patchMessages) except: utils.verboseOutput(verbose, "Error: ", sys.exc_info())
imyousuf/smart-patcher
src/smart-patcher.py
Python
gpl-3.0
5,526
/* LICENSE ------- Copyright (C) 2007 Ray Molenkamp This source code is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this source code or the software it produces. Permission is granted to anyone to use this source code for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. */ // modified for NAudio // milligan22963 - updated to include audio session manager using System; using NAudio.CoreAudioApi.Interfaces; using System.Runtime.InteropServices; namespace NAudio.CoreAudioApi { /// <summary> /// MM Device /// </summary> public class MMDevice : IDisposable { #region Variables private readonly IMMDevice deviceInterface; private PropertyStore propertyStore; private AudioMeterInformation audioMeterInformation; private AudioEndpointVolume audioEndpointVolume; private AudioSessionManager audioSessionManager; #endregion #region Guids private static Guid IID_IAudioMeterInformation = new Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064"); private static Guid IID_IAudioEndpointVolume = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A"); private static Guid IID_IAudioClient = new Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"); private static Guid IDD_IAudioSessionManager = new Guid("BFA971F1-4D5E-40BB-935E-967039BFBEE4"); #endregion #region Init /// <summary> /// Initializes the device's property store. /// </summary> /// <param name="stgmAccess">The storage-access mode to open store for.</param> /// <remarks>Administrative client is required for Write and ReadWrite modes.</remarks> public void GetPropertyInformation(StorageAccessMode stgmAccess = StorageAccessMode.Read) { IPropertyStore propstore; Marshal.ThrowExceptionForHR(deviceInterface.OpenPropertyStore(stgmAccess, out propstore)); propertyStore = new PropertyStore(propstore); } private AudioClient GetAudioClient() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioClient, ClsCtx.ALL, IntPtr.Zero, out result)); return new AudioClient(result as IAudioClient); } private void GetAudioMeterInformation() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioMeterInformation, ClsCtx.ALL, IntPtr.Zero, out result)); audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation); } private void GetAudioEndpointVolume() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioEndpointVolume, ClsCtx.ALL, IntPtr.Zero, out result)); audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume); } private void GetAudioSessionManager() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IDD_IAudioSessionManager, ClsCtx.ALL, IntPtr.Zero, out result)); audioSessionManager = new AudioSessionManager(result as IAudioSessionManager); } #endregion #region Properties /// <summary> /// Audio Client /// </summary> public AudioClient AudioClient { get { // now makes a new one each call to allow caller to manage when to dispose // n.b. should probably not be a property anymore return GetAudioClient(); } } /// <summary> /// Audio Meter Information /// </summary> public AudioMeterInformation AudioMeterInformation { get { if (audioMeterInformation == null) GetAudioMeterInformation(); return audioMeterInformation; } } /// <summary> /// Audio Endpoint Volume /// </summary> public AudioEndpointVolume AudioEndpointVolume { get { if (audioEndpointVolume == null) GetAudioEndpointVolume(); return audioEndpointVolume; } } /// <summary> /// AudioSessionManager instance /// </summary> public AudioSessionManager AudioSessionManager { get { if (audioSessionManager == null) { GetAudioSessionManager(); } return audioSessionManager; } } /// <summary> /// Properties /// </summary> public PropertyStore Properties { get { if (propertyStore == null) GetPropertyInformation(); return propertyStore; } } /// <summary> /// Friendly name for the endpoint /// </summary> public string FriendlyName { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_Device_FriendlyName)) { return (string) propertyStore[PropertyKeys.PKEY_Device_FriendlyName].Value; } else return "Unknown"; } } /// <summary> /// Friendly name of device /// </summary> public string DeviceFriendlyName { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_DeviceInterface_FriendlyName)) { return (string) propertyStore[PropertyKeys.PKEY_DeviceInterface_FriendlyName].Value; } else { return "Unknown"; } } } /// <summary> /// Icon path of device /// </summary> public string IconPath { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_Device_IconPath)) { return (string) propertyStore[PropertyKeys.PKEY_Device_IconPath].Value; } else return "Unknown"; } } /// <summary> /// Device ID /// </summary> public string ID { get { string result; Marshal.ThrowExceptionForHR(deviceInterface.GetId(out result)); return result; } } /// <summary> /// Data Flow /// </summary> public DataFlow DataFlow { get { DataFlow result; var ep = deviceInterface as IMMEndpoint; ep.GetDataFlow(out result); return result; } } /// <summary> /// Device State /// </summary> public DeviceState State { get { DeviceState result; Marshal.ThrowExceptionForHR(deviceInterface.GetState(out result)); return result; } } #endregion #region Constructor internal MMDevice(IMMDevice realDevice) { deviceInterface = realDevice; } #endregion /// <summary> /// To string /// </summary> public override string ToString() { return FriendlyName; } /// <summary> /// Dispose /// </summary> public void Dispose() { this.audioEndpointVolume?.Dispose(); this.audioSessionManager?.Dispose(); GC.SuppressFinalize(this); } /// <summary> /// Finalizer /// </summary> ~MMDevice() { Dispose(); } } }
ciribob/DCS-SimpleRadioStandalone
NAudio/CoreAudioApi/MMDevice.cs
C#
gpl-3.0
9,240
// // MIT License // // Copyright (c) Deif Lou // // 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. // #include <opencv2/imgproc.hpp> #include <vector> #include "filter.h" #include "filterwidget.h" #include <imgproc/types.h> #include <imgproc/thresholding.h> #include <imgproc/util.h> Filter::Filter() : mThresholdMode(0), mColorMode(0) { for (int i = 0; i < 5; i++) mAffectedChannel[i] = false; } Filter::~Filter() { } ImageFilter *Filter::clone() { Filter * f = new Filter(); f->mThresholdMode = mThresholdMode; f->mColorMode = mColorMode; for (int i = 0; i < 5; i++) f->mAffectedChannel[i] = mAffectedChannel[i]; return f; } extern "C" QHash<QString, QString> getIBPPluginInfo(); QHash<QString, QString> Filter::info() { return getIBPPluginInfo(); } QImage Filter::process(const QImage &inputImage) { if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32) return inputImage; QImage i = inputImage.copy(); cv::Mat dstMat(i.height(), i.width(), CV_8UC4, i.bits(), i.bytesPerLine()); const int radius = 10; const int windowSize = radius * 2 + 1; const double k = .05; if (mColorMode == 0) { if (!mAffectedChannel[0] && !mAffectedChannel[4]) return i; if (mAffectedChannel[0]) { register BGRA * bitsSrc = (BGRA *)inputImage.bits(); register BGRA * bitsDst = (BGRA *)i.bits(); register int totalPixels = i.width() * i.height(); while (totalPixels--) { bitsDst->b = IBP_pixelIntensity4(bitsSrc->r, bitsSrc->g, bitsSrc->b); bitsSrc++; bitsDst++; } } cv::Mat mSrcGray, mSrcAlpha; if (mAffectedChannel[0]) { mSrcGray = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 0,0 }; cv::mixChannels(&dstMat, 1, &mSrcGray, 1, from_to, 1); } if (mAffectedChannel[4]) { mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 3,0 }; cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1); } if (mThresholdMode == 0) { if (mAffectedChannel[0]) cv::threshold(mSrcGray, mSrcGray, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[4]) cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); } else { if (mAffectedChannel[0]) adaptiveThresholdIntegral(mSrcGray, mSrcGray, windowSize, k); if (mAffectedChannel[4]) adaptiveThresholdIntegral(mSrcAlpha, mSrcAlpha, windowSize, k); } if (mAffectedChannel[0]) { int from_to[] = { 0,0, 0,1, 0,2 }; cv::mixChannels(&mSrcGray, 1, &dstMat, 1, from_to, 3); } if (mAffectedChannel[4]) { int from_to[] = { 0,3 }; cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1); } } else { if (!mAffectedChannel[1] && !mAffectedChannel[2] && !mAffectedChannel[3] && !mAffectedChannel[4]) return i; cv::Mat mSrcRed, mSrcGreen, mSrcBlue, mSrcAlpha; if (mAffectedChannel[1]) { mSrcBlue = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 0,0 }; cv::mixChannels(&dstMat, 1, &mSrcBlue, 1, from_to, 1); } if (mAffectedChannel[2]) { mSrcGreen = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 1,0 }; cv::mixChannels(&dstMat, 1, &mSrcGreen, 1, from_to, 1); } if (mAffectedChannel[3]) { mSrcRed = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 2,0 }; cv::mixChannels(&dstMat, 1, &mSrcRed, 1, from_to, 1); } if (mAffectedChannel[4]) { mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 3,0 }; cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1); } if (mThresholdMode == 0) { if (mAffectedChannel[1]) cv::threshold(mSrcBlue, mSrcBlue, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[2]) cv::threshold(mSrcGreen, mSrcGreen, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[3]) cv::threshold(mSrcRed, mSrcRed, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[4]) cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); } else { if (mAffectedChannel[1]) adaptiveThresholdIntegral(mSrcBlue, mSrcBlue, windowSize, k); if (mAffectedChannel[2]) adaptiveThresholdIntegral(mSrcGreen, mSrcGreen, windowSize, k); if (mAffectedChannel[3]) adaptiveThresholdIntegral(mSrcRed, mSrcRed, windowSize, k); if (mAffectedChannel[4]) adaptiveThresholdIntegral(mSrcAlpha, mSrcAlpha, windowSize, k); } if (mAffectedChannel[1]) { int from_to[] = { 0,0 }; cv::mixChannels(&mSrcBlue, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[2]) { int from_to[] = { 0,1 }; cv::mixChannels(&mSrcGreen, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[3]) { int from_to[] = { 0,2 }; cv::mixChannels(&mSrcRed, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[4]) { int from_to[] = { 0,3 }; cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1); } } return i; } bool Filter::loadParameters(QSettings &s) { QString thresholdModeStr, colorModeStr, affectedChannelStr; int thresholdMode, colorMode; QStringList affectedChannelList; bool affectedChannel[5] = { false }; thresholdModeStr = s.value("thresholdmode", "global").toString(); if (thresholdModeStr == "global") thresholdMode = 0; else if (thresholdModeStr == "local") thresholdMode = 1; else return false; colorModeStr = s.value("colormode", "luma").toString(); if (colorModeStr == "luma") colorMode = 0; else if (colorModeStr == "rgb") colorMode = 1; else return false; affectedChannelStr = s.value("affectedchannels", "").toString(); affectedChannelList = affectedChannelStr.split(" ", QString::SkipEmptyParts); for (int i = 0; i < affectedChannelList.size(); i++) { affectedChannelStr = affectedChannelList.at(i); if (affectedChannelList.at(i) == "luma") affectedChannel[0] = true; else if (affectedChannelList.at(i) == "red") affectedChannel[1] = true; else if (affectedChannelList.at(i) == "green") affectedChannel[2] = true; else if (affectedChannelList.at(i) == "blue") affectedChannel[3] = true; else if (affectedChannelList.at(i) == "alpha") affectedChannel[4] = true; else return false; } setThresholdMode(thresholdMode); setColorMode(colorMode); for (int i = 0; i < 5; i++) setAffectedChannel(i, affectedChannel[i]); return true; } bool Filter::saveParameters(QSettings &s) { s.setValue("thresholdmode", mThresholdMode == 0 ? "global" : "local"); s.setValue("colormode", mColorMode == 0 ? "luma" : "rgb"); QStringList affectedChannelList; if (mAffectedChannel[0]) affectedChannelList.append("luma"); if (mAffectedChannel[1]) affectedChannelList.append("red"); if (mAffectedChannel[2]) affectedChannelList.append("green"); if (mAffectedChannel[3]) affectedChannelList.append("blue"); if (mAffectedChannel[4]) affectedChannelList.append("alpha"); s.setValue("affectedchannels", affectedChannelList.join(" ")); return true; } QWidget *Filter::widget(QWidget *parent) { FilterWidget * fw = new FilterWidget(parent); fw->setThresholdMode(mThresholdMode); fw->setColorMode(mColorMode); for (int i = 0; i < 5; i++) fw->setAffectedChannel(i, mAffectedChannel[i]); connect(this, SIGNAL(thresholdModeChanged(int)), fw, SLOT(setThresholdMode(int))); connect(this, SIGNAL(colorModeChanged(int)), fw, SLOT(setColorMode(int))); connect(this, SIGNAL(affectedChannelChanged(int,bool)), fw, SLOT(setAffectedChannel(int,bool))); connect(fw, SIGNAL(thresholdModeChanged(int)), this, SLOT(setThresholdMode(int))); connect(fw, SIGNAL(colorModeChanged(int)), this, SLOT(setColorMode(int))); connect(fw, SIGNAL(affectedChannelChanged(int,bool)), this, SLOT(setAffectedChannel(int,bool))); return fw; } void Filter::setThresholdMode(int m) { if (m == mThresholdMode) return; mThresholdMode = m; emit thresholdModeChanged(m); emit parametersChanged(); } void Filter::setColorMode(int m) { if (m == mColorMode) return; mColorMode = m; emit colorModeChanged(m); emit parametersChanged(); } void Filter::setAffectedChannel(int c, bool a) { if (a == mAffectedChannel[c]) return; mAffectedChannel[c] = a; emit affectedChannelChanged(c, a); emit parametersChanged(); }
DeifLou/anitools
src/plugins/imagefilter_autothreshold/filter.cpp
C++
gpl-3.0
10,641
<!DOCTYPE html> <html> <head> <title>SenseNet : modul Senzory</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="./SenseNet_Files/over.css"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="./SenseNet_Files/font-awesome.min.css"> <link href='http://fonts.googleapis.com/css?family=Arvo' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'> <link rel="icon" href="./SenseNet_Files/favicon.ico"> <meta name="author" content="labka.cz" /> <meta name="description" content="SenseNet platform which is able to measure, parse, and predict data about air polution in industrial region Ostrava" /> <meta name="keywords" content="SenseNet, SensoricNet, Sense Net, Sensoric Net, AI, platform, prediction, parser, neural network, hackerspace, labka.cz, labka, ostrava, hackerspaces, polution, air, environmental, environment"/> </head> <body> <!-- Imported floating menu --> <div class="obal"> <div class="menu"> <iframe src="menu.html" seamless></iframe> </div> </div> <div class="celek"> <img class="obrR" src="./SenseNet_Files/pavel_s.png" width="350px"> <h2>Modul NET : infrastruktura </h2> <div> Mezi moduly Smysly [Sense] a Mozek [Brain] musí samozřejmě existovat nějaké spojení, tak jako jsou jím v lidském těle nervy.br /> V našem případě je takových spojení potřeba několik. Budou se budou vzájemně překrývat, protože komunikace je zásadní pro každý projekt a proto je potřebné mít oněch pomyslných nervových soustav několik a na několika různých vrstvách.<br /> <br /> Cílem projektu je vytvoření rozhraní mezi senzory a servery, na kterých se budou data zpracovávat, a to tak, aby bylo možné projekt zveřejnit jak pod OpenSource licencemi, jako kompletní, preprodukovatelné řešení, tak aby na druhou stranu bylo možné enterprise nasazení za pomoci patentovaných technologií a garantovaných vysílacích pásem.<br /> <h3>NB-IoT</h3> NB-IoT je experimentální standardizovaná techologie bezdrátového přenosu malých množtví dat pomocí existující bezdrátové telefonní a datové sítě.<br /> <br /> Technologie NB-IoT je založena na standardech Low Power Wide Area (LPWA) a díky její nízké spotřebě a vysoké propustnosti se Internet věcí může masivně rozšířit. Podporuje řešení jak v průmyslu (např. v energetice, automobilovém průmyslu, strojírenství, zemědělství, atd.), zdravotnictví a v projektech chytrých měst, tak i v oblasti běžného života (monitorování a zabezpečení domácností, vozidel, domácích mazlíčků atd.). Mezi největší výhody patří výborná prostupnost signálu překážkami, signál se tak dostane i do sklepů nebo garáží, dále provoz na licencovaném frekvenčním pásmu zajišťujícím uživatelům spolehlivější a bezpečnější komunikaci, roaming, nízká spotřeba energie koncovými zařízeními (výdrž baterie až 10 – 15 let) a také jejich nízká cena. <br /> <br /> Našemu týmu se podařilo okolo testovacícho čipu vybudovat celou hardwarovou platformu tak, že tato může být připojena k senzorickému modulu, a bude možné testovat její stabilitu, pokrytí a náročnost na napájení.<br /> Tato část projektu je již téměř dokončena a nachází se ve stádiu pre-produkčního testování.<br /> <br /> Díky tomu, že se jedná o technologii patentovanou a ke své fuknci využívající produkční komerční frekvence vlastněné společností Vodafone, nebude tato část modulu zařazena v OpenSource verzi projektu SenseNet<br /> <h3>LoraWan</h3> Nekomerční, OpenSource obdoba NB-IoT sestávající z open hardware i open software, která využívá nekomerční, ale také negarantovaná vysílací pásma pro rádiový přenos.<br /> Modul bude zařazen do OpenSource dokumentace SenseNet a měl by být plně schopen nahradit komerční, patentované řešení.<br /> V součastné době ještě neproběhlo testování v Labce, nicméně hardware senzorů je pro LoraWan nasazení připraven.<br /> <h3>Interní síťová infrastruktura</h3> Interně bude pro síťování projektu použita standarndní implementace IPv4 a do budoucna IPv6.<br /> Tato část projektu je již hotová v pre-produkčním stadiu, bude vytvořena ještě dokumentace pro jiné než testovací a laboratorní použití. </body> </html>
Labka-cz/SensorNet
Web/net.html
HTML
gpl-3.0
4,611
/* This file is part of sudoku_systemc Copyright (C) 2012 Julien Thevenon ( julien_thevenon at yahoo.fr ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef SUDOKU_INTERNAL_STATE_H #define SUDOKU_INTERNAL_STATE_H #include "sudoku_types.h" #include "cell_listener_if.h" namespace sudoku_systemc { template<unsigned int SIZE> class sudoku_internal_state { public: sudoku_internal_state(const unsigned int & p_sub_x,const unsigned int & p_sub_y,const unsigned int & p_initial_value, cell_listener_if & p_listener); sudoku_internal_state(const sudoku_internal_state<SIZE> & p_initial_state,const unsigned int & p_hypothesis_level); unsigned int get_real_value(const typename sudoku_types<SIZE>::t_data_type & p_value)const; void remove_vertical_candidate(const typename sudoku_types<SIZE>::t_data_type & p_value); void remove_horizontal_candidate(const typename sudoku_types<SIZE>::t_data_type & p_value); void remove_square_candidate(const typename sudoku_types<SIZE>::t_data_type & p_value); void remove_available_value(const typename sudoku_types<SIZE>::t_data_type & p_value); const typename sudoku_types<SIZE>::t_nb_available_values & get_nb_available_values(void)const; const typename sudoku_types<SIZE>::t_data_type make_hypothesis(void); const typename sudoku_types<SIZE>::t_available_values & get_values_to_release(void)const; const typename sudoku_types<SIZE>::t_data_type get_remaining_value(void); // Value management inline const typename sudoku_types<SIZE>::t_data_type & get_value(void)const; inline const bool is_value_set(void)const; void set_value(const typename sudoku_types<SIZE>::t_data_type & p_value); const unsigned int & get_hypothesis_level(void)const; bool is_modified(void)const ; void notify_listener(void); private: void set_horizontal_candidate(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value); void set_vertical_candidate(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value); void set_square_candidate(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value); void set_available_value(const unsigned int & p_index, bool p_value); void set_release_value(const unsigned int & p_index, bool p_value); cell_listener_if & m_listener; typename sudoku_types<SIZE>::t_group_candidate m_vertical_candidates[sudoku_configuration<SIZE>::m_nb_value]; typename sudoku_types<SIZE>::t_group_candidate m_horizontal_candidates[sudoku_configuration<SIZE>::m_nb_value]; typename sudoku_types<SIZE>::t_group_candidate m_square_candidates[sudoku_configuration<SIZE>::m_nb_value]; typename sudoku_types<SIZE>::t_available_values m_available_values; typename sudoku_types<SIZE>::t_nb_available_values m_nb_available_values; typename sudoku_types<SIZE>::t_available_values m_values_to_release; typename sudoku_types<SIZE>::t_data_type m_value; bool m_value_set; unsigned int m_hypothesis_level; bool m_modified; }; } #include "sudoku_internal_state.hpp" #endif // SUDOKU_INTERNAL_STATE_H //EOF
quicky2000/sudoku_systemc
include/sudoku_internal_state.h
C
gpl-3.0
3,886
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-20 22:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('erudit', '0065_auto_20170202_1152'), ] operations = [ migrations.AddField( model_name='issue', name='force_free_access', field=models.BooleanField(default=False, verbose_name='Contraindre en libre accès'), ), ]
erudit/zenon
eruditorg/erudit/migrations/0066_issue_force_free_access.py
Python
gpl-3.0
505
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Modules.InstantAction.Views { /// <summary> /// InstantActionPage.xaml の相互作用ロジック /// </summary> public partial class InstantActionPage : UserControl { public InstantActionPage() { InitializeComponent(); } } public class InstantActionStepDataTemplateSelecter : DataTemplateSelector { public DataTemplate EmptyTemplate { get; set; } public DataTemplate FileSelectTemplate { get; set; } public DataTemplate ActionSelectTemplate { get; set; } public DataTemplate FinishingTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item == null) { return EmptyTemplate; } else if (item is ViewModels.FileSelectInstantActionStepViewModel) { return FileSelectTemplate; } else if (item is ViewModels.ActionsSelectInstantActionStepViewModel) { return ActionSelectTemplate; } else if (item is ViewModels.FinishingInstantActionStepViewModel) { return FinishingTemplate; } return base.SelectTemplate(item, container); } } }
tor4kichi/ReactiveFolder
Module/InstantAction/Views/InstantActionPage.xaml.cs
C#
gpl-3.0
1,475
package bartburg.nl.backbaseweather.provision.remote.controller; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import bartburg.nl.backbaseweather.AppConstants; import bartburg.nl.backbaseweather.provision.remote.annotation.ApiController; import bartburg.nl.backbaseweather.provision.remote.util.QueryStringUtil; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_MAP_BASE_URL; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_PROTOCOL; /** * Created by Bart on 6/3/2017. */ public abstract class BaseApiController { /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener) { return get(parameters, onErrorListener, null); } /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @param customRelativePath Use this if you want to provide a custom relative path (not the one from the annotation). * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener, @Nullable String customRelativePath) { try { parameters.put("appid", AppConstants.OPEN_WEATHER_MAP_KEY); URL url = new URL(OPEN_WEATHER_PROTOCOL + OPEN_WEATHER_MAP_BASE_URL + getRelativePath(customRelativePath) + QueryStringUtil.mapToQueryString(parameters)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); String responseMessage = urlConnection.getResponseMessage(); if (responseCode != 200 && onErrorListener != null) { onErrorListener.onError(responseCode, responseMessage); } else { return readInputStream(urlConnection); } } catch (IOException e) { e.printStackTrace(); } return null; } @NonNull private String readInputStream(HttpURLConnection urlConnection) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); return sb.toString(); } public interface OnErrorListener { void onError(int responseCode, String responseMessage); } private String getRelativePath(String customRelativePath) { if (customRelativePath != null) { return customRelativePath; } Class<? extends BaseApiController> aClass = getClass(); if (aClass.isAnnotationPresent(ApiController.class)) { Annotation annotation = aClass.getAnnotation(ApiController.class); ApiController apiController = (ApiController) annotation; return apiController.relativePath(); } return ""; } }
bartburg/backbaseweatherapp
app/src/main/java/bartburg/nl/backbaseweather/provision/remote/controller/BaseApiController.java
Java
gpl-3.0
3,934
/***************************************************************** * This file is part of CCAFS Planning and Reporting Platform. * CCAFS P&R is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * CCAFS P&R is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with CCAFS P&R. If not, see <http://www.gnu.org/licenses/>. * *************************************************************** */ package org.cgiar.ccafs.ap.data.dao.mysql; import org.cgiar.ccafs.ap.data.dao.ProjectOtherContributionDAO; import org.cgiar.ccafs.utils.db.DAOManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Javier Andrés Gallego B. */ public class MySQLProjectOtherContributionDAO implements ProjectOtherContributionDAO { // Logger private static Logger LOG = LoggerFactory.getLogger(MySQLProjectOtherContributionDAO.class); private DAOManager databaseManager; @Inject public MySQLProjectOtherContributionDAO(DAOManager databaseManager) { this.databaseManager = databaseManager; } @Override public Map<String, String> getIPOtherContributionById(int ipOtherContributionId) { Map<String, String> ipOtherContributionData = new HashMap<String, String>(); LOG.debug(">> getIPOtherContributionById( ipOtherContributionId = {} )", ipOtherContributionId); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("WHERE ipo.id= "); query.append(ipOtherContributionId); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution {}.", ipOtherContributionId, e); } LOG.debug("-- getIPOtherContributionById() > Calling method executeQuery to get the results"); return ipOtherContributionData; } @Override public Map<String, String> getIPOtherContributionByProjectId(int projectID) { LOG.debug(">> getIPOtherContributionByProjectId (projectID = {} )", projectID); Map<String, String> ipOtherContributionData = new HashMap<String, String>(); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("INNER JOIN projects p ON ipo.project_id = p.id "); query.append("WHERE ipo.project_id= "); query.append(projectID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution by the projectID {}.", projectID, e); } LOG.debug("-- getIPOtherContributionByProjectId() : {}", ipOtherContributionData); return ipOtherContributionData; } @Override public int saveIPOtherContribution(int projectID, Map<String, Object> ipOtherContributionData) { LOG.debug(">> saveIPOtherContribution(ipOtherContributionDataData={})", ipOtherContributionData); StringBuilder query = new StringBuilder(); int result = -1; Object[] values; if (ipOtherContributionData.get("id") == null) { // Insert new IP Other Contribution record query.append("INSERT INTO project_other_contributions (project_id, contribution, additional_contribution, "); query.append("crp_contributions_nature, created_by, modified_by, modification_justification) "); query.append("VALUES (?,?,?,?,?,?,?) "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("user_id"); values[6] = ipOtherContributionData.get("justification"); result = databaseManager.saveData(query.toString(), values); if (result <= 0) { LOG.error("A problem happened trying to add a new IP Other Contribution with project id={}", projectID); return -1; } } else { // update IP Other Contribution record query.append("UPDATE project_other_contributions SET project_id = ?, contribution = ?, "); query.append("additional_contribution = ?, crp_contributions_nature = ?, modified_by = ?, "); query.append("modification_justification = ? WHERE id = ? "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("justification"); values[6] = ipOtherContributionData.get("id"); result = databaseManager.saveData(query.toString(), values); if (result == -1) { LOG.error("A problem happened trying to update the IP Other Contribution identified with the id = {}", ipOtherContributionData.get("id")); return -1; } } LOG.debug("<< saveIPOtherContribution():{}", result); return result; } }
CCAFS/ccafs-ap
impactPathways/src/main/java/org/cgiar/ccafs/ap/data/dao/mysql/MySQLProjectOtherContributionDAO.java
Java
gpl-3.0
6,952
<?php // Heading $_['heading_title'] = 'TargetPay Sofort Banking'; // Text $_['text_payment'] = 'Betaling'; $_['text_success'] = 'Gelukt: de TargetPay instellingen zijn gewijzigd!'; $_['text_edit'] = 'Bewerk TargetPay ' . $_['heading_title']; $_['text_sofort'] = '<a href="https://www.targetpay.com/signup?p_actiecode=YM3R2A" target="_blank"><img src="view/image/payment/sofort.png" alt="Sofort Banking via TargetPay" title="Sofort Banking via TargetPay" style="border: none;" /></a>'; $_['text_sale'] = 'Verkopen'; // Entry $_['entry_rtlo'] = 'TargetPay Layoutcode'; $_['entry_test'] = 'Test Mode'; $_['entry_total'] = 'Min.bedrag'; $_['entry_canceled_status'] = 'Afgebroken betaling'; $_['entry_pending_status'] = 'Succesvolle betaling'; $_['entry_geo_zone'] = 'Geo Zone'; $_['entry_status'] = 'Status'; $_['entry_sort_order'] = 'Sorteer volgorde'; // Error $_['error_permission'] = 'Waarschuwing: je bent niet gemachtigd om deze instellingen te wijzigen'; $_['error_rtlo'] = 'TargetPay layoutcode (rtlo) is verplicht!'; // Tab $_['tab_general'] = 'Algemeen'; $_['tab_status'] = 'Bestelstatussen'; // Help $_['help_test'] = 'Als ingeschakeld: alle transacties worden goedgekeurd, ook als de betaling geannuleerd is.'; $_['help_rtlo'] = 'Ga naar www.targetpay.com voor een gratis account, als je nog geen account hebt'; $_['help_total'] = 'Het orderbedrag waarboven deze betaalwijze beschikbaar is'; // Error $_['error_permission'] = 'Waarschuwing: je bent niet gemachtigd om deze instellingen te wijzigen'; $_['error_rtlo'] = 'Layoutcode is verplicht!';
robe4st/ideal-opencart
upload/admin/language/nl-nl/extension/payment/sofort.php
PHP
gpl-3.0
1,564
// ReSharper disable CheckNamespace using System; using System.Collections.Generic; public class Program { public static void Main() { var people = new Dictionary<string, Person>(); string input; while ((input = Console.ReadLine()) != "End") { var split = input.Split(); string name = split[0]; if (!people.ContainsKey(name)) { people.Add(name, new Person()); } Person person = people[name]; string infoType = split[1]; if (infoType == "company") { person.Company = new Company(split[2], split[3], double.Parse(split[4])); } else if (infoType == "pokemon") { person.Pokemon.Add(new Pokemon(split[2], split[3])); } else if (infoType == "parents") { person.Parents.Add(new Parent(split[2], split[3])); } else if (infoType == "children") { person.Children.Add(new Child(split[2], split[3])); } else if (infoType == "car") { person.Car = new Car(split[2], int.Parse(split[3])); } } string nameToPrint = Console.ReadLine(); Console.WriteLine(nameToPrint); people[nameToPrint].PrintInformation(); } }
martinmladenov/SoftUni-Solutions
CSharp OOP Basics/Exercises/01. Defining Classes - Exercise/Google/Program.cs
C#
gpl-3.0
1,441
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id: Exception.php 24594 2012-01-05 21:27:01Z matthew $ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Form_Exception */ require_once 'Zend/Form/Exception.php'; /** * Exception for Zend_Form component. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Form_Element_Exception extends Zend_Form_Exception { }
basdog22/Qool
lib/Zend/Form/Element/Exception.php
PHP
gpl-3.0
1,225
// +build linux package subsystem import ( "bufio" "errors" "fmt" "io" "os" "os/exec" "runtime" "strconv" "strings" ) type PlatformHeader LinuxHeader func NewPlatformHeader() *LinuxHeader { header := new(LinuxHeader) header.Devices = make(map[string]LinuxDevice) header.getDevsParts() return header } func (header *LinuxHeader) getDevsParts() { f, err := os.Open("/proc/diskstats") if err != nil { panic(err) } defer f.Close() scan := bufio.NewScanner(f) for scan.Scan() { var major, minor int var name string c, err := fmt.Sscanf(scan.Text(), "%d %d %s", &major, &minor, &name) if err != nil { panic(err) } if c != 3 { continue } header.DevsParts = append(header.DevsParts, name) if isDevice(name) { header.Devices[name] = LinuxDevice{ name, getPartitions(name), } } } } func isDevice(name string) bool { stat, err := os.Stat(fmt.Sprintf("/sys/block/%s", name)) if err == nil && stat.IsDir() { return true } return false } func getPartitions(name string) []string { var dir *os.File var fis []os.FileInfo var err error var parts = []string{} dir, err = os.Open(fmt.Sprintf("/sys/block/%s", name)) if err != nil { panic(err) } fis, err = dir.Readdir(0) if err != nil { panic(err) } for _, fi := range fis { _, err := os.Stat(fmt.Sprintf("/sys/block/%s/%s/stat", name, fi.Name())) if err == nil { // partition exists parts = append(parts, fi.Name()) } } return parts } func ReadCpuStat(record *StatRecord) error { f, ferr := os.Open("/proc/stat") if ferr != nil { return ferr } defer f.Close() if record.Cpu == nil { num_core := 0 out, err := exec.Command("nproc", "--all").Output() out_str := strings.TrimSpace(string(out)) if err == nil { num_core, err = strconv.Atoi(out_str) if err != nil { num_core = 0 } } if num_core == 0 { num_core = runtime.NumCPU() } record.Cpu = NewCpuStat(num_core) } else { record.Cpu.Clear() } if record.Proc == nil { record.Proc = NewProcStat() } else { record.Proc.Clear() } scan := bufio.NewScanner(f) for scan.Scan() { var err error var cpu string line := scan.Text() if line[0:4] == "cpu " { // Linux 2.6.33 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d", &cpu, &record.Cpu.All.User, &record.Cpu.All.Nice, &record.Cpu.All.Sys, &record.Cpu.All.Idle, &record.Cpu.All.Iowait, &record.Cpu.All.Hardirq, &record.Cpu.All.Softirq, &record.Cpu.All.Steal, &record.Cpu.All.Guest, &record.Cpu.All.GuestNice) if err == io.EOF { // Linux 2.6.24 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d", &cpu, &record.Cpu.All.User, &record.Cpu.All.Nice, &record.Cpu.All.Sys, &record.Cpu.All.Idle, &record.Cpu.All.Iowait, &record.Cpu.All.Hardirq, &record.Cpu.All.Softirq, &record.Cpu.All.Steal, &record.Cpu.All.Guest) record.Cpu.All.GuestNice = 0 } if err != nil { panic(err) } } else if line[0:3] == "cpu" { var n_core int var core_stat *CpuCoreStat // assume n_core < 10000 _, err = fmt.Sscanf(line[3:7], "%d", &n_core) if err != nil { panic(err) } core_stat = &record.Cpu.CoreStats[n_core] // Linux 2.6.33 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d", &cpu, &core_stat.User, &core_stat.Nice, &core_stat.Sys, &core_stat.Idle, &core_stat.Iowait, &core_stat.Hardirq, &core_stat.Softirq, &core_stat.Steal, &core_stat.Guest, &core_stat.GuestNice) if err == io.EOF { // Linux 2.6.24 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d", &cpu, &core_stat.User, &core_stat.Nice, &core_stat.Sys, &core_stat.Idle, &core_stat.Iowait, &core_stat.Hardirq, &core_stat.Softirq, &core_stat.Steal, &core_stat.Guest) } if err != nil { panic(err) } } else if line[0:5] == "ctxt " { _, err = fmt.Sscanf(line[4:], "%d", &record.Proc.ContextSwitch) if err != nil { panic(err) } } else if line[0:10] == "processes " { _, err = fmt.Sscanf(line[10:], "%d", &record.Proc.Fork) if err != nil { panic(err) } } } return nil } func parseInterruptStatEntry(line string, num_core int) (*InterruptStatEntry, error) { entry := new(InterruptStatEntry) entry.NumCore = num_core entry.IntrCounts = make([]int, num_core) tokens := strings.Fields(line) idx := 0 tok := tokens[0] tok = strings.TrimRight(tok, ":") if irqno, err := strconv.Atoi(tok); err == nil { entry.IrqNo = irqno entry.IrqType = "" } else { entry.IrqNo = -1 entry.IrqType = tok } for idx := 1; idx < num_core+1; idx += 1 { var c int var err error if idx >= len(tokens) { break } tok = tokens[idx] if c, err = strconv.Atoi(tok); err != nil { return nil, errors.New("Invalid string for IntrCounts element: " + tok) } entry.IntrCounts[idx-1] = c } idx = num_core + 1 if idx < len(tokens) { entry.Descr = strings.Join(tokens[idx:], " ") } else { entry.Descr = "" } return entry, nil } func ReadInterruptStat(record *StatRecord) error { intr_stat := NewInterruptStat() if record == nil { return errors.New("Valid *StatRecord is required.") } f, err := os.Open("/proc/interrupts") if err != nil { panic(err) } defer f.Close() scan := bufio.NewScanner(f) if !scan.Scan() { return errors.New("/proc/interrupts seems to be empty") } cores := strings.Fields(scan.Text()) num_core := len(cores) for scan.Scan() { entry, err := parseInterruptStatEntry(scan.Text(), num_core) if err != nil { return err } intr_stat.Entries = append(intr_stat.Entries, entry) intr_stat.NumEntries += 1 } record.Interrupt = intr_stat return nil } func ReadDiskStats(record *StatRecord, targets *map[string]bool) error { if record == nil { return errors.New("Valid *StatRecord is required.") } f, ferr := os.Open("/proc/diskstats") if ferr != nil { panic(ferr) } defer f.Close() if record.Disk == nil { record.Disk = NewDiskStat() } else { record.Disk.Clear() } scan := bufio.NewScanner(f) var num_items int var err error for scan.Scan() { var rdmerge_or_rdsec int64 var rdsec_or_wrios int64 var rdticks_or_wrsec int64 line := scan.Text() entry := NewDiskStatEntry() num_items, err = fmt.Sscanf(line, "%d %d %s %d %d %d %d %d %d %d %d %d %d %d", &entry.Major, &entry.Minor, &entry.Name, &entry.RdIos, &rdmerge_or_rdsec, &rdsec_or_wrios, &rdticks_or_wrsec, &entry.WrIos, &entry.WrMerges, &entry.WrSectors, &entry.WrTicks, &entry.IosPgr, &entry.TotalTicks, &entry.ReqTicks) if err != nil { return err } if num_items == 14 { entry.RdMerges = rdmerge_or_rdsec entry.RdSectors = rdsec_or_wrios entry.RdTicks = rdticks_or_wrsec } else if num_items == 7 { entry.RdSectors = rdmerge_or_rdsec entry.WrIos = rdsec_or_wrios entry.WrSectors = rdticks_or_wrsec } else { continue } if entry.RdIos == 0 && entry.WrIos == 0 { continue } if targets != nil { if _, ok := (*targets)[entry.Name]; !ok { // device not in targets continue } } else { if !isDevice(entry.Name) { continue } } record.Disk.Entries = append(record.Disk.Entries, entry) } return nil } func ReadNetStat(record *StatRecord) error { if record == nil { return errors.New("Valid *StatRecord is required.") } net_stat := NewNetStat() f, err := os.Open("/proc/net/dev") if err != nil { return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() switch { case line[0:7] == "Inter-|": continue case line[0:7] == " face |": continue } line = strings.Replace(line, ":", " ", -1) e := NewNetStatEntry() var devname string n, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &devname, &e.RxBytes, &e.RxPackets, &e.RxErrors, &e.RxDrops, &e.RxFifo, &e.RxFrame, &e.RxCompressed, &e.RxMulticast, &e.TxBytes, &e.TxPackets, &e.TxErrors, &e.TxDrops, &e.TxFifo, &e.TxFrame, &e.TxCompressed, &e.TxMulticast) if err == io.EOF { break } else if err != nil { return err } if n != 17 { continue } // trim trailing ":" from devname if devname[len(devname)-1] == ':' { devname = devname[0 : len(devname)-1] } e.Name = devname net_stat.Entries = append(net_stat.Entries, e) } record.Net = net_stat return nil } func ReadMemStat(record *StatRecord) error { if record == nil { return errors.New("Valid *StatRecord is required.") } mem_stat := NewMemStat() f, err := os.Open("/proc/meminfo") if err != nil { return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { var key string var val int64 line := scanner.Text() n, err := fmt.Sscanf(line, "%s %d", &key, &val) if err == io.EOF { break } else if err != nil { return err } if n != 2 { continue } switch key { case "HugePages_Surp:": mem_stat.HugePages_Surp = val case "HugePages_Rsvd:": mem_stat.HugePages_Rsvd = val case "HugePages_Free:": mem_stat.HugePages_Free = val case "HugePages_Total:": mem_stat.HugePages_Total = val case "Hugepagesize:": mem_stat.Hugepagesize = val case "AnonHugePages:": mem_stat.AnonHugePages = val case "Committed_AS:": mem_stat.Committed_AS = val case "CommitLimit:": mem_stat.CommitLimit = val case "Bounce:": mem_stat.Bounce = val case "NFS_Unstable:": mem_stat.NFS_Unstable = val case "Shmem:": mem_stat.Shmem = val case "Slab:": mem_stat.Slab = val case "SReclaimable:": mem_stat.SReclaimable = val case "SUnreclaim:": mem_stat.SUnreclaim = val case "KernelStack:": mem_stat.KernelStack = val case "PageTables:": mem_stat.PageTables = val case "Mapped:": mem_stat.Mapped = val case "AnonPages:": mem_stat.AnonPages = val case "Writeback:": mem_stat.Writeback = val case "Dirty:": mem_stat.Dirty = val case "SwapFree:": mem_stat.SwapFree = val case "SwapTotal:": mem_stat.SwapTotal = val case "Inactive:": mem_stat.Inactive = val case "Active:": mem_stat.Active = val case "SwapCached:": mem_stat.SwapCached = val case "Cached:": mem_stat.Cached = val case "Buffers:": mem_stat.Buffers = val case "MemFree:": mem_stat.MemFree = val case "MemTotal:": mem_stat.MemTotal = val } } record.Mem = mem_stat return nil }
hayamiz/perfmonger
core/subsystem/perfmonger_linux.go
GO
gpl-3.0
10,563
/* * tca6416 keypad platform support * * Copyright (C) 2010 Texas Instruments * * Author: Sriramakrishnan <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef _TCA6416_KEYS_H #define _TCA6416_KEYS_H #include <linux/types.h> struct tca6416_button { /* Configuration parameters */ int code; /* input event code (KEY_*, SW_*) */ int active_low; int type; /* input event type (EV_KEY, EV_SW) */ }; struct tca6416_keys_platform_data { struct tca6416_button *buttons; int nbuttons; unsigned int rep: 1; /* enable input subsystem auto repeat */ uint16_t pinmask; uint16_t invert; int irq_is_gpio; int use_polling; /* use polling if Interrupt is not connected*/ }; #endif
williamfdevine/PrettyLinux
include/linux/tca6416_keypad.h
C
gpl-3.0
848
////////// // item // ////////// datablock ItemData(YoyoItem) { category = "Weapon"; // Mission editor category className = "Weapon"; // For inventory system // Basic Item Properties shapeFile = "./Yoyo.dts"; rotate = false; mass = 1; density = 0.2; elasticity = 0.2; friction = 0.6; emap = true; //gui stuff uiName = "Yo-yo"; iconName = "./icon_Yoyo"; doColorShift = true; colorShiftColor = "0 1 1 1.000"; // Dynamic properties defined by the scripts image = YoyoImage; canDrop = true; }; //////////////// //weapon image// //////////////// datablock ShapeBaseImageData(YoyoImage) { // Basic Item properties shapeFile = "./Yoyo.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; offset = "0 0 0"; eyeOffset = 0; //"0.7 1.2 -0.5"; rotation = eulerToMatrix( "0 0 0" ); // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = true; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; // Projectile && Ammo. item = YoyoItem; projectile = emptyProjectile; projectileType = Projectile; ammo = " "; //melee particles shoot from eye node for consistancy melee = false; //raise your arm up or not armReady = true; doColorShift = true; colorShiftColor = YoyoItem.colorShiftColor;//"0.400 0.196 0 1.000"; //casing = " "; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Activate"; stateTimeoutValue[0] = 0.15; stateTransitionOnTimeout[0] = "Ready"; stateSound[0] = weaponSwitchSound; stateName[1] = "Ready"; stateTransitionOnTriggerDown[1] = "Fire"; stateAllowImageChange[1] = true; stateSequence[1] = "Ready"; stateName[2] = "Fire"; stateTimeoutValue[2] = 1.1; stateTransitionOnTimeout[2] = "Reload"; stateSequence[2] = "fire"; stateScript[2] = "OnFire"; stateName[3] = "Reload"; stateSequence[3] = "Reload"; stateTransitionOnTriggerUp[3] = "Ready"; stateSequence[3] = "Ready"; };
piber20/BL-FK-GameMode
GameMode_FASTKarts/addons/novelty/Yoyo.cs
C#
gpl-3.0
2,759
/** ****************************************************************************** * @file EEPROM/EEPROM_Emulation/Inc/stm32f4xx_it.h * @author MCD Application Team * @version V1.3.6 * @date 17-February-2017 * @brief This file contains the headers of the interrupt handlers. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of STMicroelectronics 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 HOLDER 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_IT_H #define __STM32F4xx_IT_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); void MemManage_Handler(void); void BusFault_Handler(void); void UsageFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); #ifdef __cplusplus } #endif #endif /* __STM32F4xx_IT_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
TRothfelder/Multicopter
libs/STM32Cube_FW_F4_V1.16.0/Projects/STM32F401-Discovery/Applications/EEPROM/EEPROM_Emulation/Inc/stm32f4xx_it.h
C
gpl-3.0
3,163
// Copyright 2016 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 "services/video_capture/device_mojo_mock_to_media_adapter.h" #include "services/video_capture/device_client_media_to_mojo_mock_adapter.h" namespace video_capture { DeviceMojoMockToMediaAdapter::DeviceMojoMockToMediaAdapter( mojom::MockMediaDevicePtr* device) : device_(device) {} DeviceMojoMockToMediaAdapter::~DeviceMojoMockToMediaAdapter() = default; void DeviceMojoMockToMediaAdapter::AllocateAndStart( const media::VideoCaptureParams& params, std::unique_ptr<Client> client) { mojom::MockDeviceClientPtr client_proxy; auto client_request = mojo::GetProxy(&client_proxy); mojo::MakeStrongBinding( base::MakeUnique<DeviceClientMediaToMojoMockAdapter>(std::move(client)), std::move(client_request)); (*device_)->AllocateAndStart(std::move(client_proxy)); } void DeviceMojoMockToMediaAdapter::RequestRefreshFrame() {} void DeviceMojoMockToMediaAdapter::StopAndDeAllocate() { (*device_)->StopAndDeAllocate(); } void DeviceMojoMockToMediaAdapter::GetPhotoCapabilities( GetPhotoCapabilitiesCallback callback) {} void DeviceMojoMockToMediaAdapter::SetPhotoOptions( media::mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) {} void DeviceMojoMockToMediaAdapter::TakePhoto(TakePhotoCallback callback) {} } // namespace video_capture
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/services/video_capture/device_mojo_mock_to_media_adapter.cc
C++
gpl-3.0
1,483
package com.ocams.andre; import javax.swing.table.DefaultTableModel; public class MasterJurnal extends javax.swing.JFrame { public MasterJurnal() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jTextField4 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Kode:"); jLabel2.setText("Perkiraan:"); jLabel3.setText("Nomor Referensi:"); jLabel4.setText("Posisi:"); jLabel5.setText("Harga:"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton1); jRadioButton1.setText("Debit"); buttonGroup1.add(jRadioButton2); jRadioButton2.setText("Kredit"); jLabel6.setText("User:"); jLabel7.setText("NamaUser"); jButton1.setText("Logout"); jButton2.setText("Insert"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("Update"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText("Delete"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Kode", "Perkiraan", "No. Ref.", "Posisi", "Harga" } )); jTable2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable2MouseClicked(evt); } }); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7)) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton2)) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jRadioButton1) .addComponent(jRadioButton2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); Object[] row = {kode,perkiraan,noref,posisi,harga}; DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.addRow(row); }//GEN-LAST:event_jButton2MouseClicked private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.setValueAt(kode, baris, 0); model.setValueAt(perkiraan, baris, 1); model.setValueAt(noref, baris, 2); model.setValueAt(posisi, baris, 3); model.setValueAt(harga, baris, 4); }//GEN-LAST:event_jButton3MouseClicked private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.removeRow(jTable2.rowAtPoint(evt.getPoint())); }//GEN-LAST:event_jButton4MouseClicked private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); jTextField1.setText(String.valueOf(jTable2.getValueAt(baris, 0))); jTextField2.setText(String.valueOf(jTable2.getValueAt(baris, 1))); jTextField3.setText(String.valueOf(jTable2.getValueAt(baris,2))); String posisi = String.valueOf(jTable2.getValueAt(baris, 3)); if ("debit".equalsIgnoreCase(posisi)){ jRadioButton1.setSelected(true); }else if ("kredit".equalsIgnoreCase(posisi)){ jRadioButton2.setSelected(true); } jTextField4.setText(String.valueOf(jTable2.getValueAt(baris, 4))); }//GEN-LAST:event_jTable2MouseClicked private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MasterJurnal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables }
benyaminl/OCAMS
src/com/ocams/andre/MasterJurnal.java
Java
gpl-3.0
15,559
// Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder #ifndef _DUEL_H_ #define _DUEL_H_ struct duel { int members_count; int invites_count; int max_players_limit; }; #define MAX_DUEL 1024 extern struct duel duel_list[MAX_DUEL]; extern int duel_count; //Duel functions // [LuzZza] int duel_create (struct map_session_data *sd, const unsigned int maxpl); int duel_invite (const unsigned int did, struct map_session_data *sd, struct map_session_data *target_sd); int duel_accept (const unsigned int did, struct map_session_data *sd); int duel_reject (const unsigned int did, struct map_session_data *sd); int duel_leave (const unsigned int did, struct map_session_data *sd); int duel_showinfo (const unsigned int did, struct map_session_data *sd); int duel_checktime (struct map_session_data *sd); int do_init_duel (void); void do_final_duel (void); #endif /* _DUEL_H_ */
Zellukas/Radices
src/map/duel.h
C
gpl-3.0
939