text
stringlengths
2
1.04M
meta
dict
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "267b0832dc29badf32df17473adbd191", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "2ba5a877cd044734cb0e493eeb41963377e15116", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Hapalorchis/Hapalorchis lineata/ Syn. Hapalorchis lineata brevicaulis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Public Class FormMainIssue 'Public dataExist As Boolean = False Private Sub SaveData() Me.Validate() Me.MainIssueDataTableBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me.DataSetMainIssue) End Sub Private Sub loadMainIssue() Try If oMainIssue.funcCheckIsMainIssueExist() = True Then Me.MainIssueDataTableTableAdapter.Fill(Me.DataSetMainIssue.MainIssueDataTable, New Nullable(Of Integer)(CType(oProject.idProject2, Integer))) End If Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub FormMainIssue_Load(sender As Object, e As EventArgs) Handles MyBase.Load If oMainIssue.funcCheckIsMainIssueExist() = True Then loadMainIssue() End If End Sub Private Sub buttonSave_Click(sender As Object, e As EventArgs) Handles buttonSave.Click SaveData() SaveDialog(Me) End Sub Private Sub FormMainIssue_Activated(sender As Object, e As EventArgs) Handles Me.Activated If oMainIssue.funcCheckIsMainIssueExist() = 0 Then GridView1.AddNewRow() GridView1.SetFocusedRowCellValue(colidUser, aUser.IDUser) GridView1.SetFocusedRowCellValue(colidProject, oProject.idProject2) purposeMemoEdit.Focus() End If End Sub End Class
{ "content_hash": "cad3bd9b68e846bee0e0dd9f27b31030", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 157, "avg_line_length": 38.72222222222222, "alnum_prop": 0.6822094691535151, "repo_name": "bigbhe/1310", "id": "15b1b430a4c7231f8c8e786cd95d0030220e96c4", "size": "1396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SROI-SKRIPSI/Form/FormMainIssue.vb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Visual Basic", "bytes": "1733133" } ], "symlink_target": "" }
.class Lcom/android/server/sip/SipService$IntervalMeasurementProcess; .super Ljava/lang/Object; .source "SipService.java" # interfaces .implements Ljava/lang/Runnable; .implements Lcom/android/server/sip/SipSessionGroup$KeepAliveProcessCallback; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lcom/android/server/sip/SipService; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x2 name = "IntervalMeasurementProcess" .end annotation # static fields .field private static final MAX_RETRY_COUNT:I = 0x5 .field private static final MIN_INTERVAL:I = 0x5 .field private static final NAT_MEASUREMENT_RETRY_INTERVAL:I = 0x78 .field private static final PASS_THRESHOLD:I = 0xa .field private static final TAG:Ljava/lang/String; = "SipKeepAliveInterval" # instance fields .field private mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; .field private mInterval:I .field private mLocalProfile:Landroid/net/sip/SipProfile; .field private mMaxInterval:I .field private mMinInterval:I .field private mPassCount:I .field private mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; .field final synthetic this$0:Lcom/android/server/sip/SipService; # direct methods .method public constructor <init>(Lcom/android/server/sip/SipService;Landroid/net/sip/SipProfile;II)V .locals 0 .parameter .parameter "localProfile" .parameter "minInterval" .parameter "maxInterval" .prologue .line 651 iput-object p1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V .line 652 iput p4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMaxInterval:I .line 653 iput p3, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I .line 654 iput-object p2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mLocalProfile:Landroid/net/sip/SipProfile; .line 655 return-void .end method .method private checkTermination()Z .locals 2 .prologue .line 721 iget v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMaxInterval:I iget v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I sub-int/2addr v0, v1 const/4 v1, 0x5 if-ge v0, v1, :cond_0 const/4 v0, 0x1 :goto_0 return v0 :cond_0 const/4 v0, 0x0 goto :goto_0 .end method .method private restart()V .locals 5 .prologue .line 705 iget-object v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; monitor-enter v2 .line 707 :try_start_0 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; if-nez v1, :cond_0 monitor-exit v2 .line 718 :goto_0 return-void .line 709 :cond_0 const-string v1, "SipKeepAliveInterval" new-instance v3, Ljava/lang/StringBuilder; invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v4, "restart measurement w interval=" invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v3 iget v4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; move-result-object v3 invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v3 invoke-static {v1, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .line 711 :try_start_1 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; invoke-virtual {v1}, Lcom/android/server/sip/SipSessionGroup$SipSessionImpl;->stopKeepAliveProcess()V .line 712 const/4 v1, 0x0 iput v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mPassCount:I .line 713 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; iget v3, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I invoke-virtual {v1, v3, p0}, Lcom/android/server/sip/SipSessionGroup$SipSessionImpl;->startKeepAliveProcess(ILcom/android/server/sip/SipSessionGroup$KeepAliveProcessCallback;)V :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 .catch Ljavax/sip/SipException; {:try_start_1 .. :try_end_1} :catch_0 .line 717 :goto_1 :try_start_2 monitor-exit v2 goto :goto_0 :catchall_0 move-exception v1 monitor-exit v2 :try_end_2 .catchall {:try_start_2 .. :try_end_2} :catchall_0 throw v1 .line 714 :catch_0 move-exception v0 .line 715 .local v0, e:Ljavax/sip/SipException; :try_start_3 const-string v1, "SipKeepAliveInterval" const-string/jumbo v3, "restart()" invoke-static {v1, v3, v0}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I :try_end_3 .catchall {:try_start_3 .. :try_end_3} :catchall_0 goto :goto_1 .end method .method private restartLater()V .locals 4 .prologue .line 784 iget-object v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; monitor-enter v2 .line 785 const/16 v0, 0x78 .line 786 .local v0, interval:I :try_start_0 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mTimer:Lcom/android/server/sip/SipWakeupTimer; invoke-static {v1}, Lcom/android/server/sip/SipService;->access$300(Lcom/android/server/sip/SipService;)Lcom/android/server/sip/SipWakeupTimer; move-result-object v1 invoke-virtual {v1, p0}, Lcom/android/server/sip/SipWakeupTimer;->cancel(Ljava/lang/Runnable;)V .line 787 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mTimer:Lcom/android/server/sip/SipWakeupTimer; invoke-static {v1}, Lcom/android/server/sip/SipService;->access$300(Lcom/android/server/sip/SipService;)Lcom/android/server/sip/SipWakeupTimer; move-result-object v1 const v3, 0x1d4c0 invoke-virtual {v1, v3, p0}, Lcom/android/server/sip/SipWakeupTimer;->set(ILjava/lang/Runnable;)V .line 788 monitor-exit v2 .line 789 return-void .line 788 :catchall_0 move-exception v1 monitor-exit v2 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v1 .end method # virtual methods .method public onError(ILjava/lang/String;)V .locals 3 .parameter "errorCode" .parameter "description" .prologue .line 772 const-string v0, "SipKeepAliveInterval" new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string v2, "interval measurement error: " invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I .line 773 invoke-direct {p0}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->restartLater()V .line 774 return-void .end method .method public onResponse(Z)V .locals 3 .parameter "portChanged" .prologue .line 727 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; monitor-enter v1 .line 728 if-nez p1, :cond_2 .line 729 :try_start_0 iget v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mPassCount:I add-int/lit8 v0, v0, 0x1 iput v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mPassCount:I const/16 v2, 0xa if-eq v0, v2, :cond_0 monitor-exit v1 .line 767 :goto_0 return-void .line 732 :cond_0 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mKeepAliveInterval:I invoke-static {v0}, Lcom/android/server/sip/SipService;->access$1000(Lcom/android/server/sip/SipService;)I move-result v0 if-lez v0, :cond_1 .line 733 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; iget-object v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mKeepAliveInterval:I invoke-static {v2}, Lcom/android/server/sip/SipService;->access$1000(Lcom/android/server/sip/SipService;)I move-result v2 #setter for: Lcom/android/server/sip/SipService;->mLastGoodKeepAliveInterval:I invoke-static {v0, v2}, Lcom/android/server/sip/SipService;->access$1102(Lcom/android/server/sip/SipService;I)I .line 735 :cond_1 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; iget v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I iput v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I #setter for: Lcom/android/server/sip/SipService;->mKeepAliveInterval:I invoke-static {v0, v2}, Lcom/android/server/sip/SipService;->access$1002(Lcom/android/server/sip/SipService;I)I .line 740 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #calls: Lcom/android/server/sip/SipService;->onKeepAliveIntervalChanged()V invoke-static {v0}, Lcom/android/server/sip/SipService;->access$1200(Lcom/android/server/sip/SipService;)V .line 745 :goto_1 invoke-direct {p0}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->checkTermination()Z move-result v0 if-eqz v0, :cond_3 .line 747 invoke-virtual {p0}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->stop()V .line 752 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; iget v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I #setter for: Lcom/android/server/sip/SipService;->mKeepAliveInterval:I invoke-static {v0, v2}, Lcom/android/server/sip/SipService;->access$1002(Lcom/android/server/sip/SipService;I)I .line 766 :goto_2 monitor-exit v1 goto :goto_0 :catchall_0 move-exception v0 monitor-exit v1 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v0 .line 743 :cond_2 :try_start_1 iget v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I iput v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMaxInterval:I goto :goto_1 .line 759 :cond_3 iget v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMaxInterval:I iget v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I add-int/2addr v0, v2 div-int/lit8 v0, v0, 0x2 iput v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I .line 764 invoke-direct {p0}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->restart()V :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 goto :goto_2 .end method .method public run()V .locals 1 .prologue .line 779 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mTimer:Lcom/android/server/sip/SipWakeupTimer; invoke-static {v0}, Lcom/android/server/sip/SipService;->access$300(Lcom/android/server/sip/SipService;)Lcom/android/server/sip/SipWakeupTimer; move-result-object v0 invoke-virtual {v0, p0}, Lcom/android/server/sip/SipWakeupTimer;->cancel(Ljava/lang/Runnable;)V .line 780 invoke-direct {p0}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->restart()V .line 781 return-void .end method .method public start()V .locals 7 .prologue .line 658 iget-object v2, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; monitor-enter v2 .line 659 :try_start_0 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; if-eqz v1, :cond_0 .line 660 monitor-exit v2 .line 688 :goto_0 return-void .line 663 :cond_0 iget v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMaxInterval:I iget v3, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I add-int/2addr v1, v3 div-int/lit8 v1, v1, 0x2 iput v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I .line 664 const/4 v1, 0x0 iput v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mPassCount:I .line 667 iget v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I const/16 v3, 0xa if-lt v1, v3, :cond_1 invoke-direct {p0}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->checkTermination()Z move-result v1 if-eqz v1, :cond_2 .line 668 :cond_1 const-string v1, "SipKeepAliveInterval" new-instance v3, Ljava/lang/StringBuilder; invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v4, "measurement aborted; interval=[" invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v3 iget v4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMinInterval:I invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; move-result-object v3 const-string v4, "," invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v3 iget v4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mMaxInterval:I invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; move-result-object v3 const-string v4, "]" invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v3 invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v3 invoke-static {v1, v3}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I .line 670 monitor-exit v2 goto :goto_0 .line 687 :catchall_0 move-exception v1 monitor-exit v2 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v1 .line 674 :cond_2 :try_start_1 const-string v1, "SipKeepAliveInterval" new-instance v3, Ljava/lang/StringBuilder; invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v4, "start measurement w interval=" invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v3 iget v4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; move-result-object v3 invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v3 invoke-static {v1, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I .line 676 new-instance v1, Lcom/android/server/sip/SipService$SipSessionGroupExt; iget-object v3, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; iget-object v4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mLocalProfile:Landroid/net/sip/SipProfile; const/4 v5, 0x0 const/4 v6, 0x0 invoke-direct {v1, v3, v4, v5, v6}, Lcom/android/server/sip/SipService$SipSessionGroupExt;-><init>(Lcom/android/server/sip/SipService;Landroid/net/sip/SipProfile;Landroid/app/PendingIntent;Landroid/net/sip/ISipSessionListener;)V iput-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; .line 679 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; new-instance v3, Lcom/android/server/sip/SipWakeupTimer; iget-object v4, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mContext:Landroid/content/Context; invoke-static {v4}, Lcom/android/server/sip/SipService;->access$800(Lcom/android/server/sip/SipService;)Landroid/content/Context; move-result-object v4 iget-object v5, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mExecutor:Lcom/android/server/sip/SipService$MyExecutor; invoke-static {v5}, Lcom/android/server/sip/SipService;->access$900(Lcom/android/server/sip/SipService;)Lcom/android/server/sip/SipService$MyExecutor; move-result-object v5 invoke-direct {v3, v4, v5}, Lcom/android/server/sip/SipWakeupTimer;-><init>(Landroid/content/Context;Ljava/util/concurrent/Executor;)V invoke-virtual {v1, v3}, Lcom/android/server/sip/SipService$SipSessionGroupExt;->setWakeupTimer(Lcom/android/server/sip/SipWakeupTimer;)V .line 681 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; const/4 v3, 0x0 invoke-virtual {v1, v3}, Lcom/android/server/sip/SipService$SipSessionGroupExt;->createSession(Landroid/net/sip/ISipSessionListener;)Landroid/net/sip/ISipSession; move-result-object v1 check-cast v1, Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; iput-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; .line 683 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; iget v3, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mInterval:I invoke-virtual {v1, v3, p0}, Lcom/android/server/sip/SipSessionGroup$SipSessionImpl;->startKeepAliveProcess(ILcom/android/server/sip/SipSessionGroup$KeepAliveProcessCallback;)V :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 .catch Ljava/lang/Throwable; {:try_start_1 .. :try_end_1} :catch_0 .line 687 :goto_1 :try_start_2 monitor-exit v2 goto/16 :goto_0 .line 684 :catch_0 move-exception v0 .line 685 .local v0, t:Ljava/lang/Throwable; const/4 v1, -0x4 invoke-virtual {v0}, Ljava/lang/Throwable;->toString()Ljava/lang/String; move-result-object v3 invoke-virtual {p0, v1, v3}, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->onError(ILjava/lang/String;)V :try_end_2 .catchall {:try_start_2 .. :try_end_2} :catchall_0 goto :goto_1 .end method .method public stop()V .locals 2 .prologue .line 691 iget-object v1, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; monitor-enter v1 .line 692 :try_start_0 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; if-eqz v0, :cond_0 .line 693 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; invoke-virtual {v0}, Lcom/android/server/sip/SipSessionGroup$SipSessionImpl;->stopKeepAliveProcess()V .line 694 const/4 v0, 0x0 iput-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mSession:Lcom/android/server/sip/SipSessionGroup$SipSessionImpl; .line 696 :cond_0 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; if-eqz v0, :cond_1 .line 697 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; invoke-virtual {v0}, Lcom/android/server/sip/SipService$SipSessionGroupExt;->close()V .line 698 const/4 v0, 0x0 iput-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->mGroup:Lcom/android/server/sip/SipService$SipSessionGroupExt; .line 700 :cond_1 iget-object v0, p0, Lcom/android/server/sip/SipService$IntervalMeasurementProcess;->this$0:Lcom/android/server/sip/SipService; #getter for: Lcom/android/server/sip/SipService;->mTimer:Lcom/android/server/sip/SipWakeupTimer; invoke-static {v0}, Lcom/android/server/sip/SipService;->access$300(Lcom/android/server/sip/SipService;)Lcom/android/server/sip/SipWakeupTimer; move-result-object v0 invoke-virtual {v0, p0}, Lcom/android/server/sip/SipWakeupTimer;->cancel(Ljava/lang/Runnable;)V .line 701 monitor-exit v1 .line 702 return-void .line 701 :catchall_0 move-exception v0 monitor-exit v1 :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 throw v0 .end method
{ "content_hash": "6c6180c8a263a5de254c5adc80275167", "timestamp": "", "source": "github", "line_count": 747, "max_line_length": 232, "avg_line_length": 30.995983935742974, "alnum_prop": 0.7298091042584435, "repo_name": "baidurom/devices-onex", "id": "5798b763ce07aa3239ae08b315df22eb2c377734", "size": "23154", "binary": false, "copies": "1", "ref": "refs/heads/coron-4.0", "path": "framework.jar.out/smali/com/android/server/sip/SipService$IntervalMeasurementProcess.smali", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import type PlusnewAbstractElement from "../../../PlusnewAbstractElement"; import factory from "../../factory"; import reconciler from "../../reconciler"; import type FragmentInstance from "./Instance"; export default function <HostElement, HostTextElement>( newAbstractElement: PlusnewAbstractElement, instance: FragmentInstance<HostElement, HostTextElement> ) { for (let i = 0; i < newAbstractElement.props.children.length; i += 1) { if (i < instance.rendered.length) { const newInstance = reconciler.update( newAbstractElement.props.children[i], instance.rendered[i] ); if (newInstance !== instance.rendered[i]) { instance.rendered[i].remove(true); instance.rendered[i] = newInstance; instance.rendered[i].initialiseNestedElements(); } } else { const newInstance = factory( newAbstractElement.props.children[i], instance, instance.getLastIntrinsicElementOf.bind(instance, i - 1), instance.renderOptions ); instance.rendered.push(newInstance); newInstance.initialiseNestedElements(); } } while (instance.rendered.length > newAbstractElement.props.children.length) { instance.rendered[newAbstractElement.props.children.length].remove(true); instance.rendered.splice(newAbstractElement.props.children.length, 1); } instance.props = newAbstractElement.props; // updating the shadowdom }
{ "content_hash": "586a1b8419447673ecf6755c56924d80", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 79, "avg_line_length": 37, "alnum_prop": 0.7006237006237006, "repo_name": "plusgut/vood", "id": "9fad61fef48e4920caf8a043cae2666a78f4ef2c", "size": "1443", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/instances/types/Fragment/reconcile.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "66712" } ], "symlink_target": "" }
<!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/html; charset=UTF-8" /> <title>Texas hornshell factsheet on ARKive - Popenaias popeii</title> <link rel="canonical" href="http://www.arkive.org/texas-hornshell/popenaias-popeii/" /> <link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> </head> <body> <!-- onload="window.print()">--> <div id="container"> <div id="header"><a href="/"><img src="/rimg/factsheet/header_left.png" alt="" border="0" /><img src="/rimg/factsheet/header_logo.png" alt="" border="0" /><img src="/rimg/factsheet/header_right.png" alt="" border="0" /></a></div> <div id="content"> <h1>Texas hornshell (<i>Popenaias popeii</i>)</h1> <img alt="" src="/media/A2/A2E4FE02-C688-4C5B-80D8-763EF371373E/Presentation.Large/Texas-hornshell-adult-in-hand.jpg"/> <table cellspacing="0" cellpadding="0" id="factList"> <tbody> <tr class="kingdom"><th align="left">Kingdom</th><td align="left">Animalia</td></tr> <tr class="phylum"><th align="left">Phylum</th><td align="left">Mollusca</td></tr> <tr class="class"><th align="left">Class</th><td align="left">Bivalvia</td></tr> <tr class="order"><th align="left">Order</th><td align="left">Unionoida</td></tr> <tr class="family"><th align="left">Family</th><td align="left">Unionidae</td></tr> <tr class="genus"><th align="left">Genus</th><td align="left"><em>Popenaias (1)</em></td></tr> </tbody> </table> <h2><img src="/rimg/factsheet/Status.png" class="heading" /></h2><p class="Status"><p>Classified as Critically Endangered (CR) on the IUCN Red List (1).</p></p><h2><img src="/rimg/factsheet/Description.png" class="heading" /></h2><p class="Description"><p>Information on the Texas hornshell is currently being researched and written and will appear here shortly.</p></p><h2><img src="/rimg/factsheet/Authentication.png" class="heading" /></h2><p class="AuthenticatioModel">This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact: <a href="mailto:arkive@wildscreen.org.uk">arkive@wildscreen.org.uk</a></p><h2><img src="/rimg/factsheet/References.png" class="heading" /></h2> <ol id="references"> <li id="ref1"> <a id="reference_1" name="reference_1"></a> IUCN Red List (September, 2009) <br/><a href="http://www.iucnredlist.org" target="_blank">http://www.iucnredlist.org</a></li> </ol> </div> </div> </body> </html>
{ "content_hash": "0313718b19e996866ba0a4723c8ecb4a", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 770, "avg_line_length": 72.41025641025641, "alnum_prop": 0.6643059490084986, "repo_name": "andrewedstrom/cs638project", "id": "906b8429ee2fa7577daed3ea32750ddf04ee5f9a", "size": "2826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raw_data/arkive-critically-endangered-html/popenaias-popeii.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "514473381" }, { "name": "Jupyter Notebook", "bytes": "2192214" }, { "name": "Python", "bytes": "30115" }, { "name": "R", "bytes": "9081" } ], "symlink_target": "" }
layout: single --- {% include base_path %} <!doctype html> <html> {{content}} </html>
{ "content_hash": "39dd8d0eff5523a6239a8d41ba6ad6f5", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 23, "avg_line_length": 7.583333333333333, "alnum_prop": 0.5824175824175825, "repo_name": "tgquintela/tgquintela.github.io", "id": "459c25ff52e5a3e770867ede5201a5ae7e99c2ee", "size": "95", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_layouts/post.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "135525" }, { "name": "Dockerfile", "bytes": "412" }, { "name": "HTML", "bytes": "4179115" }, { "name": "JavaScript", "bytes": "130610" }, { "name": "Jupyter Notebook", "bytes": "82792" }, { "name": "Python", "bytes": "9075" }, { "name": "Ruby", "bytes": "720" }, { "name": "SCSS", "bytes": "65881" } ], "symlink_target": "" }
<?php require 'function.php'; require 'functions.php'; function getConn(){ global $conn; $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "ws"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } return $conn; } function getUserFBLogin($email, $name, $sex, $picture, $birthday){ $conn = getConn(); $sql = "SELECT * from utente where email='{$email}'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { //user in db session_start(); if (!isset($_SESSION['email'])){ $_SESSION['email'] = $_POST['email']; while($row = mysqli_fetch_assoc($result)) { $_SESSION['name'] = $row["name"]; $_SESSION['surname'] = $row["surname"]; $_SESSION['sex'] = $row["sex"]; $_SESSION['picture'] = $row["imPath"]; $_SESSION['birthday'] = $row["birthday"]; $_SESSION['registrationDate'] = $row["registrationDate"]; $_SESSION['lastLogin'] = $row["lastLogin"]; $_SESSION['webPage'] = $row["webPage"]; } $now = (new \DateTime())->format('Y-m-d H:i:s'); updateLastLogin($email, $now); } // output data of each row /*while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["name"]. " - Name: " . $row["email"]. " " . $row["surname"]. "<br>"; }*/ } else { //insert user in db $now = (new \DateTime())->format('Y-m-d H:i:s'); $picture = urldecode($picture); insertFBUser($email, $name, $sex, $picture, $birthday, $now); session_start(); $_SESSION['email'] = $_POST['email']; $nameSurname = explode (" " ,$name); //people can have more than 1 name! $_SESSION['name'] = $nameSurname[0]; $_SESSION['surname'] = $nameSurname[1]; $_SESSION['sex'] = $sex; $_SESSION['picture'] = $picture; $_SESSION['birthday'] = $birthday; $_SESSION['registrationDate'] = $now; $_SESSION['lastLogin'] = $now; $_SESSION['webPage'] = ""; } mysqli_close($conn); } /** * @author Simone Romano */ function checkUserPassword($email, $password) { $conn = getConn(); $sql = "SELECT * from utente where email='{$email}'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { //user in db session_start(); if (!isset($_SESSION['email'])){ while($row = mysqli_fetch_assoc($result)) { $confirmed = $row['confirmed']; if ($confirmed == 0){ return -3; } $passwordInDb = $row['password']; $test = md5($password); if (md5($password)==$passwordInDb){ $_SESSION['email'] = $email; $_SESSION['name'] = $row["name"]; $_SESSION['surname'] = $row["surname"]; $_SESSION['sex'] = $row["sex"]; $_SESSION['picture'] = $row["imPath"]; $_SESSION['birthday'] = $row["birthday"]; $_SESSION['registrationDate'] = $row["registrationDate"]; $_SESSION['lastLogin'] = $row["lastLogin"]; $_SESSION['webPage'] = $row["webPage"]; $now = (new \DateTime())->format('Y-m-d H:i:s'); updateLastLogin($email, $now); } else{ mysqli_close($conn); return -1; } } } } else { //insert user in db mysqli_close($conn); return -2; } mysqli_close($conn); return 1; } /** * @author Simone Romano */ function updateLastLogin($email, $now){ $conn = getConn(); $sql = "UPDATE utente set lastLogin='{$now}' where email='{$email}'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); } /** * @author Simone Romano */ function updatePassword($email, $password){ $conn = getConn(); $password = md5($password); $sql = "UPDATE utente set password='{$password}' where email='{$email}'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); } /** * @author Simone Romano * Confirm user. */ function confirmUser($email){ $conn = getConn(); $sql = "UPDATE utente set confirmed='1' where email='{$email}'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); } /** * @author Amedeo Leo */ function getCategory($category = NULL) { $returnValues = array(); $conn = getConn(); if($category != NULL) { $sql = "SELECT * FROM category WHERE name = '$category'"; } else $sql = "SELECT * from category"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues[] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getCategories() { return getCategory(); } /** * @author Amedeo Leo */ function getCategoryById($idCategory) { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM category WHERE id = '$idCategory'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues[] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function insertCategory($name) { $conn = getConn(); $sql = "INSERT INTO category (name) VALUES ('$name')"; $result = mysqli_query($conn, $sql) or die("Insert failed"); return $result; /* restituisce sempre true */ } /** * @author Amedeo Leo */ function deleteCategory($name) { $conn = getConn(); $sql = "DELETE FROM category WHERE name='$name'"; $result = mysqli_query($conn, $sql) or die("Delete failed"); return $result; /* restituisce sempre true */ } /** * @author Amedeo Leo */ function getCategoriesOfIdea($idIdea) { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM hasCategory WHERE idIdea = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $category = getCategoryById($row['idCategory']); $returnValues[] = $category[0]['name']; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function insertIdea($name, $description, $idUser, $categories, $financier = NULL, $dateOfFinancing = NULL, $imPath, $urlVideo) { $date = getTimeAndDate(); $conn = getConn(); $sql = "INSERT INTO idea (nome, dateOfInsert, description, idUser, imPath, url_video) VALUES ('$name','$date','$description','$idUser', '$imPath', '$urlVideo')"; $result = mysqli_query($conn, $sql) or die ("Insert failed"); $idIdea = mysqli_insert_id($conn); $arrayOfIdCategories = array(); foreach($categories as $category){ $element = getCategory($category); $id = $element[0]['id']; $arrayOfIdCategories[] = $id; } $query = "INSERT INTO hasCategory (idCategory, idIdea) VALUES (?, '$idIdea')"; $stmt = mysqli_prepare($conn,$query); $stmt->bind_param("s", $one); mysqli_query($conn,"START TRANSACTION"); foreach ($arrayOfIdCategories as $one) { $stmt->execute(); } $stmt->close(); mysqli_query($conn,"COMMIT"); mysqli_close($conn); return $result; } /** * @author Amedeo Leo */ function isIdeaOfUser ($idUser, $idIdea) { $conn = getConn(); $sql = "SELECT * FROM idea WHERE id = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if($row['idUser'] == $idUser) { return true; } } return false; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function hasAlreadyFollower($idUser,$idIdea) { $conn = getConn(); $sql = "SELECT * FROM follow WHERE idIdea = '$idIdea'"; $result = mysqli_query($conn, $sql) or die("Query failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if($row['idUser'] == $idUser) { mysqli_close($conn); return true; } } return false; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function deleteFollower($idUser,$idIdea) { $conn = getConn(); $sql = "DELETe FROM follow WHERE idIdea = '$idIdea' AND idUser = '$idUser'" ; $result = mysqli_query($conn, $sql) or die("Delete failed"); mysqli_close($conn); return true; } /** * @author Amedeo Leo */ function insertFollower ($idUser, $idIdea) { if(isIdeaOfUser($idUser, $idIdea)) return NULL; if(hasAlreadyFollower($idUser, $idIdea)) return NULL; $date = getTimeAndDate(); $conn = getConn(); $sql = "INSERT INTO follow (idUser, idIdea, date) VALUES ('$idUser','$idIdea','$date')"; $result = mysqli_query($conn, $sql) or die("Insert failed"); mysqli_close($conn); return $result; } /** * @author Amedeo Leo */ function getFollowersByIdIdea($idIdea) { return getFollowers(NULL, $idIdea); } /** * @author Amedeo Leo */ function getIdeasFollowed($idUser) { return getFollowers($idUser); } /** * @author Amedeo Leo */ function getFollowers($idUser = NULL, $idIdea = NULL) { $returnValues = array(); $conn = getConn(); if($idUser == NULL && $idIdea == NULL) { $sql = "SELECT * FROM follow"; } else if($idUser != NULL && $idIdea == NULL) $sql = "SELECT * FROM follow WHERE idUser = '$idUser'"; else if($idUser == NULL && $idIdea != NULL) $sql = "SELECT * FROM follow WHERE idIdea = '$idIdea'"; else $sql = "SELECT * FROM follow WHERE (idIdea = '$idIdea' AND idUser = '$idUser')"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues[] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getThreeMaxFollow(){ $returnValues = array(); $conn = getConn(); $sql = "SELECT idIdea, COUNT( idIdea ) FROM follow GROUP BY idIdea ORDER BY COUNT( idIdea ) DESC LIMIT 3"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $imPath = getIdeaById($row['idIdea'])['Idea']['imPath']; $returnValues[] = $imPath; } } mysqli_close($conn); return $returnValues; } /** * @author Simone Romano **/ function getUserFollowers($email){ $returnValues = array(); $conn = getConn(); $sql = "Select count(*) from follow where idIdea in( SELECT id FROM idea WHERE idUser='{$email}')"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['count(*)']; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano **/ function getIdeaDescription($id){ $returnValues = array(); $conn = getConn(); $sql = "select description from idea where id={$id}"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['description']; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano **/ function getIdeaImPath($id){ $returnValues = array(); $conn = getConn(); $sql = "select imPath from idea where id={$id}"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['imPath']; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano **/ function getIdeaName($idIdea){ $returnValues = array(); $conn = getConn(); $toReturn = ""; $sql = "select nome from idea where id='{$idIdea}'"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['nome']; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano * Return the count of comments for idas of $email user. **/ function getCommentForUser($email){ $returnValues = array(); $conn = getConn(); $sql = "select count(*) from comment where idIdea in (select id from idea where idUser='{$email}')"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['count(*)']; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano * Return the list of user ideas ordered by number of followers. **/ function getUserIdeasOrderedByFollowers($email){ $returnValues = array(); $conn = getConn(); $sql = "select id from idea where idUser='{$email}'"; $result = mysqli_query($conn, $sql) or die("select failed"); $toReturn = array(); $i = 0; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $sql_followers = "select count(*) from follow where idIdea='{$row['id']}'"; $result_followers_num = mysqli_query($conn, $sql_followers) or die("select failed"); $followers_numb = 0; if (mysqli_num_rows($result_followers_num) > 0) { // output data of each row while($row_followers = mysqli_fetch_assoc($result_followers_num)) { $followers_numb = $row_followers['count(*)']; } } $record = array(); $record[0] = $row['id']; $record[1] = $followers_numb; $index = 0; for($j = 0; $j < sizeOf($toReturn); $j++) { if ($toReturn[$j][1] > $record[1]){ $index = $j; break; } } for($j = sizeOf($toReturn)-1; $j >= $index; $j--) { $toReturn[$j+1] = $toReturn[$j]; } $toReturn[$index] = $record; $i++; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano * Return the max number of follower of an idea. **/ function getMaxFollow(){ $conn = getConn(); $sql = "select max(countIdea) from ( select idIdea,count(idIdea) as countIdea from follow group by idIdea ) as maxFollow"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $toReturn = $row['max(countIdea)']; } } mysqli_close($conn); return $toReturn; } /** * @author Amedeo Leo */ function getIdeaScores($idIdea){ $conn = getConn(); $toReturn = array(); $sql = "select sum(score_neg),sum(score_neu),sum(score_pos) from comment where idIdea='{$idIdea}'"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $toReturn['pos'] = $row['sum(score_pos)']; $toReturn['neg'] = $row['sum(score_neg)']; $toReturn['neu'] = $row['sum(score_neu)']; } } $toReturn['pos'] = ( $toReturn['pos'] * 10 ) / getMaxScore(); $toReturn['neg'] = ( $toReturn['neg'] * 10 ) / getMaxScore(); $toReturn['neu'] = ( $toReturn['neu'] * 10 ) / getMaxScore(); mysqli_close($conn); return $toReturn; } /** * @author Amedeo Leo */ function getMaxScore() { $conn = getConn(); $neg = 0; $pos = 0; $neu = 0; $sql = "SELECT SUM(score_neg) FROM COMMENT GROUP BY idIdea HAVING SUM( score_neg ) >0 ORDER BY SUM( score_neg ) DESC LIMIT 1"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $neg = $row['SUM(score_neg)']; } } $sql = "SELECT SUM(score_pos) FROM COMMENT GROUP BY idIdea HAVING SUM( score_pos ) >0 ORDER BY SUM( score_pos ) DESC LIMIT 1"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $pos = $row['SUM(score_pos)']; } } $sql = "SELECT SUM(score_neu) FROM COMMENT GROUP BY idIdea HAVING SUM( score_neu ) >0 ORDER BY SUM( score_neu ) DESC LIMIT 1"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $neu = $row['SUM(score_neu)']; } } mysqli_close($conn); return max($neu,$neg,$pos); } /** * @author Simone Romano * Return the count user's ideas. **/ function getUserIdeasCount($email){ $returnValues = array(); $conn = getConn(); $sql = "select count(*) from idea where idUser='{$email}'"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['count(*)']; } } mysqli_close($conn); return $toReturn; } /** * @author Simone Romano * Return last user activities. **/ function getLastUserActivities($email){ $returnValues = array(); $conn = getConn(); $sql = "select date,text,idIdea,'comment' as type from comment where idUser='{$email}' union all select date,idIdea,idUser,'follow' as type from follow where idUser='{$email}' union all select dateOfFinancing,id,idUser,'financier' as type from idea where financier='{$email}' union all select dateOfInsert,nome,id,'insert' as type from idea where idUser='{$email}' order by date;"; $result = mysqli_query($conn, $sql) or die("select failed"); mysqli_close($conn); return $result; } /** * @author Simone Romano * Return the count of financiers for idas of $email user. **/ function getUserFinancier($email){ $returnValues = array(); $conn = getConn(); $sql = "select count(*) from idea where idUser='{$email}' and financier is not null"; $result = mysqli_query($conn, $sql) or die("select failed"); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { //echo "id: " . $row["id"]. " - Name: " . $row["name"] . "<br>"; $toReturn = $row['count(*)']; } } mysqli_close($conn); return $toReturn; } /** * @author Amedeo Leo */ function insertComment ($idUser, $idIdea, $text, $score) { $date = getTimeAndDate(); $conn = getConn(); $sql = "INSERT INTO comment (idIdea, idUser, date, text, score_dom, score_neg, score_neu, score_pos) VALUES ('$idIdea','$idUser','$date','$text', '{$score['dom']}','{$score['neg']}','{$score['neu']}','{$score['pos']}')"; $result = mysqli_query($conn, $sql) or die("Insert failed"); mysqli_close($conn); return $result; } /** * @author Amedeo Leo */ function getCommentsByIdIdea($idIdea) { return getComments(NULL, $idIdea); } /** * @author Amedeo Leo */ function getUserComments($idUser) { return getComments($idUser, NULL); } /** * @author Amedeo Leo */ function getComments($idUser = NULL, $idIdea = NULL) { $returnValues = array(); $conn = getConn(); if($idUser == NULL && $idIdea == NULL) { $sql = "SELECT * FROM comment"; } else if($idUser != NULL && $idIdea == NULL) { $sql = "SELECT * FROM comment WHERE idUser = '$idUser'"; } else if($idUser == NULL && $idIdea != NULL) { $sql = "SELECT * FROM comment WHERE idIdea = '$idIdea' ORDER BY date DESC"; } else { $sql = "SELECT * FROM comment WHERE (idIdea = '$idIdea' AND idUser = '$idUser')"; } $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues[] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getIdeaById($idIdea) { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM idea WHERE id = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues['Idea'] = $row; } mysqli_close($conn); $returnValues['User'] = getUserOfIdea($idIdea); $returnValues['Followers'] = getFollowersByIdIdea($idIdea); $returnValues['Comments'] = getCommentsByIdIdea($idIdea); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getUserOfIdea($idIdea) { $returnValues = array(); $conn = getConn(); $sql = "SELECT idUser FROM idea WHERE id = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $idUser = $row['idUser']; } } else { mysqli_close($conn); return NULL; } $sql_user = "SELECT * FROM utente WHERE email = '$idUser'"; $result_user = mysqli_query($conn, $sql_user); if (mysqli_num_rows($result_user) > 0) { while($row_user = mysqli_fetch_assoc($result_user)) { $returnValues = $row_user; } return $returnValues; } else { mysqli_close($conn); return NULL; } mysqli_close($conn); } /** * @author Amedeo Leo */ function getNumberOfComments($idIdea) { $comments = getCommentsByIdIdea($idIdea); return count($comments); } /** * @author Amedeo Leo */ function getNumberOfFollowers($idIdea) { $followers = getFollowersByIdIdea($idIdea); return count($followers); } /** * @author Amedeo Leo */ function hasFinancier($idIdea) { $idea = getIdeaById($idIdea); if($idea['Idea']['financier'] == NULL) return false; return true; } /** * @author Amedeo Leo */ function insertFinancier($idIdea, $idFinancier) { $date = getTimeAndDate(); $idea = getIdeaById($idIdea); if($idea['Idea']['idUser'] == $idFinancier) return "Non puoi finanziare una tua idea"; else if($idea['Idea']['financier'] != NULL) return "Quest'idea ha già un finanziatore"; else { $conn = getConn(); $sql = "UPDATE idea SET financier = '$idFinancier', dateOfFinancing = '$date' WHERE id = '$idIdea'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); return "ok"; } } /** * @author Amedeo Leo */ function getNumberOfUserIdeas($idUser) { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM idea WHERE idUser = '$idUser'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); return count($result); } /** * @author Amedeo Leo */ function getUserById($idUser) { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM utente WHERE email = '$idUser'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues['User'] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getPointsForIdeaComments($idIdea, $score) { $return = 0; $conn = getConn(); $sql = "SELECT * FROM comment where idIdea = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if(!isCommentOfOwner($row['idUser'],$idIdea)) { $return = $return + $row[$score]; } } } return $return; mysqli_close($conn); } /** * @author Amedeo Leo */ function getPointsForIdeaCommentsForLastWeek($idIdea, $score) { $conn = getConn(); $today = strtotime(getTimeAndDate()); $ts = $today; // calculate the number of days since Monday $dow = date('w', $ts); $offset = $dow - 1; if ($offset < 0) { $offset = 6; } // calculate timestamp for the Monday $ts = $ts - $offset*86400; // loop from Monday till Sunday //$comments = array(); $return = 0; for ($i = 1; $i <= 7; $i++, $ts += 86400){ $current_date = date("d-m-Y", $ts); $sql = "SELECT * FROM comment where idIdea = '$idIdea' ORDER BY date DESC"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if(!isCommentOfOwner($row['idUser'],$idIdea)) { $comment_date = fromTimestampToDate(strtotime($row['date'])); if($comment_date == $current_date) { $return = $return + $row[$score]; } } } } } mysqli_close($conn); return $return; } /** * @author Amedeo Leo */ function getNumberOfCommentsOfIdea($idIdea) { $conn = getConn(); $return = 0; $sql = "SELECT count(*) AS cnt, idUser FROM comment where idIdea = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if(!isCommentOfOwner($row['idUser'],$idIdea)) { $return = $row['cnt']; } } } mysqli_close($conn); return $return; } /** * @author Amedeo Leo */ function getNumberOfCommentsOfLastWeekByIdIdea($idIdea) { $conn = getConn(); $today = strtotime(getTimeAndDate()); $ts = $today; // calculate the number of days since Monday $dow = date('w', $ts); $offset = $dow - 1; if ($offset < 0) { $offset = 6; } // calculate timestamp for the Monday $ts = $ts - $offset*86400; // loop from Monday till Sunday $comments = array(); for ($i = 1; $i <= 7; $i++, $ts += 86400){ $current_date = date("d-m-Y", $ts); $sql = "SELECT * FROM comment where idIdea = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if(!isCommentOfOwner($row['idUser'],$idIdea)) { $comment_date = fromTimestampToDate(strtotime($row['date'])); if($comment_date == $current_date) { $comments[$i][] = $row; } } } } } $return = 0; for($i = 1; $i <= 7; $i++) { if(!empty($comments[$i])) { foreach((array)$comments[$i] as $comment) { $return++; } } } mysqli_close($conn); return $return; } /** * @author Amedeo Leo */ function getTotalScoreOfLastWeekByIdIdea($idIdea) { $conn = getConn(); $today = strtotime(getTimeAndDate()); $ts = $today; // calculate the number of days since Monday $dow = date('w', $ts); $offset = $dow - 1; if ($offset < 0) { $offset = 6; } // calculate timestamp for the Monday $ts = $ts - $offset*86400; // loop from Monday till Sunday $comments = array(); for ($i = 1; $i <= 7; $i++, $ts += 86400){ $current_date = date("d-m-Y", $ts); $sql = "SELECT * FROM comment where idIdea = '$idIdea'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { if(!isCommentOfOwner($row['idUser'],$idIdea)) { $comment_date = fromTimestampToDate(strtotime($row['date'])); if($comment_date == $current_date) { $comments[$i][]= $row; } } } } } $return = 0; for($i = 1; $i <= 7; $i++) { if(!empty($comments[$i])) { foreach((array)$comments[$i] as $comment) { $return = $return + $comment['Score']; } } } mysqli_close($conn); return $return; } /** * @author Amedeo Leo */ function isCommentOfOwner($idUser, $idIdea) { $user = getUserOfIdea($idIdea); if($idUser == $user['email']) return true; return false; } /** * @author Amedeo Leo */ function getIdeas() { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM idea"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues['Idea'] = $row; } mysqli_close($conn); $returnValues['User'] = getUserOfIdea($returnValues['Idea']['id']); $returnValues['Followers'] = getFollowersByIdIdea($returnValues['Idea']['id']); $returnValues['Comments'] = getCommentsByIdIdea($returnValues['Idea']['id']); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getIdeasByCategory($category) { $returnValues = array(); $conn = getConn(); $idCategory = getCategory($category)[0]['id']; $sql = "SELECT * FROM hasCategory WHERE idCategory = '$idCategory'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues[] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getIdeasOrderedByFollowers(){ $returnValues = array(); $conn = getConn(); $sql = "select id from idea"; $result = mysqli_query($conn, $sql) or die("select failed"); $toReturn = array(); $i = 0; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $sql_followers = "select count(*) from follow where idIdea='{$row['id']}'"; $result_followers_num = mysqli_query($conn, $sql_followers) or die("select failed"); $followers_numb = 0; if (mysqli_num_rows($result_followers_num) > 0) { while($row_followers = mysqli_fetch_assoc($result_followers_num)) { $followers_numb = $row_followers['count(*)']; } } $record = array(); $record[0] = $row['id']; $record[1] = $followers_numb; $index = 0; for($j = 0; $j < sizeOf($toReturn); $j++) { if ($toReturn[$j][1] > $record[1]){ $index = $j; break; } } for($j = sizeOf($toReturn)-1; $j >= $index; $j--) { $toReturn[$j+1] = $toReturn[$j]; } $toReturn[$index] = $record; $i++; } } mysqli_close($conn); return $toReturn; } /** * @author Amedeo Leo */ function getIdeasOrderedByFollowersByCategory($category = NULL){ $returnValues = array(); $conn = getConn(); if($category == NULL) $sql = "SELECT id FROM idea WHERE id IN ( SELECT idIdea FROM hasCategory)"; else { $category = getCategory($category)[0]['id']; $sql = "SELECT id FROM idea WHERE id IN ( SELECT idIdea FROM hasCategory WHERE idCategory = '$category')"; } $result = mysqli_query($conn, $sql) or die("select failed"); $toReturn = array(); $i = 0; if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $sql_followers = "select count(*) from follow where idIdea='{$row['id']}'"; $result_followers_num = mysqli_query($conn, $sql_followers) or die("select failed"); $followers_numb = 0; if (mysqli_num_rows($result_followers_num) > 0) { while($row_followers = mysqli_fetch_assoc($result_followers_num)) { $followers_numb = $row_followers['count(*)']; } } $record = array(); $record[0] = $row['id']; $record[1] = $followers_numb; $index = 0; for($j = 0; $j < sizeOf($toReturn); $j++) { if ($toReturn[$j][1] > $record[1]){ $index = $j; break; } } for($j = sizeOf($toReturn)-1; $j >= $index; $j--) { $toReturn[$j+1] = $toReturn[$j]; } $toReturn[$index] = $record; $i++; } } mysqli_close($conn); return $toReturn; } /** * @author Amedeo Leo */ function sendMail($mail_destinatario, $mail_oggetto, $title, $body) { $nome_mittente = "OpenIdeas"; $mail_mittente = ""; $mail_corpo = <<<HTML <html> <head> <title>{$title}</title> </head> <body> {$body} </body> </html> HTML; $mail_headers = "From: " . $nome_mittente . " <" . $mail_mittente . ">\r\n"; $mail_headers .= "Reply-To: " . $mail_mittente . "\r\n"; $mail_headers .= "X-Mailer: PHP/" . phpversion() . "\r\n"; $mail_headers .= "MIME-Version: 1.0\r\n"; $mail_headers .= "Content-type: text/html; charset=iso-8859-1"; if (mail($mail_destinatario, $mail_oggetto, $mail_corpo, $mail_headers)) return "Messaggio inviato con successo a " . $mail_destinatario; else return "Errore. Nessun messaggio inviato."; } /** * @author Amedeo Leo */ function insertNotice($idDestinatario, $idIdea, $text, $type, $confirmed = 0) { $date = getTimeAndDate(); $conn = getConn(); $sql = "INSERT INTO notice (idDestinatario, idIdea, date, text, type, confirmed) VALUES ('$idDestinatario','$idIdea','$date','$text', '$type', '$confirmed')"; $result = mysqli_query($conn, $sql) or die ("Insert failed"); return $result; } /** * @author Amedeo Leo */ function getWritersOfIdea($idIdea) { $toReturn = array(); $comments = getCommentsByIdIdea($idIdea); if($comments == NULL) return NULL; else { foreach($comments as $comment) { if(!in_array($comment['idUser'], $toReturn)) { $toReturn[] = $comment['idUser']; } } } return $toReturn; } /** * @author Amedeo Leo */ function getNoticesOfUser($idUser) { $returnValues = array(); $conn = getConn(); $sql = "SELECT * FROM notice WHERE idDestinatario = '$idUser' AND confirmed = 0"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues[] = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function getNoticeById($idNotice) { $returnValues; $conn = getConn(); $sql = "SELECT * FROM notice WHERE idNotice = '$idNotice'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $returnValues = $row; } mysqli_close($conn); return $returnValues; } else { mysqli_close($conn); return NULL; } } /** * @author Amedeo Leo */ function updateAllNoticesOfUSer($idDestinatario, $confirmed = 1) { $conn = getConn(); $sql = "UPDATE notice SET confirmed = 1 WHERE idDestinatario = '$idDestinatario'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); return "ok"; } /** * @author Amedeo Leo */ function updateNotice($idDestinatario, $idIdea, $date, $text, $type, $confirmed = 1) { $conn = getConn(); $sql = "UPDATE notice SET confirmed = '$confirmed' WHERE idIdea = '$idIdea' AND idDestinatario = '$idDestinatario' AND date='$date' AND text='$text' AND type='$type'"; $result = mysqli_query($conn, $sql); mysqli_close($conn); return "ok"; } /** * @author Simone Romano */ function insertFBUser($email, $name, $sex, $picture, $birthday, $now){ $conn = getConn(); $nameSurname = explode (" " ,$name); //people can have more than 1 name! $name = $nameSurname[0]; $surname = $nameSurname[1]; $sql = "INSERT INTO utente(name,surname,dateOfBirth,email,sex,imPath,confirmed,lastLogin,registrationDate) values('{$name}','${surname}','{$birthday}','{$email}','{$sex}','{$picture}','1','{$now}','{$now}')"; $result = mysqli_query($conn, $sql); mysqli_close($conn); } /** * @author Simone Romano * Register new User into system **/ function insertUser($email,$password, $name, $surname, $picture, $birthday, $webPage){ $conn = getConn(); $validationCode = md5($email . $name); $nameSurname = explode (" " ,$name); $now = (new \DateTime())->format('Y-m-d H:i:s'); //check user already in db $sql = "select confirmed from utente where email='{$email}'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $confirmed = $row['confirmed']; if ($confirmed == 1){ mysqli_close($conn); return -1; } else{ mysqli_close($conn); return -2; } } } $password = md5($password); $sql = "INSERT INTO utente(name,surname,dateOfBirth,webPage,email,password,imPath,confirmed,registrationDate,validationCode) values('{$name}','${surname}','{$birthday}','{$webPage}','{$email}','{$password}','{$picture}','0','{$now}', '{$validationCode}')"; $result = mysqli_query($conn, $sql); mysqli_close($conn); //send confirmation email $validationLink = "<a href='http://localhost/WebSemantico/OpenIdeas/validation.php?email={$email}&name={$name}'>Conferma</a></body></html>"; // definisco mittente e destinatario della mail $nome_mittente = "OpenIdeas"; $mail_mittente = ""; $mail_destinatario = "{$email}"; // definisco il subject $mail_oggetto = "Registrazione"; // definisco il messaggio formattato in HTML $mail_corpo = <<<HTML <html> <head> <title>Registrazione al portale OpenIdeas</title> </head> <body> La tua registrazione al portale <a href='http://localhost/WebSemantico/OpenIdeas/index.php'>OpenIdeas</a> è quasi completa. Clicca al link seguente per confermare<br> {$validationLink} </body> </html> HTML; // aggiusto un po' le intestazioni della mail // E' in questa sezione che deve essere definito il mittente (From) // ed altri eventuali valori come Cc, Bcc, ReplyTo e X-Mailer $mail_headers = "From: " . $nome_mittente . " <" . $mail_mittente . ">\r\n"; $mail_headers .= "Reply-To: " . $mail_mittente . "\r\n"; $mail_headers .= "X-Mailer: PHP/" . phpversion() . "\r\n"; // Aggiungo alle intestazioni della mail la definizione di MIME-Version, // Content-type e charset (necessarie per i contenuti in HTML) $mail_headers .= "MIME-Version: 1.0\r\n"; $mail_headers .= "Content-type: text/html; charset=iso-8859-1"; if (mail($mail_destinatario, $mail_oggetto, $mail_corpo, $mail_headers)) echo "Messaggio inviato con successo a " . $mail_destinatario; else echo "Errore. Nessun messaggio inviato."; } /** * @author Simone Romano * Validate user registration **/ function checkValidation($email, $name){ $conn = getConn(); $validationCode = md5($email . $name); $now = (new \DateTime())->format('Y-m-d H:i:s'); $sql = "select validationCode from utente where email='{$email}'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { $validationCodeInDb = $row['validationCode']; echo"{$validationCode} {$validationCodeInDb}"; if ($validationCode == $validationCodeInDb){ return true; } else return false; } } return false; mysqli_close($conn); } ?>
{ "content_hash": "311c97cfa495d61ebd1f6cfbd4e57cb2", "timestamp": "", "source": "github", "line_count": 1484, "max_line_length": 264, "avg_line_length": 32.96630727762803, "alnum_prop": 0.4679898614120437, "repo_name": "sromano1992/OpenIdeas", "id": "b35a2eb9d8107dc66b3ea80e952f7cb200086acf", "size": "48922", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "manageDB.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "130778" }, { "name": "HTML", "bytes": "14247" }, { "name": "JavaScript", "bytes": "48254" }, { "name": "PHP", "bytes": "1472266" }, { "name": "Web Ontology Language", "bytes": "1606" } ], "symlink_target": "" }
var gui = require('nw.gui'); var win = gui.Window.get(); var maximized = true; win.maximize(); document.getElementById("btn-max").onclick = function(){ if(!maximized){ win.maximize(); maximized = true; } else{ win.unmaximize(); maximized = false; } } document.getElementById("btn-min").onclick = function(){ win.minimize(); } document.getElementById("btn-close").onclick = function(){ win.close(); } function supportExternalLinks(event) { var href; var isExternal = false; function crawlDom(element) { if (element.nodeName.toLowerCase() === 'a') { href = element.getAttribute('href'); } if (element.classList.contains('js-external-link')) { isExternal = true; } if (href && isExternal) { gui.Shell.openExternal(href); event.preventDefault(); } else if (element.parentElement) { crawlDom(element.parentElement); } } crawlDom(event.target); } document.body.addEventListener('click', supportExternalLinks, false);
{ "content_hash": "27f46805e26af9680e13033abe74e90b", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 69, "avg_line_length": 19.596153846153847, "alnum_prop": 0.647693817468106, "repo_name": "kurai021/MDWriter", "id": "200bddd2464b5a77d8be673618a2545de1456655", "size": "1019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/assets/js/window.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7634" }, { "name": "HTML", "bytes": "43446" }, { "name": "JavaScript", "bytes": "44922" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ru" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About JohnKeyoin</source> <translation>&amp;О JohnKeyoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;JohnKeyoin&lt;/b&gt; version</source> <translation>&lt;b&gt;JohnKeyoin&lt;/b&gt; версия</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Это экспериментальная программа. Распространяется на правах лицензии MIT/X11, см. файл license.txt или http://www.opensource.org/licenses/mit-license.php. Этот продукт включает ПО, разработанное OpenSSL Project для использования в OpenSSL Toolkit (http://www.openssl.org/) и криптографическое ПО, написанное Eric Young (eay@cryptsoft.com) и ПО для работы с UPnP, написанное Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Все права защищены</translation> </message> <message> <location line="+0"/> <source>The JohnKeyoin developers</source> <translation>Разработчики JohnKeyoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>&amp;Адресная книга</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Для того, чтобы изменить адрес или метку, дважды кликните по изменяемому объекту</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Создать новый адрес</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Копировать текущий выделенный адрес в буфер обмена</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Новый адрес</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your JohnKeyoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Это Ваши адреса для получения платежей. Вы можете дать разные адреса отправителям, чтобы отслеживать, кто именно вам платит.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Копировать адрес</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Показать &amp;QR код</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a JohnKeyoin address</source> <translation>Подписать сообщение, чтобы доказать владение адресом JohnKeyoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>&amp;Подписать сообщение</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Удалить выбранный адрес из списка</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Экспортировать данные из вкладки в файл</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Экспорт</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified JohnKeyoin address</source> <translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом JohnKeyoin</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Проверить сообщение</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Удалить</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your JohnKeyoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Ваши адреса для получения средств. Совет: проверьте сумму и адрес назначения перед переводом.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Копировать &amp;метку</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Правка</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>&amp;Отправить монеты</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Экспортировать адресную книгу</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Текст, разделённый запятыми (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Ошибка экспорта</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Невозможно записать в файл %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Метка</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адрес</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>[нет метки]</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Диалог ввода пароля</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Введите пароль</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Новый пароль</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Повторите новый пароль</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Введите новый пароль для бумажника. &lt;br/&gt; Пожалуйста, используйте фразы из &lt;b&gt;10 или более случайных символов,&lt;/b&gt; или &lt;b&gt;восьми и более слов.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Зашифровать бумажник</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Для выполнения операции требуется пароль вашего бумажника.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Разблокировать бумажник</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Для выполнения операции требуется пароль вашего бумажника.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Расшифровать бумажник</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Сменить пароль</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Введите старый и новый пароль для бумажника.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Подтвердите шифрование бумажника</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Внимание: если вы зашифруете бумажник и потеряете пароль, вы &lt;b&gt;ПОТЕРЯЕТЕ ВСЕ ВАШИ JohnKeyoin&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Вы уверены, что хотите зашифровать ваш бумажник?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>ВАЖНО: все предыдущие резервные копии вашего кошелька должны быть заменены новым зашифрованным файлом. В целях безопасности предыдущие резервные копии нешифрованного кошелька станут бесполезны, как только вы начнёте использовать новый шифрованный кошелёк.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Внимание: Caps Lock включен!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Бумажник зашифрован</translation> </message> <message> <location line="-56"/> <source>JohnKeyoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your johnkeyoins from being stolen by malware infecting your computer.</source> <translation>Сейчас программа закроется для завершения процесса шифрования. Помните, что шифрование вашего бумажника не может полностью защитить ваши JohnKeyoin от кражи с помощью инфицирования вашего компьютера вредоносным ПО.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Не удалось зашифровать бумажник</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Шифрование бумажника не удалось из-за внутренней ошибки. Ваш бумажник не был зашифрован.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Введённые пароли не совпадают.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Разблокировка бумажника не удалась</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Указанный пароль не подходит.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Расшифрование бумажника не удалось</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Пароль бумажника успешно изменён.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>&amp;Подписать сообщение...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Синхронизация с сетью...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>О&amp;бзор</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Показать общий обзор действий с бумажником</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Транзакции</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Показать историю транзакций</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Изменить список сохранённых адресов и меток к ним</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Показать список адресов для получения платежей</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>В&amp;ыход</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Закрыть приложение</translation> </message> <message> <location line="+4"/> <source>Show information about JohnKeyoin</source> <translation>Показать информацию о JohnKeyoin&apos;е</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>О &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Показать информацию о Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>Оп&amp;ции...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Зашифровать бумажник...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Сделать резервную копию бумажника...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Изменить пароль...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Импортируются блоки с диска...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Идёт переиндексация блоков на диске...</translation> </message> <message> <location line="-347"/> <source>Send coins to a JohnKeyoin address</source> <translation>Отправить монеты на указанный адрес JohnKeyoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for JohnKeyoin</source> <translation>Изменить параметры конфигурации JohnKeyoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Сделать резервную копию бумажника в другом месте</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Изменить пароль шифрования бумажника</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Окно отладки</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Открыть консоль отладки и диагностики</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Проверить сообщение...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>JohnKeyoin</source> <translation>JohnKeyoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Бумажник</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Отправить</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Получить</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Адреса</translation> </message> <message> <location line="+22"/> <source>&amp;About JohnKeyoin</source> <translation>&amp;О JohnKeyoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Показать / Скрыть</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Показать или скрыть главное окно</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Зашифровать приватные ключи, принадлежащие вашему бумажнику</translation> </message> <message> <location line="+7"/> <source>Sign messages with your JohnKeyoin addresses to prove you own them</source> <translation>Подписать сообщения вашим адресом JohnKeyoin, чтобы доказать, что вы им владеете</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified JohnKeyoin addresses</source> <translation>Проверить сообщения, чтобы удостовериться, что они были подписаны определённым адресом JohnKeyoin</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Настройки</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Помощь</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Панель вкладок</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[тестовая сеть]</translation> </message> <message> <location line="+47"/> <source>JohnKeyoin client</source> <translation>JohnKeyoin клиент</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to JohnKeyoin network</source> <translation><numerusform>%n активное соединение с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform><numerusform>%n активных соединений с сетью</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Источник блоков недоступен...</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Обработано %1 из %2 (примерно) блоков истории транзакций.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Обработано %1 блоков истории транзакций.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n час</numerusform><numerusform>%n часа</numerusform><numerusform>%n часов</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n день</numerusform><numerusform>%n дня</numerusform><numerusform>%n дней</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n неделя</numerusform><numerusform>%n недели</numerusform><numerusform>%n недель</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 позади</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Последний полученный блок был сгенерирован %1 назад.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Транзакции после этой пока не будут видны.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Ошибка</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Внимание</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Информация</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Транзакция превышает максимальный размер. Вы можете провести её, заплатив комиссию %1, которая достанется узлам, обрабатывающим эту транзакцию, и поможет работе сети. Вы действительно хотите заплатить комиссию?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Синхронизировано</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Синхронизируется...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Подтвердите комиссию</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Исходящая транзакция</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Входящая транзакция</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Дата: %1 Количество: %2 Тип: %3 Адрес: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Обработка URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid JohnKeyoin address or malformed URI parameters.</source> <translation>Не удалось обработать URI! Это может быть связано с неверным адресом JohnKeyoin или неправильными параметрами URI.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Бумажник &lt;b&gt;зашифрован&lt;/b&gt; и в настоящее время &lt;b&gt;разблокирован&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Бумажник &lt;b&gt;зашифрован&lt;/b&gt; и в настоящее время &lt;b&gt;заблокирован&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. JohnKeyoin can no longer continue safely and will quit.</source> <translation>Произошла неисправимая ошибка. JohnKeyoin не может безопасно продолжать работу и будет закрыт.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Сетевая Тревога</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Изменить адрес</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Метка</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Метка, связанная с данной записью</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Адрес</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Адрес, связанный с данной записью.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Новый адрес для получения</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Новый адрес для отправки</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Изменение адреса для получения</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Изменение адреса для отправки</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Введённый адрес «%1» уже находится в адресной книге.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid JohnKeyoin address.</source> <translation>Введённый адрес &quot;%1&quot; не является правильным JohnKeyoin-адресом.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Не удается разблокировать бумажник.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Генерация нового ключа не удалась.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>JohnKeyoin-Qt</source> <translation>JohnKeyoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>версия</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Использование:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>параметры командной строки</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Опции интерфейса</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Выберите язык, например &quot;de_DE&quot; (по умолчанию: как в системе)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Запускать свёрнутым</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Показывать сплэш при запуске (по умолчанию: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Опции</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Главная</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Необязательная комиссия за каждый КБ транзакции, которая ускоряет обработку Ваших транзакций. Большинство транзакций занимают 1КБ.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Заплатить ко&amp;миссию</translation> </message> <message> <location line="+31"/> <source>Automatically start JohnKeyoin after logging in to the system.</source> <translation>Автоматически запускать JohnKeyoin после входа в систему</translation> </message> <message> <location line="+3"/> <source>&amp;Start JohnKeyoin on system login</source> <translation>&amp;Запускать JohnKeyoin при входе в систему</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Сбросить все опции клиента на значения по умолчанию.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Сбросить опции</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Сеть</translation> </message> <message> <location line="+6"/> <source>Automatically open the JohnKeyoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Автоматически открыть порт для JohnKeyoin-клиента на роутере. Работает только если Ваш роутер поддерживает UPnP, и данная функция включена.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Пробросить порт через &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the JohnKeyoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Подключаться к сети JohnKeyoin через прокси SOCKS (например, при подключении через Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Подключаться через SOCKS прокси:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP Прокси: </translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>IP-адрес прокси (например 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>По&amp;рт: </translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Порт прокси-сервера (например, 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Версия SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Версия SOCKS-прокси (например, 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Окно</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Показывать только иконку в системном лотке после сворачивания окна.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Cворачивать в системный лоток вместо панели задач</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Сворачивать вместо закрытия. Если данная опция будет выбрана — приложение закроется только после выбора соответствующего пункта в меню.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>С&amp;ворачивать при закрытии</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>О&amp;тображение</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Язык интерфейса:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting JohnKeyoin.</source> <translation>Здесь можно выбрать язык интерфейса. Настройки вступят в силу после перезапуска JohnKeyoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Отображать суммы в единицах: </translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Выберите единицу измерения монет при отображении и отправке.</translation> </message> <message> <location line="+9"/> <source>Whether to show JohnKeyoin addresses in the transaction list or not.</source> <translation>Показывать ли адреса JohnKeyoin в списке транзакций.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Показывать адреса в списке транзакций</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>О&amp;К</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Отмена</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Применить</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>по умолчанию</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Подтвердите сброс опций</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Некоторые настройки могут потребовать перезапуск клиента, чтобы вступить в силу.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Желаете продолжить?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Внимание</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting JohnKeyoin.</source> <translation>Эта настройка вступит в силу после перезапуска JohnKeyoin</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Адрес прокси неверен.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the JohnKeyoin network after a connection is established, but this process has not completed yet.</source> <translation>Отображаемая информация может быть устаревшей. Ваш бумажник автоматически синхронизируется с сетью JohnKeyoin после подключения, но этот процесс пока не завершён.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Не подтверждено:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Бумажник</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Незрелые:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Баланс добытых монет, который ещё не созрел</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Последние транзакции&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Ваш текущий баланс</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Общая сумма всех транзакций, которые до сих пор не подтверждены, и до сих пор не учитываются в текущем балансе</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>не синхронизировано</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start johnkeyoin: click-to-pay handler</source> <translation>Не удаётся запустить JohnKeyoin: обработчик click-to-pay</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Диалог QR-кода</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Запросить платёж</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Количество:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Метка:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Сообщение:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Сохранить как...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Ошибка кодирования URI в QR-код</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Введено неверное количество, проверьте ещё раз.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Получившийся URI слишком длинный, попробуйте сократить текст метки / сообщения.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Сохранить QR-код</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG Изображения (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Имя клиента</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Н/Д</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Версия клиента</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Информация</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Используется версия OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Время запуска</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Сеть</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Число подключений</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>В тестовой сети</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Цепь блоков</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Текущее число блоков</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Расчётное число блоков</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Время последнего блока</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Открыть</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Параметры командной строки</translation> </message> <message> <location line="+7"/> <source>Show the JohnKeyoin-Qt help message to get a list with possible JohnKeyoin command-line options.</source> <translation>Показать помощь по JohnKeyoin-Qt, чтобы получить список доступных параметров командной строки.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Показать</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Дата сборки</translation> </message> <message> <location line="-104"/> <source>JohnKeyoin - Debug window</source> <translation>JohnKeyoin - Окно отладки</translation> </message> <message> <location line="+25"/> <source>JohnKeyoin Core</source> <translation>Ядро JohnKeyoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Отладочный лог-файл</translation> </message> <message> <location line="+7"/> <source>Open the JohnKeyoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Открыть отладочный лог-файл JohnKeyoin из текущего каталога данных. Это может занять несколько секунд для больших лог-файлов.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Очистить консоль</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the JohnKeyoin RPC console.</source> <translation>Добро пожаловать в RPC-консоль JohnKeyoin.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Используйте стрелки вверх и вниз для просмотра истории и &lt;b&gt;Ctrl-L&lt;/b&gt; для очистки экрана.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Напишите &lt;b&gt;help&lt;/b&gt; для просмотра доступных команд.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Отправка</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Отправить нескольким получателям одновременно</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Добавить получателя</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Удалить все поля транзакции</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Очистить &amp;всё</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Баланс:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Подтвердить отправку</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Отправить</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; адресату %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Подтвердите отправку монет</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Вы уверены, что хотите отправить %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> и </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Адрес получателя неверный, пожалуйста, перепроверьте.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Количество монет для отправки должно быть больше 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Количество отправляемых монет превышает Ваш баланс</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Сумма превысит Ваш баланс, если комиссия в размере %1 будет добавлена к транзакции</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Обнаружен дублирующийся адрес. Отправка на один и тот же адрес возможна только один раз за одну операцию отправки</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Ошибка: не удалось создать транзакцию!</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Ошибка: В транзакции отказано. Такое может произойти, если некоторые монеты уже были потрачены, например, если Вы используете одну копию файла wallet.dat, а монеты были потрачены из другой копии, но не были отмечены как потраченные в этой.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Ко&amp;личество:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Полу&amp;чатель:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Адрес, на который будет выслан платёж (например Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Введите метку для данного адреса (для добавления в адресную книгу)</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Метка:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Выберите адрес из адресной книги</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Вставить адрес из буфера обмена</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Удалить этого получателя</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a JohnKeyoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введите JohnKeyoin-адрес (например 1LA5FtQhnnWnkK6zjFfutR7Stiit4wKd63)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Подписи - подписать/проверить сообщение</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Подписать сообщение</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Вы можете подписывать сообщения своими адресами, чтобы доказать владение ими. Будьте осторожны, не подписывайте что-то неопределённое, так как фишинговые атаки могут обманным путём заставить вас подписать нежелательные сообщения. Подписывайте только те сообщения, с которыми вы согласны вплоть до мелочей.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Адрес, которым вы хотите подписать сообщение (напр. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Выберите адрес из адресной книги</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Вставить адрес из буфера обмена</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Введите сообщение для подписи</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Подпись</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Скопировать текущую подпись в системный буфер обмена</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this JohnKeyoin address</source> <translation>Подписать сообщение, чтобы доказать владение адресом JohnKeyoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Подписать &amp;Сообщение</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Сбросить значения всех полей подписывания сообщений</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Очистить &amp;всё</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Проверить сообщение</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Введите ниже адрес для подписи, сообщение (убедитесь, что переводы строк, пробелы, табы и т.п. в точности скопированы) и подпись, чтобы проверить сообщение. Убедитесь, что не скопировали лишнего в подпись, по сравнению с самим подписываемым сообщением, чтобы не стать жертвой атаки &quot;man-in-the-middle&quot;.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Адрес, которым было подписано сообщение (напр. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified JohnKeyoin address</source> <translation>Проверить сообщение, чтобы убедиться, что оно было подписано указанным адресом JohnKeyoin</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Проверить &amp;Сообщение</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Сбросить все поля проверки сообщения</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a JohnKeyoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Введите адрес JohnKeyoin (напр. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Нажмите &quot;Подписать сообщение&quot; для создания подписи</translation> </message> <message> <location line="+3"/> <source>Enter JohnKeyoin signature</source> <translation>Введите подпись JohnKeyoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Введённый адрес неверен</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Пожалуйста, проверьте адрес и попробуйте ещё раз.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Введённый адрес не связан с ключом</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Разблокировка бумажника была отменена.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Для введённого адреса недоступен закрытый ключ</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Не удалось подписать сообщение</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Сообщение подписано</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Подпись не может быть раскодирована.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Пожалуйста, проверьте подпись и попробуйте ещё раз.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Подпись не соответствует отпечатку сообщения.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Проверка сообщения не удалась.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Сообщение проверено.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The JohnKeyoin developers</source> <translation>Разработчики JohnKeyoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[тестовая сеть]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Открыто до %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/отключен</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/не подтверждено</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 подтверждений</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Статус</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, разослано через %n узел</numerusform><numerusform>, разослано через %n узла</numerusform><numerusform>, разослано через %n узлов</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Источник</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Сгенерированно</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>От</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Для</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>свой адрес</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>метка</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Кредит</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>будет доступно через %n блок</numerusform><numerusform>будет доступно через %n блока</numerusform><numerusform>будет доступно через %n блоков</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>не принято</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Дебет</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Комиссия</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Чистая сумма</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Сообщение</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Комментарий:</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID транзакции</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Сгенерированные монеты должны подождать 120 блоков, прежде чем они могут быть потрачены. Когда Вы сгенерировали этот блок, он был отправлен в сеть для добавления в цепочку блоков. Если данная процедура не удастся, статус изменится на «не подтверждено», и монеты будут недействительны. Это иногда происходит в случае, если другой узел сгенерирует блок на несколько секунд раньше вас.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Отладочная информация</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Транзакция</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Входы</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Количество</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>истина</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>ложь</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ещё не было успешно разослано</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Открыто для ещё %n блока</numerusform><numerusform>Открыто для ещё %n блоков</numerusform><numerusform>Открыто для ещё %n блоков</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>неизвестно</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Детали транзакции</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Данный диалог показывает детализированную статистику по выбранной транзакции</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Адрес</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Количество</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Открыто для ещё %n блока</numerusform><numerusform>Открыто для ещё %n блоков</numerusform><numerusform>Открыто для ещё %n блоков</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Открыто до %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Оффлайн (%1 подтверждений)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Не подтверждено (%1 из %2 подтверждений)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Подтверждено (%1 подтверждений)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Добытыми монетами можно будет воспользоваться через %n блок</numerusform><numerusform>Добытыми монетами можно будет воспользоваться через %n блока</numerusform><numerusform>Добытыми монетами можно будет воспользоваться через %n блоков</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Этот блок не был получен другими узлами и, возможно, не будет принят!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Сгенерированно, но не подтверждено</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Получено</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Получено от</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Отправлено</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Отправлено себе</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Добыто</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>[не доступно]</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Статус транзакции. Подведите курсор к нужному полю для того, чтобы увидеть количество подтверждений.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Дата и время, когда транзакция была получена.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Тип транзакции.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Адрес назначения транзакции.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Сумма, добавленная, или снятая с баланса.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Все</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Сегодня</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>На этой неделе</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>В этом месяце</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>За последний месяц</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>В этом году</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Промежуток...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Получено на</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Отправлено на</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Отправленные себе</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Добытые</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Другое</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Введите адрес или метку для поиска</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Мин. сумма</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Копировать адрес</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Копировать метку</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Скопировать сумму</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Скопировать ID транзакции</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Изменить метку</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Показать подробности транзакции</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Экспортировать данные транзакций</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Текст, разделённый запятыми (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Подтверждено</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Тип</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Метка</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Адрес</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Количество</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Ошибка экспорта</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Невозможно записать в файл %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Промежуток от:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>до</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Отправка</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Экспорт</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Экспортировать данные из вкладки в файл</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Сделать резервную копию бумажника</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Данные бумажника (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Резервное копирование не удалось</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>При попытке сохранения данных бумажника в новое место произошла ошибка.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Резервное копирование успешно завершено</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Данные бумажника успешно сохранены в новое место.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>JohnKeyoin version</source> <translation>Версия</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Использование:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or johnkeyoind</source> <translation>Отправить команду на -server или JohnKeyoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Список команд </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Получить помощь по команде</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Опции:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: johnkeyoin.conf)</source> <translation>Указать конфигурационный файл (по умолчанию: JohnKeyoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: johnkeyoind.pid)</source> <translation>Задать pid-файл (по умолчанию: JohnKeyoin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Задать каталог данных</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Установить размер кэша базы данных в мегабайтах (по умолчанию: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Принимать входящие подключения на &lt;port&gt; (по умолчанию: 9333 или 19333 в тестовой сети)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Поддерживать не более &lt;n&gt; подключений к узлам (по умолчанию: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Подключиться к узлу, чтобы получить список адресов других участников и отключиться</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Укажите ваш собственный публичный адрес</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Порог для отключения неправильно ведущих себя узлов (по умолчанию: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Число секунд блокирования неправильно ведущих себя узлов (по умолчанию: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Произошла ошибка при открытии RPC-порта %u для прослушивания на IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Прослушивать подключения JSON-RPC на &lt;порту&gt; (по умолчанию: 9332 или для testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Принимать командную строку и команды JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Запускаться в фоне как демон и принимать команды</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Использовать тестовую сеть</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Принимать подключения извне (по умолчанию: 1, если не используется -proxy или -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=johnkeyoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;JohnKeyoin Alert&quot; admin@foo.com </source> <translation>%s, вы должны установить опцию rpcpassword в конфигурационном файле: %s Рекомендуется использовать следующий случайный пароль: rpcuser=johnkeyoinrpc rpcpassword=%s (вам не нужно запоминать этот пароль) Имя и пароль ДОЛЖНЫ различаться. Если файл не существует, создайте его и установите права доступа только для владельца, только для чтения. Также рекомендуется включить alertnotify для оповещения о проблемах; Например: alertnotify=echo %%s | mail -s &quot;JohnKeyoin Alert&quot; admin@foo.com </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Произошла ошибка при открытии на прослушивание IPv6 RCP-порта %u, возвращаемся к IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Привязаться к указанному адресу и всегда прослушивать только его. Используйте [хост]:порт для IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. JohnKeyoin is probably already running.</source> <translation>Не удаётся установить блокировку на каталог данных %s. Возможно, JohnKeyoin уже работает.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Ошибка: транзакция была отклонена! Это могло произойти в случае, если некоторые монеты в вашем бумажнике уже были потрачены, например, если вы используете копию wallet.dat, и монеты были использованы в копии, но не отмечены как потраченные здесь.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Ошибка: эта транзакция требует комиссию как минимум %s из-за суммы, сложности или использования недавно полученных средств!</translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Выполнить команду, когда приходит сообщение о тревоге (%s в команде заменяется на сообщение)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Выполнить команду, когда меняется транзакция в бумажнике (%s в команде заменяется на TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Максимальный размер высокоприоритетных/низкокомиссионных транзакций в байтах (по умолчанию: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Это пре-релизная тестовая сборка - используйте на свой страх и риск - не используйте для добычи или торговых приложений</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Внимание: установлено очень большое значение -paytxfee. Это комиссия, которую вы заплатите при проведении транзакции.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Внимание: отображаемые транзакции могут быть некорректны! Вам или другим узлам, возможно, следует обновиться.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong JohnKeyoin will not work properly.</source> <translation>Внимание: убедитесь, что дата и время на Вашем компьютере выставлены верно. Если Ваши часы идут неправильно, JohnKeyoin будет работать некорректно.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Внимание: ошибка чтения wallet.dat! Все ключи прочитаны верно, но данные транзакций или записи адресной книги могут отсутствовать или быть неправильными.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Внимание: wallet.dat повреждён, данные спасены! Оригинальный wallet.dat сохранён как wallet.{timestamp}.bak в %s; если ваш баланс или транзакции некорректны, вы должны восстановить файл из резервной копии.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Попытаться восстановить приватные ключи из повреждённого wallet.dat</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Параметры создания блоков:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Подключаться только к указанному узлу(ам)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>БД блоков повреждена</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Определить свой IP (по умолчанию: 1 при прослушивании и если не используется -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Пересобрать БД блоков прямо сейчас?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Ошибка инициализации БД блоков</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Ошибка инициализации окружения БД бумажника %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Ошибка чтения базы данных блоков</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Не удалось открыть БД блоков</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Ошибка: мало места на диске!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Ошибка: бумажник заблокирован, невозможно создать транзакцию!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Ошибка: системная ошибка:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Не удалось начать прослушивание на порту. Используйте -listen=0 если вас это устраивает.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Не удалось прочитать информацию блока</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Не удалось прочитать блок</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Не удалось синхронизировать индекс блоков</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Не удалось записать индекс блоков</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Не удалось записать информацию блока</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Не удалось записать блок</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Не удалось записать информацию файла</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Не удалось записать БД монет</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Не удалось записать индекс транзакций</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Не удалось записать данные для отмены</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Искать узлы с помощью DNS (по умолчанию: 1, если не указан -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Включить добычу монет (по умолчанию: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Сколько блоков проверять при запуске (по умолчанию: 288, 0 = все)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Насколько тщательно проверять блок (0-4, по умолчанию: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Недостаточно файловых дескрипторов.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Перестроить индекс цепи блоков из текущих файлов blk000??.dat</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Задать число потоков выполнения(по умолчанию: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Проверка блоков...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Проверка бумажника...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Импортировать блоки из внешнего файла blk000??.dat</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Задать число потоков проверки скрипта (вплоть до 16, 0=авто, &lt;0 = оставить столько ядер свободными, по умолчанию: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Информация</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Неверный адрес -tor: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Неверное количество в параметре -minrelaytxfee=&lt;кол-во&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Неверное количество в параметре -mintxfee=&lt;кол-во&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Держать полный индекс транзакций (по умолчанию: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Максимальный размер буфера приёма на соединение, &lt;n&gt;*1000 байт (по умолчанию: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Максимальный размер буфера отправки на соединение, &lt;n&gt;*1000 байт (по умолчанию: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Принимать цепь блоков, только если она соответствует встроенным контрольным точкам (по умолчанию: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Подключаться только к узлам из сети &lt;net&gt; (IPv4, IPv6 или Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Выводить больше отладочной информации. Включает все остальные опции -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Выводить дополнительную сетевую отладочную информацию</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Дописывать отметки времени к отладочному выводу</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the JohnKeyoin Wiki for SSL setup instructions)</source> <translation> Параметры SSL: (см. JohnKeyoin Wiki для инструкций по настройке SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Выбрать версию SOCKS-прокси (4-5, по умолчанию: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Выводить информацию трассировки/отладки на консоль вместо файла debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Отправлять информацию трассировки/отладки в отладчик</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Максимальный размер блока в байтах (по умолчанию: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Минимальный размер блока в байтах (по умолчанию: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Сжимать файл debug.log при запуске клиента (по умолчанию: 1, если нет -debug)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Не удалось подписать транзакцию</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Таймаут соединения в миллисекундах (по умолчанию: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Системная ошибка:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Объём транзакции слишком мал</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Объём транзакции должен быть положителен</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Транзакция слишком большая</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Использовать UPnP для проброса порта (по умолчанию: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Использовать UPnP для проброса порта (по умолчанию: 1, если используется прослушивание)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Использовать прокси для скрытых сервисов (по умолчанию: тот же, что и в -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Имя для подключений JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Внимание</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Внимание: эта версия устарела, требуется обновление!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Вам необходимо пересобрать базы данных с помощью -reindex, чтобы изменить -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat повреждён, спасение данных не удалось</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Пароль для подключений JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Разрешить подключения JSON-RPC с указанного IP</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Посылать команды узлу, запущенному на &lt;ip&gt; (по умолчанию: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Выполнить команду, когда появляется новый блок (%s в команде заменяется на хэш блока)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Обновить бумажник до последнего формата</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Установить размер запаса ключей в &lt;n&gt; (по умолчанию: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Перепроверить цепь блоков на предмет отсутствующих в бумажнике транзакций</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Использовать OpenSSL (https) для подключений JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Файл серверного сертификата (по умолчанию: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Приватный ключ сервера (по умолчанию: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Разрешённые алгоритмы (по умолчанию: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Эта справка</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Невозможно привязаться к %s на этом компьютере (bind вернул ошибку %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Подключаться через socks прокси</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Разрешить поиск в DNS для -addnode, -seednode и -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Загрузка адресов...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Ошибка загрузки wallet.dat: Бумажник поврежден</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of JohnKeyoin</source> <translation>Ошибка загрузки wallet.dat: бумажник требует более новую версию JohnKeyoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart JohnKeyoin to complete</source> <translation>Необходимо перезаписать бумажник, перезапустите JohnKeyoin для завершения операции.</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Ошибка при загрузке wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Неверный адрес -proxy: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>В параметре -onlynet указана неизвестная сеть: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>В параметре -socks запрошена неизвестная версия: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Не удаётся разрешить адрес в параметре -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Не удаётся разрешить адрес в параметре -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Неверное количество в параметре -paytxfee=&lt;кол-во&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Неверное количество</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Недостаточно монет</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Загрузка индекса блоков...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Добавить узел для подключения и пытаться поддерживать соединение открытым</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. JohnKeyoin is probably already running.</source> <translation>Невозможно привязаться к %s на этом компьютере. Возможно, JohnKeyoin уже работает.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Комиссия на килобайт, добавляемая к вашим транзакциям</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Загрузка бумажника...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Не удаётся понизить версию бумажника</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Не удаётся записать адрес по умолчанию</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Сканирование...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Загрузка завершена</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Чтобы использовать опцию %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Ошибка</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Вы должны установить rpcpassword=&lt;password&gt; в конфигурационном файле: %s Если файл не существует, создайте его и установите права доступа только для владельца.</translation> </message> </context> </TS>
{ "content_hash": "bd89498da5c137751875f308ca7b13fd", "timestamp": "", "source": "github", "line_count": 2940, "max_line_length": 417, "avg_line_length": 39.9734693877551, "alnum_prop": 0.6371402801177651, "repo_name": "JohnKeyCoin/JohnKeyoin", "id": "ee3b69d20a9536f61fcec71c207b4eb906daf212", "size": "135123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_ru.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "96512" }, { "name": "C++", "bytes": "2519687" }, { "name": "CSS", "bytes": "1127" }, { "name": "IDL", "bytes": "14634" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "37264" }, { "name": "Shell", "bytes": "2527" }, { "name": "TypeScript", "bytes": "5239467" } ], "symlink_target": "" }
'use strict'; var isCallable = require('is-callable'); var fnToStr = Function.prototype.toString; var isNonArrowFnRegex = /^\s*function/; var isArrowFnWithParensRegex = /^\([^)]*\) *=>/; var isArrowFnWithoutParensRegex = /^[^=]*=>/; module.exports = function isArrowFunction(fn) { if (!isCallable(fn)) { return false; } var fnStr = fnToStr.call(fn); return fnStr.length > 0 && !isNonArrowFnRegex.test(fnStr) && (isArrowFnWithParensRegex.test(fnStr) || isArrowFnWithoutParensRegex.test(fnStr)); };
{ "content_hash": "4697a9dbda305cb28c60c34a7bc17016", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 84, "avg_line_length": 29.941176470588236, "alnum_prop": 0.7013752455795678, "repo_name": "ljharb/node-is-arrow-function", "id": "ad245a84795a7b8f885d57fb1eb82b747ea0f83c", "size": "509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2425" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. ~ ~ WSO2 Inc. licenses this file to you under the Apache License, ~ Version 2.0 (the "License"); you may not use this file except ~ in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, ~ software distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the License for the ~ specific language governing permissions and limitations ~ under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.wso2.carbon.devicemgt-plugins</groupId> <artifactId>extensions</artifactId> <version>4.1.19-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>appm-connector</artifactId> <packaging>pom</packaging> <name>WSO2 Carbon - IoT Base Plugin</name> <url>http://wso2.org</url> <modules> <module>org.wso2.carbon.appmgt.mdm.osgiconnector</module> <module>org.wso2.carbon.appmgt.mdm.restconnector</module> </modules> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-scr-plugin</artifactId> <version>1.7.2</version> <executions> <execution> <id>generate-scr-scrdescriptor</id> <goals> <goal>scr</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> </build> </project>
{ "content_hash": "235614a00d8735fd54c98af83c13c7d3", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 204, "avg_line_length": 36.516666666666666, "alnum_prop": 0.5846645367412141, "repo_name": "lasanthaDLPDS/carbon-device-mgt-plugins", "id": "f41f5d851c0dbb0f964de0052b822e4509d136c1", "size": "2191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/extensions/appm-connector/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "912" }, { "name": "C", "bytes": "2475" }, { "name": "C++", "bytes": "14451" }, { "name": "CSS", "bytes": "565755" }, { "name": "HTML", "bytes": "679943" }, { "name": "Java", "bytes": "3860603" }, { "name": "JavaScript", "bytes": "9901466" }, { "name": "PLSQL", "bytes": "4277" }, { "name": "Python", "bytes": "36818" }, { "name": "Shell", "bytes": "16631" } ], "symlink_target": "" }
extern crate rand; extern crate hyper; extern crate regex; extern crate openssl; extern crate itertools; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate winreg; #[cfg(windows)] extern crate shell32; #[cfg(windows)] extern crate ole32; extern crate rust_manifest; extern crate tempdir; extern crate walkdir; pub use errors::*; pub use install::*; pub mod env_var; #[macro_use] pub mod notify; pub mod utils; pub mod temp; #[cfg(windows)] pub mod msi; pub mod dist; mod errors; mod install; pub mod component; pub mod manifest; pub mod download; // Mocks shared by tests pub mod mock;
{ "content_hash": "0a24e8a8b12ec1c48e119ee2f0aa5553", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 27, "avg_line_length": 15.947368421052632, "alnum_prop": 0.740924092409241, "repo_name": "kamalmarhubi/rust-bisect", "id": "ca02211dbb59650d43b7016c2c4916cadca20cca", "size": "681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/multirust-rs/rust-install/src/lib.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "9147" }, { "name": "Shell", "bytes": "2151" } ], "symlink_target": "" }
An app to collect and display information about service entrance for any given building in New York City. It is based on Angular2-Meteor boilerplate. ## NPM Scripts Angular2-Meteor boilerplate comes with predefined NPM scripts, defined in `package.json`: - `$ npm run start` - Run the Meteor application. - `$ npm run start:prod` - Run the Meteor application in production mode. - `$ npm run build` - Creates a Meteor build version under `./build/` directory. - `$ npm run clear` - Resets Meteor's cache and clears the MongoDB collections. - `$ npm run meteor:update` - Updates Meteor's version and it's dependencies. - `$ npm run test` - Executes Meteor in test mode with Mocha. - `$ npm run test:ci` - Executes Meteor in test mode with Mocha for CI (run once).
{ "content_hash": "fd4f8f63fb0b32bd2d7d98b780ca1f08", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 105, "avg_line_length": 51.13333333333333, "alnum_prop": 0.7392438070404173, "repo_name": "mradenovic/service-entrance-info", "id": "a96848d2eeedc49e04c978a51342de739b3cb109", "size": "792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12044" }, { "name": "HTML", "bytes": "12398" }, { "name": "TypeScript", "bytes": "24649" } ], "symlink_target": "" }
<?php namespace app\modules\ls_admin\controllers; \Yii::$app->session->set('id_doc_create', false); use app\modules\ls_admin\models\ProductPrice; use app\modules\ls_admin\models\ProductStock; use Yii; use app\modules\ls_admin\models\Product; use app\modules\ls_admin\models\ProductSearch; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * ProductController implements the CRUD actions for Product model. */ class ProductController extends Controller { /** * @inheritdoc */ public $layout = 'admin'; public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['POST'], ], ], 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, 'roles' => ['@'], ], ], ], 'auth'=>[ 'class' =>'app\commands\Auth', ], ]; } /** * Lists all Product models. * @return mixed */ public function actionIndex() { $searchModel = new ProductSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider->sort = false; return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Product model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Product model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Product(); $productPrice = new ProductPrice(); $productPrice->product_id = 0; if ($model->load(Yii::$app->request->post()) && $model->save()) { if($productPrice->load(Yii::$app->request->post()) ){ $productPrice->product_id = $model->id; $productPrice->save(); return $this->redirect(['index']); }else{ return $this->render('create', [ 'model' => $model, 'productPrice' => $productPrice, ]); } } else { return $this->render('create', [ 'model' => $model, 'productPrice' => $productPrice, ]); } } /** * Updates an existing Product model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $productPrice = ProductPrice::findOne(['product_id'=>$id]); if ($model->load(Yii::$app->request->post()) && $model->save()) { if($productPrice->load(Yii::$app->request->post()) ){ $productPrice->product_id = $model->id; $productPrice->save(); return $this->redirect(['index']); }else{ return $this->render('update', [ 'model' => $model, 'productPrice' => $productPrice, ]); } } else { return $this->render('update', [ 'model' => $model, 'productPrice' => $productPrice, ]); } } /** * Deletes an existing Product model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Product model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Product the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Product::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
{ "content_hash": "680a99320d7e4e65cc539581fa9fad9b", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 85, "avg_line_length": 27.75, "alnum_prop": 0.5032175032175032, "repo_name": "AndrewListat/paydoc", "id": "cb0fb886a35555a02d47a50746ae6e69390ec6af", "size": "4662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/ls_admin/controllers/ProductController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "650" }, { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "544676" }, { "name": "HTML", "bytes": "1760010" }, { "name": "JavaScript", "bytes": "3015976" }, { "name": "PHP", "bytes": "412224" } ], "symlink_target": "" }
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link><script type="text/javascript" src="js/jquery-1.4.2.min.js"></script><script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script><script type="text/javascript" src="js/jquery.cookie.js"></script><script type="text/javascript" src="js/jquery.treeview.js"></script><script type="text/javascript"> $(document).ready(function() { $(".filetree").treeview({ collapsed: true, persist: "cookie" }); $("#accordion").accordion({ collapsible: true, autoHeight: false, fillSpace: true }); $(".tabs").tabs(); }); </script></head><body><div xmlns="" class="content"> <div class="sub-page-main-header-api-documentation"><h2>API Documentation</h2></div> <div class="dotted-line"></div> </div> <div xmlns="" id="content"> <script type="text/javascript" src="js/menu.js"></script><script> $(document).ready(function() { $('a.gripper').click(function() { $(this).nextAll('div.code-tabs').slideToggle(); $(this).children('img').toggle(); return false; }); $('div.code-tabs').hide(); $('a.gripper').show(); $('div.file-nav').show(); }); </script><h1 class="file">Form/Decorator/ViewScript.php</h1> <div class="file-nav"><ul id="file-nav"> <li><a href="#top">Global</a></li> <li> <a href="#classes"><img src="images/icons/class.png" height="14"> Classes </a><ul><li><a href="#%5CZend_Form_Decorator_ViewScript">\Zend_Form_Decorator_ViewScript</a></li></ul> </li> </ul></div> <a name="top"></a><div id="file-description"> <p class="short-description">Zend Framework</p> <div class="long-description"><p>LICENSE</p> <p>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 license@zend.com so we can send you a copy immediately.</p> </div> </div> <dl class="file-info"> <dt>category</dt> <dd>Zend   </dd> <dt>copyright</dt> <dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)   </dd> <dt>license</dt> <dd> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a>   </dd> <dt>package</dt> <dd>Zend_Form   </dd> <dt>subpackage</dt> <dd>Decorator   </dd> </dl> <a name="classes"></a><a id="\Zend_Form_Decorator_ViewScript"></a><h2 class="class">\Zend_Form_Decorator_ViewScript<div class="to-top"><a href="#top">jump to top</a></div> </h2> <div class="class"> <p class="short-description">Zend_Form_Decorator_ViewScript</p> <div class="long-description"><p>Render a view script as a decorator</p> <p>Accepts the options: - separator: separator to use between view script content and provided content (defaults to PHP_EOL) - placement: whether to append or prepend view script content to provided content (defaults to prepend) - viewScript: view script to use - viewModule: module that view script is in (optional)</p> <p>The view script is rendered as a partial; the element being decorated is passed in as the 'element' variable:</p> <pre><code>// in view script: echo $this->element->getLabel(); </code></pre> <p>Any options other than separator, placement, viewScript, and viewModule are passed to the partial as local variables.</p> </div> <dl class="class-info"> <dt>Extends from</dt> <dd><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></dd> <dt>category</dt> <dd>Zend   </dd> <dt>copyright</dt> <dd>Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)   </dd> <dt>license</dt> <dd> <a href="http://framework.zend.com/license/new-bsd">New BSD License</a>   </dd> <dt>package</dt> <dd>Zend_Form   </dd> <dt>subpackage</dt> <dd>Decorator   </dd> <dt>version</dt> <dd>$Id: ViewScript.php 23775 2011-03-01 17:25:24Z ralph $   </dd> </dl> <h3>Properties</h3> <div> <a id="\Zend_Form_Decorator_ViewScript::$_placement"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">string  <span class="highlight">$_placement</span>= 'APPEND' </code><div class="description"> <p class="short-description">Default placement: append</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Default value</strong><code>APPEND</code><strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd>string</dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::$_viewModule"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">string  <span class="highlight">$_viewModule</span>= '' </code><div class="description"> <p class="short-description">View script module</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd>string</dd> </dl> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::$_viewScript"></a><div class="property"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/property.png" alt="Property"><img src="images/icons/visibility_protected.png" style="margin-right: 5px" alt="protected">string  <span class="highlight">$_viewScript</span>= '' </code><div class="description"> <p class="short-description">View script to render</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Details</strong><dl class="property-info"> <dt>Type</dt> <dd>string</dd> </dl> </div> <div class="clear"></div> </div> </div> <h3>Methods</h3> <div> <a id="\Zend_Form_Decorator_ViewScript::__construct()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">__construct</span><span class="nb-faded-text">( array|\Zend_Config $options = null ) </span> : void</code><div class="description"> <p class="short_description">Constructor</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::__construct()">\Zend_Form_Decorator_Abstract::__construct()</a></small> </div> <div class="code-tabs"> <div class="long-description"><p>Accept options during initialization.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$options</th> <td>array|\Zend_Config</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::clearOptions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">clearOptions</span><span class="nb-faded-text">( ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Clear all options</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::clearOptions()">\Zend_Form_Decorator_Abstract::clearOptions()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getElement()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getElement</span><span class="nb-faded-text">( ) </span> : <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a>|<a href="db_Form.html#%5CZend_Form">\Zend_Form</a></code><div class="description"> <p class="short_description">Retrieve current element</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getElement()">\Zend_Form_Decorator_Abstract::getElement()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td> <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a><a href="db_Form.html#%5CZend_Form">\Zend_Form</a> </td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getOption()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getOption</span><span class="nb-faded-text">( string $key ) </span> : mixed</code><div class="description"> <p class="short_description">Get option</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getOption()">\Zend_Form_Decorator_Abstract::getOption()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$key</th> <td>string</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>mixed</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getOptions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getOptions</span><span class="nb-faded-text">( ) </span> : array</code><div class="description"> <p class="short_description">Retrieve options</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getOptions()">\Zend_Form_Decorator_Abstract::getOptions()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>array</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getPlacement()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getPlacement</span><span class="nb-faded-text">( ) </span> : string</code><div class="description"> <p class="short_description">Determine if decorator should append or prepend content</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getPlacement()">\Zend_Form_Decorator_Abstract::getPlacement()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getSeparator()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getSeparator</span><span class="nb-faded-text">( ) </span> : string</code><div class="description"> <p class="short_description">Retrieve separator to use between old and new content</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::getSeparator()">\Zend_Form_Decorator_Abstract::getSeparator()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getViewModule()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getViewModule</span><span class="nb-faded-text">( ) </span> : string|null</code><div class="description"><p class="short_description">Get view script module</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>stringnull</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::getViewScript()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">getViewScript</span><span class="nb-faded-text">( ) </span> : string|null</code><div class="description"><p class="short_description">Get view script</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>stringnull</td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::removeOption()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">removeOption</span><span class="nb-faded-text">( mixed $key ) </span> : void</code><div class="description"> <p class="short_description">Remove single option</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::removeOption()">\Zend_Form_Decorator_Abstract::removeOption()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$key</th> <td>mixed</td> <td><em></em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::render()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">render</span><span class="nb-faded-text">( string $content ) </span> : string</code><div class="description"><p class="short_description">Render a view script</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$content</th> <td>string</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td>string</td> <td></td> </tr> </table> <strong>Throws</strong><table class="argument-info"> <thead><tr> <th>Exception</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Exception.html#%5CZend_Form_Decorator_Exception">\Zend_Form_Decorator_Exception</a></td> <td><em>when unimplemented</em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::setConfig()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setConfig</span><span class="nb-faded-text">( \Zend_Config $config ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set options from config object</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setConfig()">\Zend_Form_Decorator_Abstract::setConfig()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$config</th> <td>\Zend_Config</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::setElement()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setElement</span><span class="nb-faded-text">( <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a>|<a href="db_Form.html#%5CZend_Form">\Zend_Form</a> $element ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set current form element</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setElement()">\Zend_Form_Decorator_Abstract::setElement()</a></small> </div> <div class="code-tabs"> <div class="long-description"><p>While the name is "setElement", a form decorator could decorate either an element or a form object.</p> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$element</th> <td> <a href="db_Form_Element.html#%5CZend_Form_Element">\Zend_Form_Element</a>|<a href="db_Form.html#%5CZend_Form">\Zend_Form</a> </td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> <strong>Throws</strong><table class="argument-info"> <thead><tr> <th>Exception</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Exception.html#%5CZend_Form_Decorator_Exception">\Zend_Form_Decorator_Exception</a></td> <td><em>on invalid element type</em></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::setOption()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setOption</span><span class="nb-faded-text">( string $key, mixed $value ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set option</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setOption()">\Zend_Form_Decorator_Abstract::setOption()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$key</th> <td>string</td> <td><em></em></td> </tr> <tr> <th>$value</th> <td>mixed</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::setOptions()"></a><div class="method inherited_from "> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setOptions</span><span class="nb-faded-text">( array $options ) </span> : <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></code><div class="description"> <p class="short_description">Set options</p> <small>Inherited from: <a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract::setOptions()">\Zend_Form_Decorator_Abstract::setOptions()</a></small> </div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$options</th> <td>array</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_Abstract.html#%5CZend_Form_Decorator_Abstract">\Zend_Form_Decorator_Abstract</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::setViewModule()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setViewModule</span><span class="nb-faded-text">(  $viewModule ) </span> : <a href="db_Form_Decorator_ViewScript.html#%5CZend_Form_Decorator_ViewScript">\Zend_Form_Decorator_ViewScript</a></code><div class="description"><p class="short_description">Set view script module</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$viewModule</th> <td></td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_ViewScript.html#%5CZend_Form_Decorator_ViewScript">\Zend_Form_Decorator_ViewScript</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> <a id="\Zend_Form_Decorator_ViewScript::setViewScript()"></a><div class="method"> <a href="#" class="gripper"><img src="images/icons/arrow_right.png"><img src="images/icons/arrow_down.png" style="display: none;"></a><code><img src="images/icons/method.png" alt="method"><img src="images/icons/visibility_public.png" style="margin-right: 5px" alt="public"><span class="highlight">setViewScript</span><span class="nb-faded-text">( string $script ) </span> : <a href="db_Form_Decorator_ViewScript.html#%5CZend_Form_Decorator_ViewScript">\Zend_Form_Decorator_ViewScript</a></code><div class="description"><p class="short_description">Set view script</p></div> <div class="code-tabs"> <div class="long-description"> </div> <strong>Parameters</strong><table class="argument-info"> <thead><tr> <th>Name</th> <th>Type</th> <th>Description</th> </tr></thead> <tr> <th>$script</th> <td>string</td> <td><em></em></td> </tr> </table> <strong>Returns</strong><table class="argument-info"> <thead><tr> <th>Type</th> <th>Description</th> </tr></thead> <tr> <td><a href="db_Form_Decorator_ViewScript.html#%5CZend_Form_Decorator_ViewScript">\Zend_Form_Decorator_ViewScript</a></td> <td></td> </tr> </table> </div> <div class="clear"></div> </div> </div> </div> </div> <small xmlns="" class="footer">Documentation was generated by <a href="http://docblox-project.org">DocBlox 0.13.3</a>. </small></body></html>
{ "content_hash": "a3d6d604a8d35a579aab086eb2071e65", "timestamp": "", "source": "github", "line_count": 753, "max_line_length": 721, "avg_line_length": 38.16201859229748, "alnum_prop": 0.6567371937639198, "repo_name": "wukchung/Home-development", "id": "d853c3918f63682ffed2850141f2a66ff3d25477", "size": "28761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/api/core/db_Form_Decorator_ViewScript.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#include <QMainWindow> namespace Ui { class MainWindow; } static const QString ListHeaderTemplate = "<h3>%1</h3>"; static const QString ListElementTemplate = "<p style='margin: 0px 0px 4px 20px'> %1 </p>"; class MainWindow : public QMainWindow { Q_OBJECT signals: void commandEntered(const QString &); void helpLaunchQueried(); void logviewLaunch(); public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void clearInputArea(); public slots: void displayErrorInfo(const QString &info); void hideErrorInfo(); void updateSidebar(const QString &contents); void resultReturned(const QString &result); private slots: void commandEntered(); protected: void resizeEvent(QResizeEvent *); private slots: void aboutTriggered(); private: Ui::MainWindow *ui; void setSplitterSizes(); }; #endif // MAINWINDOW_H
{ "content_hash": "298db0c85851c92fb26e0bbc2837bf3d", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 90, "avg_line_length": 19.6, "alnum_prop": 0.7018140589569161, "repo_name": "ming13/aequatio", "id": "ddc9f6fa2191e2d03ee86067302d94c9431660e3", "size": "926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/mainwindow.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "233942" }, { "name": "Prolog", "bytes": "4147" }, { "name": "Rust", "bytes": "44" } ], "symlink_target": "" }
package org.activiti.standalone.jpa; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.activiti.engine.impl.test.AbstractFlowableTestCase; import org.activiti.engine.impl.variable.EntityManagerSession; import org.activiti.engine.impl.variable.EntityManagerSessionFactory; import org.activiti.engine.task.Task; import org.flowable.engine.ProcessEngine; import org.flowable.engine.ProcessEngineConfiguration; import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.engine.test.Deployment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test for JPA enhancement support * * @author <a href="mailto:eugene.khrustalev@gmail.com">Eugene Khrustalev</a> */ public class JPAEnhancedVariableTest extends AbstractFlowableTestCase { protected static final Logger logger = LoggerFactory.getLogger(JPAEnhancedVariableTest.class); protected static EntityManagerFactory entityManagerFactory; protected static ProcessEngine cachedProcessEngine; protected static org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl activiti5ProcessEngineConfig; protected static FieldAccessJPAEntity fieldEntity; protected static FieldAccessJPAEntity fieldEntity2; protected static PropertyAccessJPAEntity propertyEntity; @Override protected void initializeProcessEngine() { if (cachedProcessEngine == null) { ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) ProcessEngineConfiguration .createProcessEngineConfigurationFromResource("org/activiti/standalone/jpa/flowable.cfg.xml"); cachedProcessEngine = processEngineConfiguration.buildProcessEngine(); activiti5ProcessEngineConfig = (org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) ((ProcessEngineConfigurationImpl) cachedProcessEngine.getProcessEngineConfiguration()).getFlowable5CompatibilityHandler().getRawProcessConfiguration(); EntityManagerSessionFactory entityManagerSessionFactory = (EntityManagerSessionFactory) activiti5ProcessEngineConfig .getSessionFactories() .get(EntityManagerSession.class); entityManagerFactory = entityManagerSessionFactory.getEntityManagerFactory(); setupJPAVariables(); } processEngine = cachedProcessEngine; } private static void setupJPAVariables() { EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); fieldEntity = new FieldAccessJPAEntity(); fieldEntity.setId(1L); fieldEntity.setValue("fieldEntity"); em.persist(fieldEntity); propertyEntity = new PropertyAccessJPAEntity(); propertyEntity.setId(1L); propertyEntity.setValue("propertyEntity"); em.persist(propertyEntity); em.flush(); em.getTransaction().commit(); em.close(); // load enhanced versions of entities em = entityManagerFactory.createEntityManager(); fieldEntity = em.find(FieldAccessJPAEntity.class, fieldEntity.getId()); propertyEntity = em.find(PropertyAccessJPAEntity.class, propertyEntity.getId()); em.getTransaction().begin(); fieldEntity2 = new FieldAccessJPAEntity(); fieldEntity2.setId(2L); fieldEntity2.setValue("fieldEntity2"); em.persist(fieldEntity2); em.flush(); em.getTransaction().commit(); em.close(); } private Task getTask(ProcessInstance instance) { return activiti5ProcessEngineConfig.getTaskService() .createTaskQuery() .processInstanceId(instance.getProcessInstanceId()) .includeProcessVariables() .singleResult(); } @Deployment(resources = { "org/activiti/standalone/jpa/JPAVariableTest.testStoreJPAEntityAsVariable.bpmn20.xml" }) public void testEnhancedEntityVariables() throws Exception { // test if enhancement is used if (FieldAccessJPAEntity.class == fieldEntity.getClass() || PropertyAccessJPAEntity.class == propertyEntity.getClass()) { logger.warn("Entity enhancement is not used"); return; } // start process with enhanced jpa variables Map<String, Object> params = new HashMap<String, Object>(); params.put("fieldEntity", fieldEntity); params.put("propertyEntity", propertyEntity); ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey("JPAVariableProcess", params); Task task = getTask(instance); for (Map.Entry<String, Object> entry : task.getProcessVariables().entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (name.equals("fieldEntity")) { assertTrue(value instanceof FieldAccessJPAEntity); } else if (name.equals("propertyEntity")) { assertTrue(value instanceof PropertyAccessJPAEntity); } else { fail(); } } } @Deployment(resources = { "org/activiti/standalone/jpa/JPAVariableTest.testStoreJPAEntityAsVariable.bpmn20.xml" }) public void testEnhancedEntityListVariables() throws Exception { // test if enhancement is used if (FieldAccessJPAEntity.class == fieldEntity.getClass() || PropertyAccessJPAEntity.class == propertyEntity.getClass()) { logger.warn("Entity enhancement is not used"); return; } // start process with lists of enhanced jpa variables Map<String, Object> params = new HashMap<String, Object>(); params.put("list1", Arrays.asList(fieldEntity, fieldEntity)); params.put("list2", Arrays.asList(propertyEntity, propertyEntity)); ProcessInstance instance = processEngine.getRuntimeService().startProcessInstanceByKey("JPAVariableProcess", params); Task task = getTask(instance); List list = (List) task.getProcessVariables().get("list1"); assertEquals(2, list.size()); assertTrue(list.get(0) instanceof FieldAccessJPAEntity); assertTrue(list.get(1) instanceof FieldAccessJPAEntity); list = (List) task.getProcessVariables().get("list2"); assertEquals(2, list.size()); assertTrue(list.get(0) instanceof PropertyAccessJPAEntity); assertTrue(list.get(1) instanceof PropertyAccessJPAEntity); // start process with enhanced and persisted only jpa variables in the same list params.putAll(Collections.singletonMap("list", Arrays.asList(fieldEntity, fieldEntity2))); instance = processEngine.getRuntimeService().startProcessInstanceByKey("JPAVariableProcess", params); task = getTask(instance); list = (List) task.getProcessVariables().get("list"); assertEquals(2, list.size()); assertTrue(list.get(0) instanceof FieldAccessJPAEntity); assertEquals(1L, (long) ((FieldAccessJPAEntity) list.get(0)).getId()); assertTrue(list.get(1) instanceof FieldAccessJPAEntity); assertEquals(2L, (long) ((FieldAccessJPAEntity) list.get(1)).getId()); // shuffle list and start a new process params.putAll(Collections.singletonMap("list", Arrays.asList(fieldEntity2, fieldEntity))); instance = processEngine.getRuntimeService().startProcessInstanceByKey("JPAVariableProcess", params); task = getTask(instance); list = (List) task.getProcessVariables().get("list"); assertEquals(2, list.size()); assertTrue(list.get(0) instanceof FieldAccessJPAEntity); assertEquals(2L, (long) ((FieldAccessJPAEntity) list.get(0)).getId()); assertTrue(list.get(1) instanceof FieldAccessJPAEntity); assertEquals(1L, (long) ((FieldAccessJPAEntity) list.get(1)).getId()); // start process with mixed jpa entities in list try { params = new HashMap<String, Object>(); params.put("list", Arrays.asList(fieldEntity, propertyEntity)); instance = processEngine.getRuntimeService().startProcessInstanceByKey("JPAVariableProcess", params); fail(); } catch (Exception e) { /* do nothing */ } } }
{ "content_hash": "2b5cb874a2b05451fd68183043399d24", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 161, "avg_line_length": 40.97969543147208, "alnum_prop": 0.7408646104298279, "repo_name": "motorina0/flowable-engine", "id": "ce282cf128910ed2368af3da92f1ef3776902d07", "size": "8073", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/flowable5-test/src/test/java/org/activiti/standalone/jpa/JPAEnhancedVariableTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "96556" }, { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "681931" }, { "name": "HTML", "bytes": "858905" }, { "name": "Java", "bytes": "22289599" }, { "name": "JavaScript", "bytes": "12782950" }, { "name": "Shell", "bytes": "18731" } ], "symlink_target": "" }
チュートリアル用のサーバは非常にシンプルであり、典型的なPlayアプリケーションではありませんが、クライアント側のコードの基本的なサポートには十分です。 サーバ側のルーティングロビックはPlayのコントローラーを用いて定義されます。 ```scala object Application extends Controller { val apiService = new ApiService() def index = Action { Ok(views.html.index("SPA tutorial")) } def autowireApi(path: String) = Action.async(parse.raw) { implicit request => println(s"Request path: $path") // get the request body as ByteString val b = request.body.asBytes(parse.UNLIMITED).get // call Autowire route Router.route[Api](apiService)( autowire.Core.Request(path.split("/"), Unpicクライアント側と同様に、kle[Map[がtring, ByteBuffer]].fromBytes(b.asByteBuffer))そのため、単に、 ).map(buffer => { val data = Array.ofDim[Byte](buffer.remaining()) buffer.get(data) Ok(data) }) } def logging = Action(parse.anyContent) { implicit request => request.body.asJson.foreach { msg => println(s"CLIENT - $msg") } Ok("") } } ``` mainのHTMLページ及び関連するリソースは、`twirl`ディレクトリからPlayのテンプレートエンジンにより提供されます。 興味深いのは、Autowireルーターを用いての`api`リクエストの扱い方です。 クライアント側と同様に、Autowireが、複雑な事柄を取り扱います。すなわち、単にAutowireをプラグするだけで、そのマジックは発揮されます。 Boopickleが、リクエストのデシリアライズと、レスポンスのバイナリへのシリアライズを行います。 `ApiService`は、単なる通常のクラスであり、それ自体はシリアライズやURlリクエストのマッピングに関与しません。 このサービスは、クライアント側で用いられたのと同一の`Api` を実装します。 シンプルだね! ```scala class ApiService extends Api { var todos = Seq( Poi("1", "Wear shirt that says 'Life'. Hand out lemons on street corner.", TodoLow, false), Poi("2", "Make vanilla pudding. Put in mayo jar. Eat in public.", TodoNormal, false), Poi("3", "Walk away slowly from an explosion without looking back.", TodoHigh, false), Poi("4", "Sneeze in front of the pope. Get blessed.", TodoNormal, true) ) override def motd(name: String): String = s"Welcome to SPA, $name! Time is now ${new Date}" override def getTodos(): Seq[Poi] = { // provide some fake Todos println(s"Sending ${todos.size} Todo items") todos } // update a Todo override def updateTodo(item: Poi): Seq[Poi] = { // TODO, update database etc :) if(todos.exists(_.id == item.id)) { todos = todos.collect { case i if i.id == item.id => item case i => i } println(s"Todo item was updated: $item") } else { // add a new item val newItem = item.copy(id = UUID.randomUUID().toString) todos :+= newItem println(s"Todo item was added: $newItem") } todos } // delete a Todo override def deleteTodo(itemId: String): Seq[Poi] = { println(s"Deleting item with id = $itemId") todos = todos.filterNot(_.id == itemId) todos } } ```
{ "content_hash": "9796a55d093cbacf822686a331151351", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 127, "avg_line_length": 30.306818181818183, "alnum_prop": 0.6636670416197975, "repo_name": "devkat/kidstravel", "id": "4ada172993cbb405bbf168e58c1c94a110e53e58", "size": "3455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/jp/server-side.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "96" }, { "name": "HTML", "bytes": "826" }, { "name": "Scala", "bytes": "82687" } ], "symlink_target": "" }
{% extends 'conductor/layout.html' %} {% block content %} {{ super() }} <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h4><strong>Successfully Updated! Newly available contracts:</strong></h4> {% if contract.parent.children|length > 0 %} {% for _contract in contract.parent.children %} {% include 'conductor/edit/success_contract.html' %} {% endfor %} {% elif contract.children|length > 0 %} {% for _contract in contract.children %} {% include 'conductor/edit/success_contract.html' %} {% endfor %} </ul> {% else %} {% set _contract = contract %} {% include 'conductor/edit/success_contract.html' %} {% endif %} </div> </div> </div> {% endblock %}
{ "content_hash": "ab2909d7971c18ff155aa33b0b423064", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 78, "avg_line_length": 24.70967741935484, "alnum_prop": 0.5913838120104439, "repo_name": "CityofPittsburgh/pittsburgh-purchasing-suite", "id": "75076722728a8a8751fd3aa149f5a0fe89b53dc8", "size": "766", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "purchasing/templates/conductor/edit/success.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "24438" }, { "name": "HTML", "bytes": "316264" }, { "name": "JavaScript", "bytes": "25700" }, { "name": "Makefile", "bytes": "613" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "685542" }, { "name": "Shell", "bytes": "3379" } ], "symlink_target": "" }
import PropTypes from "prop-types"; import React from "react"; import styles from "./index.module.css"; const SearchBar = ({ onChange, onSubmit, placeholderText, submitText, value, }) => ( <form className={styles.formMobile} onSubmit={onSubmit} role="search"> <div className="field has-addons"> <div className="control"> <input aria-label="Search the food list" className="input" onChange={onChange} placeholder={placeholderText} type="search" value={value} /> </div> <div className="control"> <input className="button" type="submit" value={submitText} /> </div> </div> </form> ); SearchBar.propTypes = { onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, placeholderText: PropTypes.string, submitText: PropTypes.string, value: PropTypes.string, }; SearchBar.defaultProps = { placeholderText: "Enter a food name", submitText: "Search", value: "", }; export default SearchBar;
{ "content_hash": "81ed31530bf0bd28b1e734344dc60b4b", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 72, "avg_line_length": 23.31111111111111, "alnum_prop": 0.6387035271687321, "repo_name": "lburdock/fodmap", "id": "410772f9a108cd43091a76f7203005ad88bf6871", "size": "1049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/search-bar/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "509" }, { "name": "JavaScript", "bytes": "44867" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/TaskKilla.iml" filepath="$PROJECT_DIR$/.idea/TaskKilla.iml" /> </modules> </component> </project>
{ "content_hash": "84acc55b0367d1a867c94eaba3ca5cf1", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 112, "avg_line_length": 30.22222222222222, "alnum_prop": 0.6580882352941176, "repo_name": "DesenvolvedoresGoogle/TaskKilla", "id": "bfdd75f1ddf47545dd51e12a3328480d641f697a", "size": "272", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": ".idea/modules.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "109951" }, { "name": "JavaScript", "bytes": "93058" }, { "name": "Python", "bytes": "9899" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Collections; namespace Xrm { /// <summary> /// This class is here because we can't use the mscorlib Array Extensions in Ribbon Commands/Form JS because they conflict with the CRM scripts /// </summary> public class ArrayEx { public static void Add(object list, object item) { Script.Literal("{0}[{0}.length]={1}", list, item); } public static IEnumerator GetEnumerator(object list) { return (IEnumerator)Script.Literal("new ss.ArrayEnumerator({0})",list); } public static string Join(Array list, string delimeter) { string result = ""; for (int i = 0; i < list.Length; i++) { if (i > 0) result += delimeter; result += list[i]; } return result; } } }
{ "content_hash": "9cb93eb6daca4b701f678b0faf543147", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 147, "avg_line_length": 28.636363636363637, "alnum_prop": 0.5407407407407407, "repo_name": "gfritz/SparkleXrm", "id": "dffee389c4d8805ca23dd4b1f07663d6e30c55cb", "size": "945", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "SparkleXrmSource/SparkleXrm/ArrayEx.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "1427" }, { "name": "C#", "bytes": "12133385" }, { "name": "CSS", "bytes": "247330" }, { "name": "HTML", "bytes": "130746" }, { "name": "JavaScript", "bytes": "1282934" } ], "symlink_target": "" }
<?php namespace Oro\Bundle\TranslationBundle\Migrations\Schema\v1_2; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\QueryBag; class OroTranslationBundle implements Migration { /** * @inheritdoc */ public function up(Schema $schema, QueryBag $queries) { /** Tables generation **/ $this->createOroLanguageTable($schema); /** Foreign keys generation **/ $this->addOroLanguageForeignKeys($schema); } /** * Create oro_language table * * @param Schema $schema */ protected function createOroLanguageTable(Schema $schema) { $table = $schema->createTable('oro_language'); $table->addColumn('id', 'integer', ['autoincrement' => true]); $table->addColumn('organization_id', 'integer', ['notnull' => false]); $table->addColumn('user_owner_id', 'integer', ['notnull' => false]); $table->addColumn('code', 'string', ['length' => 16]); $table->addColumn('enabled', 'boolean', ['default' => false]); $table->addColumn('installed_build_date', 'datetime', ['notnull' => false]); $table->addColumn('created_at', 'datetime', []); $table->addColumn('updated_at', 'datetime', []); $table->setPrimaryKey(['id']); $table->addUniqueIndex(['code']); } /** * Add oro_language foreign keys. * * @param Schema $schema */ protected function addOroLanguageForeignKeys(Schema $schema) { $table = $schema->getTable('oro_language'); $table->addForeignKeyConstraint( $schema->getTable('oro_organization'), ['organization_id'], ['id'], ['onDelete' => 'SET NULL', 'onUpdate' => null] ); $table->addForeignKeyConstraint( $schema->getTable('oro_user'), ['user_owner_id'], ['id'], ['onDelete' => 'SET NULL', 'onUpdate' => null] ); } }
{ "content_hash": "b8c6b40ee4a99d5d1aaff63fbbf91c16", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 84, "avg_line_length": 31.323076923076922, "alnum_prop": 0.5756385068762279, "repo_name": "geoffroycochard/platform", "id": "ad1dbc3b6bf4b95bc789ba882fd882eb15885433", "size": "2036", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Oro/Bundle/TranslationBundle/Migrations/Schema/v1_2/OroTranslationBundle.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "583679" }, { "name": "Cucumber", "bytes": "660" }, { "name": "HTML", "bytes": "1342329" }, { "name": "JavaScript", "bytes": "4589734" }, { "name": "PHP", "bytes": "19492046" } ], "symlink_target": "" }
casper.test.begin('m15_001 marc-588 Source Description note', 3, function suite(test) { casper.echo("Test environment: "+SERVER); var USECASE='/item/124229'; var ENTITY=SERVER+USECASE; casper.start(ENTITY, function() { test.assertTextExists('The organ yearbook' , 'page title The organ yearbook found'); test.assertTextExists('Source Description' , 'Source Description note TAG 555'); test.assertTextExists('Latest issue consulted: Vol. 39 (2010)', 'found a Source Description note'); }).run(function() { test.done(); }); });
{ "content_hash": "440cfefc47473dd231d6a7e92ff4a3da", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 100, "avg_line_length": 45.583333333333336, "alnum_prop": 0.7129798903107861, "repo_name": "gwu-libraries/launchpad-autotest", "id": "8c9c999e5c430a020fb10a076eaa64f33e788638", "size": "570", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "marc-tests/marc-588.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "128196" }, { "name": "Shell", "bytes": "16219" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "68ac3a7b67d672009f1246ab63505d8d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "a13bc09f8e05298e07108ca1e9a7f0fef9be7eb0", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Vitales/Vitaceae/Cyphostemma/Cyphostemma degraeri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /* * GENERATED CODE WARNING * This file was automatically generated - do not edit! */ require_once __DIR__ . '/../../../vendor/autoload.php'; // [START retail_v2alpha_generated_ProductService_ImportProducts_sync] use Google\ApiCore\ApiException; use Google\ApiCore\OperationResponse; use Google\Cloud\Retail\V2alpha\ImportProductsResponse; use Google\Cloud\Retail\V2alpha\ProductInputConfig; use Google\Cloud\Retail\V2alpha\ProductServiceClient; use Google\Rpc\Status; /** * Bulk import of multiple [Product][google.cloud.retail.v2alpha.Product]s. * * Request processing may be synchronous. No partial updating is supported. * Non-existing items are created. * * Note that it is possible for a subset of the * [Product][google.cloud.retail.v2alpha.Product]s to be successfully updated. * * @param string $formattedParent Required. * `projects/1234/locations/global/catalogs/default_catalog/branches/default_branch` * * If no updateMask is specified, requires products.create permission. * If updateMask is specified, requires products.update permission. Please see * {@see ProductServiceClient::branchName()} for help formatting this field. */ function import_products_sample(string $formattedParent): void { // Create a client. $productServiceClient = new ProductServiceClient(); // Prepare any non-scalar elements to be passed along with the request. $inputConfig = new ProductInputConfig(); // Call the API and handle any network failures. try { /** @var OperationResponse $response */ $response = $productServiceClient->importProducts($formattedParent, $inputConfig); $response->pollUntilComplete(); if ($response->operationSucceeded()) { /** @var ImportProductsResponse $response */ $result = $response->getResult(); printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString()); } else { /** @var Status $error */ $error = $response->getError(); printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString()); } } catch (ApiException $ex) { printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage()); } } /** * Helper to execute the sample. * * This sample has been automatically generated and should be regarded as a code * template only. It will require modifications to work: * - It may require correct/in-range values for request initialization. * - It may require specifying regional endpoints when creating the service client, * please see the apiEndpoint client configuration option for more details. */ function callSample(): void { $formattedParent = ProductServiceClient::branchName( '[PROJECT]', '[LOCATION]', '[CATALOG]', '[BRANCH]' ); import_products_sample($formattedParent); } // [END retail_v2alpha_generated_ProductService_ImportProducts_sync]
{ "content_hash": "6eebc11bdbc4f5cf104a7b67fcce5a01", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 115, "avg_line_length": 37.51807228915663, "alnum_prop": 0.6727681438664097, "repo_name": "googleapis/gapic-generator-php", "id": "8548397abc24096c72b8c1f45aec4b1f97a8b132", "size": "3708", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "tests/Integration/goldens/retail/samples/V2alpha/ProductServiceClient/import_products.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "4696178" }, { "name": "Shell", "bytes": "4841" }, { "name": "Starlark", "bytes": "52730" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Licensed to the Apache Software Foundation (ASF) under one or more ~ contributor license agreements. See the NOTICE file distributed with ~ this work for additional information regarding copyright ownership. ~ The ASF licenses this file to You under the Apache License, Version 2.0 ~ (the "License"); you may not use this file except in compliance with ~ the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. ~ --> <Configuration status="INFO"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout charset="UTF-8" pattern="%d %c %L [%t] %-5p %x - %m%n"/> </Console> </Appenders> <Loggers> <Root level="INFO"> <AppenderRef ref="Console"/> </Root> </Loggers> </Configuration>
{ "content_hash": "161799934f582d00d6936c9b0f203abb", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 83, "avg_line_length": 39.16129032258065, "alnum_prop": 0.6729818780889621, "repo_name": "apache/skywalking", "id": "eab9c374158d833b82c53144886f04e4d2cd3176", "size": "1214", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/e2e-v2/script/prepare/setup-oap/log4j2.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "10340" }, { "name": "Batchfile", "bytes": "6422" }, { "name": "Dockerfile", "bytes": "4853" }, { "name": "FreeMarker", "bytes": "10653" }, { "name": "Go", "bytes": "3209" }, { "name": "Java", "bytes": "6273596" }, { "name": "JavaScript", "bytes": "1367" }, { "name": "Lua", "bytes": "8229" }, { "name": "Makefile", "bytes": "6045" }, { "name": "PHP", "bytes": "1052" }, { "name": "Python", "bytes": "8798" }, { "name": "Shell", "bytes": "32763" }, { "name": "TypeScript", "bytes": "2515" } ], "symlink_target": "" }
package com.github.walterfan.kanban.domain; public class Criteria { public String criteriaCode; public int sn; public int year; public String toString() { return criteriaCode + " " + sn + "-" + year; } } class GB extends Criteria { public GB() { criteriaCode = "GB"; } public String toString() { return super.toString(); } } class ZB extends GB { public ZB() { criteriaCode = "ZB"; } public String professionCode; public String classificationCode; public String toString() { return criteriaCode + " " + professionCode+ " " + classificationCode + " " + sn + "-" + year; } } class DB extends GB { public DB() { criteriaCode = "DB"; } public String regionCode; public String areaCode; public String professionCode; public String kindCode; public String toString() { return criteriaCode + " " + regionCode + "" + areaCode + " " + professionCode+ " " + kindCode + " " + sn + "-" + year; } } class QB extends GB { public QB() { criteriaCode = "Q"; } public String toString() { return super.toString(); } }
{ "content_hash": "51810ba8ecd4903563d7157ce58499e1", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 84, "avg_line_length": 17.833333333333332, "alnum_prop": 0.6420560747663552, "repo_name": "walterfan/pims4java", "id": "c60c39473aee7b51b22691909aa59664104a7d6e", "size": "1070", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/java/com/github/walterfan/kanban/domain/Criteria.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4835" }, { "name": "Java", "bytes": "261534" }, { "name": "JavaScript", "bytes": "5045" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("VkNet.Shared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("VkNet.Shared")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("646DE977-0B6F-4883-A93C-996B8F0F4AB6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "16eeec24ea451f5de96c816e561b52fa", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 38.77142857142857, "alnum_prop": 0.7406042741341193, "repo_name": "Soniclev/vk", "id": "113c9a8b6712b6ed5fbdfe7f0b1107d42d4f3826", "size": "1360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/VkNet.Shared/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4244252" } ], "symlink_target": "" }
package specification; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; /** * Created by Tomas Hanus on 4/11/2015. */ @XmlAccessorType(XmlAccessType.NONE) public class PartitionReducer { @XmlAttribute private String ref; @XmlElement private Properties properties; public PartitionReducer() { this.ref = new String(""); } public PartitionReducer(String ref, Properties properties) { this.ref = ref; this.properties = properties; } public String getRef() { return ref; } public void setRef(String ref) { this.ref = ref; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } }
{ "content_hash": "ba1ff9f7a76276e483a79ec7605bbd95", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 64, "avg_line_length": 21.74418604651163, "alnum_prop": 0.6748663101604279, "repo_name": "tmhanus/jVb-Designer-intellij-plugin", "id": "cac318c5eed9a0475b1411965d12055a3f54cda9", "size": "935", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/specification/PartitionReducer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "412530" } ], "symlink_target": "" }
- Add React 17 to the supported versions. - Some CI housekeeping # 2.0.7 - Make RenderProp typing more generic (#221) Thanks @leabaertschi # 2.0.6 - Add offset to Typescript definitions (#219) Thanks @tomeightyeight # 2.0.5 - Add targetAttachment to Typescript definitions (#217). Thanks @ilyamkin # 2.0.4 - Added constraints property to Typescript type definitions. Thanks @JabbyPanda - Improved stability of class names on the tethered element. Thanks @j3tan # 2.0.3 - Fixed target rendering in SSR. Thanks @reintroducing # 2.0.2 - Fixed attachment property in TypeScript defintion. Thanks @dylan-baskind ### 2.0.1 - Fix unnecessary DOM mutations in render, which caused unexpected behaviour. Thanks @NilSet ### 2.0.0 **Breaking changes** New API which supports React Suspense and Concurrent rendering. See the README for the new render prop based API. Please not that you now have to manually pass refs to your components. This change also comes with a deprecation of older versions of React. If you want to use 2+ you must be on React 16.3+. For older versions please stick to version 1 of react-tether or see the [1.x branch](https://github.com/danreeves/react-tether/tree/1.x). A big thanks to @CorinChappy for all their work on this! ### 1.0.4 - Fixed passing of event arguments to onUpdate and onRepositioned. Thanks @minznerjosh - Improved TypeScript definition. Thanks @minznerjosh ### 1.0.3 - Added some missing props in the TypeScript definition. Thanks to @flacerdk ### 1.0.2 - Some rendering optimisations (#189). Thanks to @eaglus ### 1.0.1 - Add `className` to the TypeScript definition for the TetherComponent. Thanks @ryprice ### 1.0.0 - Use `React.createPortal` :tada: Big thanks to @doronbrikman for their work on this. In versions where `createPortal` isn't available we still fall back to the old method. - Default export has changed: You can now use the default export in ES Modules and TypeScript, but in CommonJS environments you'll have to use `require('react-tether').default`. See [the examples](./example/tests/). - TypeScript definition file built in - Upgrade to Webpack 4 for the UMD distribution. Smaller bundle sizes! - Internal: New unit and E2E tests with code coverage, a [new demo page](https://danreeves.github.io/react-tether/), linting and prettier applied to the source, publishing less files to npm. - :crying_cat_face: Dropped bower support. Recommended upgrade path is either npm or [unpkg](https://unpkg.com/react-tether@0.6.1/lib/react-tether.js) ### 0.6.1 - Upgrade tether to 1.4.3 [#63](https://github.com/danreeves/react-tether/pull/63) ### 0.6.0 - Update compatibility for React 16 [#57](https://github.com/souporserious/react-tether/pull/57) - Update repo to point at danreeves/react-tether ### 0.5.7 Update the target node when updating the component [PR #48](https://github.com/souporserious/react-tether/pull/48) Compatibility React 15.5.0 [PR #49](https://github.com/souporserious/react-tether/pull/49) ### 0.5.6 Properly call `onUpdate` and `onRepositioned` [PR #40](https://github.com/souporserious/react-tether/pull/40) Only render subtree if `destroy` method was not called yet [PR #41](https://github.com/souporserious/react-tether/pull/41) Use `babel-plugin-add-module-exports` for `dist` files ### 0.5.5 Add `.npmignore` [PR #39](https://github.com/souporserious/react-tether/pull/39) ### 0.5.4 Expose Tether event system as imperative and props API [PR #30](https://github.com/souporserious/react-tether/pull/30) Update tether version to 1.3.7 [PR #32](https://github.com/souporserious/react-tether/pull/32) Attachment positions [PR #33](https://github.com/souporserious/react-tether/pull/33) ### 0.5.2 Better `renderElementTo` [PR #19](https://github.com/souporserious/react-tether/pull/19) Use `Children.toArray` instead of `Children.forEach` to get individual children ### 0.5.1 Fixed Tether element props not being re-rendered on change ### 0.5.0 Added the ability to apply an `id`, `className`, or `style` to the wrapper Tether element. ### 0.4.0 Fixes: `renderElementTo` now uses `document.querySelector` Add dependency warning for people using old school script tags ### 0.3.3 Fix ASI issue with document.body [PR #12](https://github.com/souporserious/react-tether/pull/12) ### 0.3.2 Fixes: - Unmount node only if it was mounted [#8](https://github.com/souporserious/react-tether/issues/8) - Lazily evaluate document.body [#6](https://github.com/souporserious/react-tether/issues/6) - Server-side rendering [#4](https://github.com/souporserious/react-tether/issues/4) ### 0.3.1 Fix tethered element not being positioned correctly ### 0.3.0 All [Tether options](http://tether.io/#options) are now props `renderElementTag` prop to specify which DOM tag to use to render the second child to `renderElementTo` prop to specify where in the DOM the element should be appended to Added `position` public method from Tether removed `shallowCompare` ### 0.2.0 Bower exposed lib name renamed to `TetherComponent` from `TetherElement` New API accepts a max of two children. First child is used as the target and second child is used as the element that is being tethered.
{ "content_hash": "dc8cad9d315dc3c4b6ac5efa70087d79", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 257, "avg_line_length": 33.3525641025641, "alnum_prop": 0.7499519507976168, "repo_name": "souporserious/react-tether", "id": "cf8c667ab2edececff3d095df67b09e66a0e9e2d", "size": "5226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "504" }, { "name": "HTML", "bytes": "184" }, { "name": "JavaScript", "bytes": "12813" } ], "symlink_target": "" }
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_VECTOR_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_VECTOR_H_ #include <string.h> #include <algorithm> #include <initializer_list> #include <iterator> #include <utility> #include "base/compiler_specific.h" #include "base/dcheck_is_on.h" #include "base/template_util.h" #include "build/build_config.h" #include "third_party/blink/renderer/platform/wtf/allocator/partition_allocator.h" #include "third_party/blink/renderer/platform/wtf/assertions.h" #include "third_party/blink/renderer/platform/wtf/atomic_operations.h" #include "third_party/blink/renderer/platform/wtf/conditional_destructor.h" #include "third_party/blink/renderer/platform/wtf/construct_traits.h" #include "third_party/blink/renderer/platform/wtf/container_annotations.h" #include "third_party/blink/renderer/platform/wtf/forward.h" // For default Vector template parameters. #include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" #include "third_party/blink/renderer/platform/wtf/vector_traits.h" #include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" // For ASAN builds, disable inline buffers completely as they cause various // issues. #ifdef ANNOTATE_CONTIGUOUS_CONTAINER #define INLINE_CAPACITY 0 #else #define INLINE_CAPACITY inlineCapacity #endif namespace WTF { #if defined(MEMORY_TOOL_REPLACES_ALLOCATOR) // The allocation pool for nodes is one big chunk that ASAN has no insight // into, so it can cloak errors. Make it as small as possible to force nodes // to be allocated individually where ASAN can see them. static const wtf_size_t kInitialVectorSize = 1; #else static const wtf_size_t kInitialVectorSize = 4; #endif template <typename T, wtf_size_t inlineBuffer, typename Allocator> class Deque; // // Vector Traits // // Bunch of traits for Vector are defined here, with which you can customize // Vector's behavior. In most cases the default traits are appropriate, so you // usually don't have to specialize those traits by yourself. // // The behavior of the implementation below can be controlled by VectorTraits. // If you want to change the behavior of your type, take a look at VectorTraits // (defined in VectorTraits.h), too. // Tracing assumes the entire backing store is safe to access. To guarantee // that, tracing a backing store starts by marking the whole backing store // capacity as accessible. With concurrent marking enabled, annotating size // changes could conflict with marking the whole store as accessible, causing // a race. #if defined(ADDRESS_SANITIZER) #define MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, buffer, capacity, \ old_size, new_size) \ if (Allocator::kIsGarbageCollected && Allocator::IsIncrementalMarking()) { \ ANNOTATE_CHANGE_SIZE(buffer, capacity, 0, capacity); \ } else { \ ANNOTATE_CHANGE_SIZE(buffer, capacity, old_size, new_size) \ } #define MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, buffer, capacity, size) \ if (Allocator::kIsGarbageCollected && Allocator::IsIncrementalMarking()) { \ ANNOTATE_NEW_BUFFER(buffer, capacity, capacity); \ } else { \ ANNOTATE_NEW_BUFFER(buffer, capacity, size) \ } #else #define MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, buffer, capacity, \ old_size, new_size) \ ANNOTATE_CHANGE_SIZE(buffer, capacity, old_size, new_size) #define MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, buffer, capacity, size) \ ANNOTATE_NEW_BUFFER(buffer, capacity, size) #endif // defined(ADDRESS_SANITIZER) template <typename T> struct VectorElementComparer { STATIC_ONLY(VectorElementComparer); template <typename U> static bool CompareElement(const T& left, const U& right) { return left == right; } }; template <typename T> struct VectorElementComparer<std::unique_ptr<T>> { STATIC_ONLY(VectorElementComparer); template <typename U> static bool CompareElement(const std::unique_ptr<T>& left, const U& right) { return left.get() == right; } }; // A collection of all the traits used by Vector. This is basically an // implementation detail of Vector, and you probably don't want to change this. // If you want to customize Vector's behavior, you should specialize // VectorTraits instead (defined in VectorTraits.h). template <typename T, typename Allocator> struct VectorTypeOperations { STATIC_ONLY(VectorTypeOperations); using ConstructTraits = WTF::ConstructTraits<T, VectorTraits<T>, Allocator>; static void Destruct(T* begin, T* end) { if constexpr (VectorTraits<T>::kNeedsDestruction) { for (T* cur = begin; cur != end; ++cur) cur->~T(); } } static void Initialize(T* begin, T* end) { if constexpr (VectorTraits<T>::kCanInitializeWithMemset) { memset(begin, 0, reinterpret_cast<char*>(end) - reinterpret_cast<char*>(begin)); } else { for (T* cur = begin; cur != end; ++cur) ConstructTraits::Construct(cur); } } static void Move(T* const src, T* const src_end, T* const dst, bool has_inline_buffer = true) { if constexpr (VectorTraits<T>::kCanMoveWithMemcpy) { if (!LIKELY(src && dst)) return; size_t bytes = reinterpret_cast<const char*>(src_end) - reinterpret_cast<const char*>(src); if constexpr (Allocator::kIsGarbageCollected && IsTraceableInCollectionTrait<VectorTraits<T>>::value) AtomicWriteMemcpy(dst, src, bytes); else memcpy(dst, src, bytes); if (has_inline_buffer) ConstructTraits::NotifyNewElements(dst, src_end - src); } else { for (T *s = src, *d = dst; s != src_end; ++s, ++d) { T* newly_created = ConstructTraits::Construct(d, std::move(*s)); if (has_inline_buffer) ConstructTraits::NotifyNewElement(newly_created); s->~T(); } } } static void MoveOverlapping(T* const src, T* const src_end, T* const dst, bool has_inline_buffer = true) { if constexpr (VectorTraits<T>::kCanMoveWithMemcpy) { if (!LIKELY(src && dst)) return; if constexpr (Allocator::kIsGarbageCollected && IsTraceableInCollectionTrait<VectorTraits<T>>::value) { if (dst < src) { for (T *s = src, *d = dst; s < src_end; ++s, ++d) AtomicWriteMemcpy<sizeof(T)>(d, s); } else if (dst > src) { T* s = src_end - 1; T* d = dst + (s - src); for (; s >= src; --s, --d) AtomicWriteMemcpy<sizeof(T)>(d, s); } } else { memmove(dst, src, reinterpret_cast<const char*>(src_end) - reinterpret_cast<const char*>(src)); } if (has_inline_buffer) ConstructTraits::NotifyNewElements(dst, src_end - src); } else { if (dst < src) { Move(src, src_end, dst, has_inline_buffer); } else if (dst > src) { T* s = src_end - 1; T* d = dst + (s - src); for (; s >= src; --s, --d) { T* newly_created = ConstructTraits::Construct(d, std::move(*s)); if (has_inline_buffer) ConstructTraits::NotifyNewElement(newly_created); s->~T(); } } } } static void Swap(T* const src, T* const src_end, T* const dst) { if constexpr (!VectorTraits<T>::kCanMoveWithMemcpy) { std::swap_ranges(src, src_end, dst); } else if constexpr (Allocator::kIsGarbageCollected && IsTraceableInCollectionTrait<VectorTraits<T>>::value) { constexpr size_t boundary = std::max(alignof(T), sizeof(size_t)); alignas(boundary) char buf[sizeof(T)]; for (T *s = src, *d = dst; s < src_end; ++s, ++d) { memcpy(buf, d, sizeof(T)); AtomicWriteMemcpy<sizeof(T)>(d, s); AtomicWriteMemcpy<sizeof(T)>(s, buf); } } else { std::swap_ranges(reinterpret_cast<char*>(src), reinterpret_cast<char*>(src_end), reinterpret_cast<char*>(dst)); } const size_t len = src_end - src; ConstructTraits::NotifyNewElements(src, len); ConstructTraits::NotifyNewElements(dst, len); } static void Copy(const T* src, const T* src_end, T* dst) { if constexpr (!VectorTraits<T>::kCanCopyWithMemcpy) { std::copy(src, src_end, dst); } else if constexpr (Allocator::kIsGarbageCollected && IsTraceableInCollectionTrait<VectorTraits<T>>::value) { AtomicWriteMemcpy(dst, src, reinterpret_cast<const char*>(src_end) - reinterpret_cast<const char*>(src)); } else { memcpy(dst, src, reinterpret_cast<const char*>(src_end) - reinterpret_cast<const char*>(src)); } } template <typename U> static void UninitializedCopy(const U* src, const U* src_end, T* dst) { if constexpr (std::is_same_v<T, U> && VectorTraits<T>::kCanCopyWithMemcpy) { if (!LIKELY(dst && src)) return; Copy(src, src_end, dst); ConstructTraits::NotifyNewElements(dst, src_end - src); } else { while (src != src_end) { ConstructTraits::ConstructAndNotifyElement(dst, *src); ++dst; ++src; } } } static void UninitializedFill(T* dst, T* dst_end, const T& val) { if constexpr (VectorTraits<T>::kCanFillWithMemset) { static_assert(sizeof(T) == sizeof(char), "size of type should be one"); memset(dst, val, dst_end - dst); } else { while (dst != dst_end) { ConstructTraits::ConstructAndNotifyElement(dst, T(val)); ++dst; } } } static bool Compare(const T* a, const T* b, size_t size) { DCHECK(a); DCHECK(b); if constexpr (VectorTraits<T>::kCanCompareWithMemcmp) return memcmp(a, b, sizeof(T) * size) == 0; else return std::equal(a, a + size, b); } template <typename U> static bool CompareElement(const T& left, U&& right) { return VectorElementComparer<T>::CompareElement(left, std::forward<U>(right)); } }; // // VectorBuffer // // VectorBuffer is an implementation detail of Vector and Deque. It manages // Vector's underlying buffer, and does operations like allocation or // expansion. // // Not meant for general consumption. template <typename T, typename Allocator> class VectorBufferBase { DISALLOW_NEW(); public: VectorBufferBase(VectorBufferBase&&) = default; VectorBufferBase& operator=(VectorBufferBase&&) = default; void AllocateBufferNoBarrier(wtf_size_t new_capacity) { DCHECK(new_capacity); DCHECK_LE(new_capacity, Allocator::template MaxElementCountInBackingStore<T>()); size_t size_to_allocate = AllocationSize(new_capacity); AsAtomicPtr(&buffer_)->store( Allocator::template AllocateVectorBacking<T>(size_to_allocate), std::memory_order_relaxed); capacity_ = static_cast<wtf_size_t>(size_to_allocate / sizeof(T)); } void AllocateBuffer(wtf_size_t new_capacity) { AllocateBufferNoBarrier(new_capacity); Allocator::BackingWriteBarrier(&buffer_); } size_t AllocationSize(size_t capacity) const { return Allocator::template QuantizedSize<T>(capacity); } T* Buffer() { return buffer_; } const T* Buffer() const { return buffer_; } wtf_size_t capacity() const { return capacity_; } static constexpr bool NeedsToClearUnusedSlots() { // Tracing and finalization access all slots of a vector backing. In case // there's work to be done there unused slots should be cleared. return Allocator::kIsGarbageCollected && (IsTraceableInCollectionTrait<VectorTraits<T>>::value || VectorTraits<T>::kNeedsDestruction); } void ClearUnusedSlots(T* from, T* to) { if constexpr (NeedsToClearUnusedSlots()) { AtomicMemzero(reinterpret_cast<void*>(from), sizeof(T) * (to - from)); } } void CheckUnusedSlots(const T* from, const T* to) { #if DCHECK_IS_ON() && !defined(ANNOTATE_CONTIGUOUS_CONTAINER) if constexpr (NeedsToClearUnusedSlots()) { const unsigned char* unused_area = reinterpret_cast<const unsigned char*>(from); const unsigned char* end_address = reinterpret_cast<const unsigned char*>(to); DCHECK_GE(end_address, unused_area); for (; unused_area != end_address; ++unused_area) DCHECK(!*unused_area); } #endif } void MoveBufferInto(VectorBufferBase& other) { AsAtomicPtr(&other.buffer_)->store(buffer_, std::memory_order_relaxed); other.capacity_ = capacity_; } // |end| is exclusive, a la STL. struct OffsetRange final { OffsetRange() : begin(0), end(0) {} explicit OffsetRange(wtf_size_t begin, wtf_size_t end) : begin(begin), end(end) { DCHECK_LE(begin, end); } bool empty() const { return begin == end; } wtf_size_t begin; wtf_size_t end; }; protected: static VectorBufferBase AllocateTemporaryBuffer(wtf_size_t capacity) { VectorBufferBase buffer; buffer.AllocateBufferNoBarrier(capacity); return buffer; } VectorBufferBase() : buffer_(nullptr), capacity_(0) {} VectorBufferBase(T* buffer, wtf_size_t capacity) : buffer_(buffer), capacity_(capacity) {} VectorBufferBase(HashTableDeletedValueType value) : buffer_(reinterpret_cast<T*>(-1)) {} bool IsHashTableDeletedValue() const { return buffer_ == reinterpret_cast<T*>(-1); } const T* BufferSafe() const { return AsAtomicPtr(&buffer_)->load(std::memory_order_relaxed); } T* buffer_; wtf_size_t capacity_; wtf_size_t size_; }; template <typename T, wtf_size_t inlineCapacity, typename Allocator = PartitionAllocator> class VectorBuffer; template <typename T, typename Allocator> class VectorBuffer<T, 0, Allocator> : protected VectorBufferBase<T, Allocator> { private: using Base = VectorBufferBase<T, Allocator>; public: using OffsetRange = typename Base::OffsetRange; VectorBuffer() = default; explicit VectorBuffer(wtf_size_t capacity) { // Calling malloc(0) might take a lock and may actually do an allocation // on some systems. if (capacity) AllocateBuffer(capacity); } void Destruct() { DeallocateBuffer(buffer_); buffer_ = nullptr; } void DeallocateBuffer(T* buffer_to_deallocate) { Allocator::FreeVectorBacking(buffer_to_deallocate); } bool ExpandBuffer(wtf_size_t new_capacity) { size_t size_to_allocate = AllocationSize(new_capacity); if (buffer_ && Allocator::ExpandVectorBacking(buffer_, size_to_allocate)) { capacity_ = static_cast<wtf_size_t>(size_to_allocate / sizeof(T)); return true; } return false; } inline bool ShrinkBuffer(wtf_size_t new_capacity) { DCHECK(buffer_); DCHECK_LT(new_capacity, capacity()); size_t size_to_allocate = AllocationSize(new_capacity); #ifdef ANNOTATE_CONTIGUOUS_CONTAINER ANNOTATE_DELETE_BUFFER(buffer_, capacity_, size_); #endif bool succeeded = false; if (Allocator::ShrinkVectorBacking(buffer_, AllocationSize(capacity()), size_to_allocate)) { capacity_ = static_cast<wtf_size_t>(size_to_allocate / sizeof(T)); succeeded = true; } #ifdef ANNOTATE_CONTIGUOUS_CONTAINER MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, buffer_, capacity_, size_); #endif return succeeded; } void ResetBufferPointer() { AsAtomicPtr(&buffer_)->store(nullptr, std::memory_order_relaxed); capacity_ = 0; } // See the other specialization for the meaning of |thisHole| and |otherHole|. // They are irrelevant in this case. void SwapVectorBuffer(VectorBuffer<T, 0, Allocator>& other, OffsetRange this_hole, OffsetRange other_hole) { static_assert(VectorTraits<T>::kCanSwapUsingCopyOrMove, "Cannot swap using copy or move."); AtomicWriteSwap(buffer_, other.buffer_); std::swap(capacity_, other.capacity_); std::swap(size_, other.size_); Allocator::BackingWriteBarrier(&buffer_); Allocator::BackingWriteBarrier(&other.buffer_); } using Base::AllocateBuffer; using Base::AllocationSize; using Base::Buffer; using Base::capacity; using Base::ClearUnusedSlots; using Base::CheckUnusedSlots; bool HasOutOfLineBuffer() const { // When inlineCapacity is 0 we have an out of line buffer if we have a // buffer. return IsOutOfLineBuffer(Buffer()); } T** BufferSlot() { return &buffer_; } const T* const* BufferSlot() const { return &buffer_; } protected: using Base::BufferSafe; using Base::size_; bool IsOutOfLineBuffer(const T* buffer) const { return buffer; } private: using Base::buffer_; using Base::capacity_; }; template <typename T, wtf_size_t inlineCapacity, typename Allocator> class VectorBuffer : protected VectorBufferBase<T, Allocator> { private: using Base = VectorBufferBase<T, Allocator>; public: using OffsetRange = typename Base::OffsetRange; VectorBuffer() : Base(InlineBuffer(), inlineCapacity) { InitInlinedBuffer(); } explicit VectorBuffer(HashTableDeletedValueType value) : Base(value) { InitInlinedBuffer(); } bool IsHashTableDeletedValue() const { return Base::IsHashTableDeletedValue(); } explicit VectorBuffer(wtf_size_t capacity) : Base(InlineBuffer(), inlineCapacity) { InitInlinedBuffer(); if (capacity > inlineCapacity) Base::AllocateBuffer(capacity); } VectorBuffer(const VectorBuffer&) = delete; VectorBuffer& operator=(const VectorBuffer&) = delete; void Destruct() { DeallocateBuffer(buffer_); buffer_ = nullptr; } NOINLINE void ReallyDeallocateBuffer(T* buffer_to_deallocate) { Allocator::FreeVectorBacking(buffer_to_deallocate); } void DeallocateBuffer(T* buffer_to_deallocate) { if (UNLIKELY(buffer_to_deallocate != InlineBuffer())) ReallyDeallocateBuffer(buffer_to_deallocate); } bool ExpandBuffer(wtf_size_t new_capacity) { DCHECK_GT(new_capacity, inlineCapacity); if (buffer_ == InlineBuffer()) return false; size_t size_to_allocate = AllocationSize(new_capacity); if (buffer_ && Allocator::ExpandVectorBacking(buffer_, size_to_allocate)) { capacity_ = static_cast<wtf_size_t>(size_to_allocate / sizeof(T)); return true; } return false; } inline bool ShrinkBuffer(wtf_size_t new_capacity) { DCHECK(buffer_); DCHECK_LT(new_capacity, capacity()); if (new_capacity <= inlineCapacity) { // We need to switch to inlineBuffer. Vector::ShrinkCapacity will // handle it. return false; } DCHECK_NE(buffer_, InlineBuffer()); size_t new_size = AllocationSize(new_capacity); bool succeeded = false; #ifdef ANNOTATE_CONTIGUOUS_CONTAINER ANNOTATE_DELETE_BUFFER(buffer_, capacity_, size_); #endif if (Allocator::ShrinkVectorBacking(buffer_, AllocationSize(capacity()), new_size)) { capacity_ = static_cast<wtf_size_t>(new_size / sizeof(T)); succeeded = true; } #ifdef ANNOTATE_CONTIGUOUS_CONTAINER MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, buffer_, capacity_, size_); #endif return succeeded; } void ResetBufferPointer() { AsAtomicPtr(&buffer_)->store(InlineBuffer(), std::memory_order_relaxed); capacity_ = inlineCapacity; } void AllocateBuffer(wtf_size_t new_capacity) { // FIXME: This should DCHECK(!buffer_) to catch misuse/leaks. if (new_capacity > inlineCapacity) Base::AllocateBuffer(new_capacity); else ResetBufferPointer(); } size_t AllocationSize(size_t capacity) const { if (capacity <= inlineCapacity) return kInlineBufferSize; return Base::AllocationSize(capacity); } // Swap two vector buffers, both of which have the same non-zero inline // capacity. // // If the data is in an out-of-line buffer, we can just pass the pointers // across the two buffers. If the data is in an inline buffer, we need to // either swap or move each element, depending on whether each slot is // occupied or not. // // Further complication comes from the fact that VectorBuffer is also used as // the backing store of a Deque. Deque allocates the objects like a ring // buffer, so there may be a "hole" (unallocated region) in the middle of the // buffer. This function assumes elements in a range [buffer_, buffer_ + // size_) are all allocated except for elements within |thisHole|. The same // applies for |other.buffer_| and |otherHole|. void SwapVectorBuffer(VectorBuffer<T, inlineCapacity, Allocator>& other, OffsetRange this_hole, OffsetRange other_hole) { using TypeOperations = VectorTypeOperations<T, Allocator>; static_assert(VectorTraits<T>::kCanSwapUsingCopyOrMove, "Cannot swap using copy or move."); if (Buffer() != InlineBuffer() && other.Buffer() != other.InlineBuffer()) { // The easiest case: both buffers are non-inline. We just need to swap the // pointers. AtomicWriteSwap(buffer_, other.buffer_); std::swap(capacity_, other.capacity_); std::swap(size_, other.size_); Allocator::BackingWriteBarrier(&buffer_); Allocator::BackingWriteBarrier(&other.buffer_); return; } Allocator::EnterGCForbiddenScope(); // Otherwise, we at least need to move some elements from one inline buffer // to another. // // Terminology: "source" is a place from which elements are copied, and // "destination" is a place to which elements are copied. thisSource or // otherSource can be empty (represented by nullptr) when this range or // other range is in an out-of-line buffer. // // We first record which range needs to get moved and where elements in such // a range will go. Elements in an inline buffer will go to the other // buffer's inline buffer. Elements in an out-of-line buffer won't move, // because we can just swap pointers of out-of-line buffers. T* this_source_begin = nullptr; wtf_size_t this_source_size = 0; T* this_destination_begin = nullptr; if (Buffer() == InlineBuffer()) { this_source_begin = Buffer(); this_source_size = size_; this_destination_begin = other.InlineBuffer(); if (!this_hole.empty()) { // Sanity check. DCHECK_LT(this_hole.begin, this_hole.end); DCHECK_LE(this_hole.end, this_source_size); } } else { // We don't need the hole information for an out-of-line buffer. this_hole.begin = this_hole.end = 0; } T* other_source_begin = nullptr; wtf_size_t other_source_size = 0; T* other_destination_begin = nullptr; if (other.Buffer() == other.InlineBuffer()) { other_source_begin = other.Buffer(); other_source_size = other.size_; other_destination_begin = InlineBuffer(); if (!other_hole.empty()) { DCHECK_LT(other_hole.begin, other_hole.end); DCHECK_LE(other_hole.end, other_source_size); } } else { other_hole.begin = other_hole.end = 0; } // Next, we mutate members and do other bookkeeping. We do pointer swapping // (for out-of-line buffers) here if we can. From now on, don't assume // buffer() or capacity() maintains their original values. std::swap(capacity_, other.capacity_); if (this_source_begin && !other_source_begin) { // Our buffer is inline, theirs is not. DCHECK_EQ(Buffer(), InlineBuffer()); DCHECK_NE(other.Buffer(), other.InlineBuffer()); ANNOTATE_DELETE_BUFFER(buffer_, inlineCapacity, size_); AsAtomicPtr(&buffer_)->store(other.Buffer(), std::memory_order_relaxed); AsAtomicPtr(&other.buffer_) ->store(other.InlineBuffer(), std::memory_order_relaxed); std::swap(size_, other.size_); MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, other.buffer_, inlineCapacity, other.size_); Allocator::BackingWriteBarrier(&buffer_); } else if (!this_source_begin && other_source_begin) { // Their buffer is inline, ours is not. DCHECK_NE(Buffer(), InlineBuffer()); DCHECK_EQ(other.Buffer(), other.InlineBuffer()); ANNOTATE_DELETE_BUFFER(other.buffer_, inlineCapacity, other.size_); AsAtomicPtr(&other.buffer_)->store(Buffer(), std::memory_order_relaxed); AsAtomicPtr(&buffer_)->store(InlineBuffer(), std::memory_order_relaxed); std::swap(size_, other.size_); MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, buffer_, inlineCapacity, size_); Allocator::BackingWriteBarrier(&other.buffer_); } else { // Both buffers are inline. DCHECK(this_source_begin); DCHECK(other_source_begin); DCHECK_EQ(Buffer(), InlineBuffer()); DCHECK_EQ(other.Buffer(), other.InlineBuffer()); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, buffer_, inlineCapacity, size_, other.size_); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, other.buffer_, inlineCapacity, other.size_, size_); std::swap(size_, other.size_); } // We are ready to move elements. We determine an action for each "section", // which is a contiguous range such that all elements in the range are // treated similarly. wtf_size_t section_begin = 0; while (section_begin < inlineCapacity) { // To determine the end of this section, we list up all the boundaries // where the "occupiedness" may change. wtf_size_t section_end = inlineCapacity; if (this_source_begin && section_begin < this_source_size) section_end = std::min(section_end, this_source_size); if (!this_hole.empty() && section_begin < this_hole.begin) section_end = std::min(section_end, this_hole.begin); if (!this_hole.empty() && section_begin < this_hole.end) section_end = std::min(section_end, this_hole.end); if (other_source_begin && section_begin < other_source_size) section_end = std::min(section_end, other_source_size); if (!other_hole.empty() && section_begin < other_hole.begin) section_end = std::min(section_end, other_hole.begin); if (!other_hole.empty() && section_begin < other_hole.end) section_end = std::min(section_end, other_hole.end); DCHECK_LT(section_begin, section_end); // Is the |sectionBegin|-th element of |thisSource| occupied? bool this_occupied = false; if (this_source_begin && section_begin < this_source_size) { // Yes, it's occupied, unless the position is in a hole. if (this_hole.empty() || section_begin < this_hole.begin || section_begin >= this_hole.end) this_occupied = true; } bool other_occupied = false; if (other_source_begin && section_begin < other_source_size) { if (other_hole.empty() || section_begin < other_hole.begin || section_begin >= other_hole.end) other_occupied = true; } if (this_occupied && other_occupied) { // Both occupied; swap them. In this case, one's destination must be the // other's source (i.e. both ranges are in inline buffers). DCHECK_EQ(this_destination_begin, other_source_begin); DCHECK_EQ(other_destination_begin, this_source_begin); TypeOperations::Swap(this_source_begin + section_begin, this_source_begin + section_end, other_source_begin + section_begin); } else if (this_occupied) { // Move from ours to theirs. TypeOperations::Move(this_source_begin + section_begin, this_source_begin + section_end, this_destination_begin + section_begin); Base::ClearUnusedSlots(this_source_begin + section_begin, this_source_begin + section_end); } else if (other_occupied) { // Move from theirs to ours. TypeOperations::Move(other_source_begin + section_begin, other_source_begin + section_end, other_destination_begin + section_begin); Base::ClearUnusedSlots(other_source_begin + section_begin, other_source_begin + section_end); } else { // Both empty; nothing to do. } section_begin = section_end; } Allocator::LeaveGCForbiddenScope(); } using Base::Buffer; using Base::capacity; bool HasOutOfLineBuffer() const { return IsOutOfLineBuffer(Buffer()); } T** BufferSlot() { return &buffer_; } const T* const* BufferSlot() const { return &buffer_; } protected: using Base::BufferSafe; using Base::size_; bool IsOutOfLineBuffer(const T* buffer) const { return buffer && buffer != InlineBuffer(); } private: using Base::buffer_; using Base::capacity_; static const wtf_size_t kInlineBufferSize = inlineCapacity * sizeof(T); T* InlineBuffer() { return unsafe_reinterpret_cast_ptr<T*>(inline_buffer_); } const T* InlineBuffer() const { return unsafe_reinterpret_cast_ptr<const T*>(inline_buffer_); } void InitInlinedBuffer() { if (Allocator::kIsGarbageCollected) { memset(&inline_buffer_, 0, kInlineBufferSize); } } alignas(T) char inline_buffer_[kInlineBufferSize]; template <typename U, wtf_size_t inlineBuffer, typename V> friend class Deque; }; // // Vector // // Vector is a container that works just like std::vector. WTF's Vector has // several extra functionalities: inline buffer, behavior customization via // traits, and Oilpan support. Those are explained in the sections below. // // Vector is the most basic container, which stores its element in a contiguous // buffer. The buffer is expanded automatically when necessary. The elements // are automatically moved to the new buffer. This event is called a // reallocation. A reallocation takes O(N)-time (N = number of elements), but // its occurrences are rare, so its time cost should not be significant, // compared to the time cost of other operations to the vector. // // Time complexity of key operations is as follows: // // * Indexed access -- O(1) // * Insertion or removal of an element at the end -- amortized O(1) // * Other insertion or removal -- O(N) // * Swapping with another vector -- O(1) // // 1. Iterator invalidation semantics // // Vector provides STL-compatible iterators and reverse iterators. Iterators // are _invalidated_ on certain occasions. Reading an invalidated iterator // causes undefined behavior. // // Iterators are invalidated on the following situations: // // * When a reallocation happens on a vector, all the iterators for that // vector will be invalidated. // * Some member functions invalidate part of the existing iterators for // the vector; see comments on the individual functions. // * [Oilpan only] Heap compaction invalidates all the iterators for any // HeapVectors. This means you can only store an iterator on stack, as // a local variable. // // In this context, pointers or references to an element of a Vector are // essentially equivalent to iterators, in that they also become invalid // whenever corresponding iterators are invalidated. // // 2. Inline buffer // // Vectors may have an _inline buffer_. An inline buffer is a storage area // that is contained in the vector itself, along with other metadata like // size_. It is used as a storage space when the vector's elements fit in // that space. If the inline buffer becomes full and further space is // necessary, an out-of-line buffer is allocated in the heap, and it will // take over the role of the inline buffer. // // The existence of an inline buffer is indicated by non-zero |inlineCapacity| // template argument. The value represents the number of elements that can be // stored in the inline buffer. Zero |inlineCapacity| means the vector has no // inline buffer. // // An inline buffer increases the size of the Vector instances, and, in trade // for that, it gives you several performance benefits, as long as the number // of elements do not exceed |inlineCapacity|: // // * No heap allocation will be made. // * Memory locality will improve. // // Generally, having an inline buffer is useful for vectors that (1) are // frequently accessed or modified, and (2) contain only a few elements at // most. // // 3. Behavior customization // // You usually do not need to customize Vector's behavior, since the default // behavior is appropriate for normal usage. The behavior is controlled by // VectorTypeOperations traits template above. Read VectorTypeOperations // and VectorTraits if you want to change the behavior for your types (i.e. // if you really want faster vector operations). // // The default traits basically do the following: // // * Skip constructor call and fill zeros with memset for simple types; // * Skip destructor call for simple types; // * Copy or move by memcpy for simple types; and // * Customize the comparisons for smart pointer types, so you can look // up a std::unique_ptr<T> element with a raw pointer, for instance. // // 4. Oilpan // // If you want to store garbage collected objects in Vector, (1) use HeapVector // (defined in HeapAllocator.h) instead of Vector, and (2) make sure your // garbage-collected type is wrapped with Member, like: // // HeapVector<Member<Node>> nodes; // // Unlike normal garbage-collected objects, a HeapVector object itself is // NOT a garbage-collected object, but its backing buffer is allocated in // Oilpan heap, and it may still carry garbage-collected objects. // // Even though a HeapVector object is not garbage-collected, you still need // to trace it, if you stored it in your class. Also, you can allocate it // as a local variable. This is useful when you want to build a vector locally // and put it in an on-heap vector with swap(). // // Also, heap compaction, which may happen at any time when Blink code is not // running (i.e. Blink code does not appear in the call stack), may invalidate // existing iterators for any HeapVectors. So, essentially, you should always // allocate an iterator on stack (as a local variable), and you should not // store iterators in another heap object. template <typename T, wtf_size_t inlineCapacity, typename Allocator> class Vector : private VectorBuffer<T, INLINE_CAPACITY, Allocator>, // ConditionalDestructor could in addition check for // VectorTraits<T>::kNeedsDestruction which requires that the complete // type is available though. Unfortunately, there's some use cases that // use Vector with foward-declared types. public ConditionalDestructor<Vector<T, INLINE_CAPACITY, Allocator>, (INLINE_CAPACITY == 0) && Allocator::kIsGarbageCollected> { USE_ALLOCATOR(Vector, Allocator); using Base = VectorBuffer<T, INLINE_CAPACITY, Allocator>; using TypeOperations = VectorTypeOperations<T, Allocator>; using OffsetRange = typename Base::OffsetRange; public: using ValueType = T; using value_type = T; using iterator = T*; using const_iterator = const T*; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; // Create an empty vector. inline Vector(); // Create a vector containing the specified number of default-initialized // elements. inline explicit Vector(wtf_size_t); // Create a vector containing the specified number of elements, each of which // is copy initialized from the specified value. inline Vector(wtf_size_t, const T&); // HashTable support Vector(HashTableDeletedValueType value) : Base(value) {} bool IsHashTableDeletedValue() const { return Base::IsHashTableDeletedValue(); } // Copying. Vector(const Vector&); template <wtf_size_t otherCapacity> explicit Vector(const Vector<T, otherCapacity, Allocator>&); Vector& operator=(const Vector&); template <wtf_size_t otherCapacity> Vector& operator=(const Vector<T, otherCapacity, Allocator>&); // Moving. Vector(Vector&&); Vector& operator=(Vector&&); // Construct with an initializer list. You can do e.g. // Vector<int> v({1, 2, 3}); // or // v = {4, 5, 6}; Vector(std::initializer_list<T> elements); Vector& operator=(std::initializer_list<T> elements); // Basic inquiry about the vector's state. // // capacity() is the maximum number of elements that the Vector can hold // without a reallocation. It can be zero. wtf_size_t size() const { return size_; } wtf_size_t capacity() const { return Base::capacity(); } size_t CapacityInBytes() const { return Base::AllocationSize(capacity()); } bool IsEmpty() const { return !size(); } // at() and operator[]: Obtain the reference of the element that is located // at the given index. The reference may be invalidated on a reallocation. // // at() can be used in cases like: // pointerToVector->at(1); // instead of: // (*pointerToVector)[1]; T& at(wtf_size_t i) { CHECK_LT(i, size()); return Base::Buffer()[i]; } const T& at(wtf_size_t i) const { CHECK_LT(i, size()); return Base::Buffer()[i]; } T& operator[](wtf_size_t i) { return at(i); } const T& operator[](wtf_size_t i) const { return at(i); } // Return a pointer to the front of the backing buffer. Those pointers get // invalidated on a reallocation. T* data() { return Base::Buffer(); } const T* data() const { return Base::Buffer(); } // Iterators and reverse iterators. They are invalidated on a reallocation. iterator begin() { return data(); } iterator end() { return begin() + size_; } const_iterator begin() const { return data(); } const_iterator end() const { return begin() + size_; } reverse_iterator rbegin() { return reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } // Quick access to the first and the last element. It is invalid to call // these functions when the vector is empty. T& front() { return at(0); } const T& front() const { return at(0); } T& back() { return at(size() - 1); } const T& back() const { return at(size() - 1); } // Searching. // // Comparisons are done in terms of compareElement(), which is usually // operator==(). find() and reverseFind() returns an index of the element // that is found first. If no match is found, kNotFound will be returned. template <typename U> bool Contains(const U&) const; template <typename U> wtf_size_t Find(const U&) const; template <typename U> wtf_size_t ReverseFind(const U&) const; // Resize the vector to the specified size. // // These three functions are essentially similar. They differ in that // (1) shrink() has a DCHECK to make sure the specified size is not more than // size(), and (2) grow() has a DCHECK to make sure the specified size is // not less than size(). // // When a vector shrinks, the extra elements in the back will be destructed. // All the iterators pointing to a to-be-destructed element will be // invalidated. // // When a vector grows, new elements will be added in the back, and they // will be default-initialized. A reallocation may happen in this case. void Shrink(wtf_size_t); void Grow(wtf_size_t); void resize(wtf_size_t); // Increase the capacity of the vector to at least |newCapacity|. The // elements in the vector are not affected. This function does not shrink // the size of the backing buffer, even if |newCapacity| is small. This // function may cause a reallocation. void ReserveCapacity(wtf_size_t new_capacity); // This is similar to reserveCapacity() but must be called immediately after // the vector is default-constructed. void ReserveInitialCapacity(wtf_size_t initial_capacity); // Shrink the backing buffer to |new_capacity|. This function may cause a // reallocation. void ShrinkCapacity(wtf_size_t new_capacity); // Shrink the backing buffer so it can contain exactly |size()| elements. // This function may cause a reallocation. void ShrinkToFit() { ShrinkCapacity(size()); } // Shrink the backing buffer if at least 50% of the vector's capacity is // unused. If it shrinks, the new buffer contains roughly 25% of unused // space. This function may cause a reallocation. void ShrinkToReasonableCapacity() { if (size() * 2 < capacity()) ShrinkCapacity(size() + size() / 4 + 1); } // Remove all the elements. This function actually releases the backing // buffer, thus any iterators will get invalidated (including begin()). REINITIALIZES_AFTER_MOVE void clear() { ShrinkCapacity(0); } // Insertion to the back. All of these functions except uncheckedAppend() may // cause a reallocation. // // push_back(value) // Insert a single element to the back. // emplace_back(args...) // Insert a single element constructed as T(args...) to the back. The // element is constructed directly on the backing buffer with placement // new. // Append(buffer, size) // AppendVector(vector) // AppendRange(begin, end) // Insert multiple elements represented by (1) |buffer| and |size| // (for append), (2) |vector| (for AppendVector), or (3) a pair of // iterators (for AppendRange) to the back. The elements will be copied. // UncheckedAppend(value) // Insert a single element like push_back(), but this function assumes // the vector has enough capacity such that it can store the new element // without a reallocation. Using this function could improve the // performance when you append many elements repeatedly. template <typename U> void push_back(U&&); template <typename... Args> T& emplace_back(Args&&...); ALWAYS_INLINE T& emplace_back() { Grow(size_ + 1); return back(); } template <typename U> void Append(const U*, wtf_size_t); template <typename U, wtf_size_t otherCapacity, typename V> void AppendVector(const Vector<U, otherCapacity, V>&); template <typename Iterator> void AppendRange(Iterator begin, Iterator end); template <typename U> void UncheckedAppend(U&&); // Insertion to an arbitrary position. All of these functions will take // O(size())-time. All of the elements after |position| will be moved to // the new locations. |position| must be no more than size(). All of these // functions may cause a reallocation. In any case, all the iterators // pointing to an element after |position| will be invalidated. // // insert(position, value) // Insert a single element at |position|, where |position| is an index. // insert(position, buffer, size) // InsertVector(position, vector) // Insert multiple elements represented by either |buffer| and |size| // or |vector| at |position|. The elements will be copied. // InsertAt(position, value) // Insert a single element at |position|, where |position| is an iterator. // InsertAt(position, buffer, size) // Insert multiple elements represented by either |buffer| and |size| // or |vector| at |position|. The elements will be copied. template <typename U> void insert(wtf_size_t position, U&&); template <typename U> void insert(wtf_size_t position, const U*, wtf_size_t); template <typename U> void InsertAt(iterator position, U&&); template <typename U> void InsertAt(iterator position, const U*, wtf_size_t); template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> void InsertVector(wtf_size_t position, const Vector<U, otherCapacity, OtherAllocator>&); // Insertion to the front. All of these functions will take O(size())-time. // All of the elements in the vector will be moved to the new locations. // All of these functions may cause a reallocation. In any case, all the // iterators pointing to any element in the vector will be invalidated. // // push_front(value) // Insert a single element to the front. // push_front(buffer, size) // PrependVector(vector) // Insert multiple elements represented by either |buffer| and |size| or // |vector| to the front. The elements will be copied. template <typename U> void push_front(U&&); template <typename U> void push_front(const U*, wtf_size_t); template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> void PrependVector(const Vector<U, otherCapacity, OtherAllocator>&); // Remove an element or elements at the specified position. These functions // take O(size())-time. All of the elements after the removed ones will be // moved to the new locations. All the iterators pointing to any element // after |position| will be invalidated. void EraseAt(wtf_size_t position); void EraseAt(wtf_size_t position, wtf_size_t length); iterator erase(iterator position); iterator erase(iterator first, iterator last); // This is to prevent compilation of deprecated calls like 'vector.erase(0)'. void erase(std::nullptr_t) = delete; // Remove the last element. Unlike remove(), (1) this function is fast, and // (2) only iterators pointing to the last element will be invalidated. Other // references will remain valid. void pop_back() { DCHECK(!IsEmpty()); Shrink(size() - 1); } // Filling the vector with the same value. If the vector has shrinked or // growed as a result of this call, those events may invalidate some // iterators. See comments for shrink() and grow(). // // Fill(value, size) will resize the Vector to |size|, and then copy-assign // or copy-initialize all the elements. // // Fill(value) is a synonym for Fill(value, size()). // // The implementation of Fill uses std::fill which is not yet supported for // garbage collected vectors. template <typename A = Allocator> std::enable_if_t<!A::kIsGarbageCollected> Fill(const T&, wtf_size_t); template <typename A = Allocator> std::enable_if_t<!A::kIsGarbageCollected> Fill(const T& val) { Fill(val, size()); } // Swap two vectors quickly. void swap(Vector& other) { Base::SwapVectorBuffer(other, OffsetRange(), OffsetRange()); } // Reverse the contents. void Reverse(); // Maximum element count supported; allocating a vector // buffer with a larger count will fail. static size_t MaxCapacity() { return Allocator::template MaxElementCountInBackingStore<T>(); } void Finalize() { static_assert(!Allocator::kIsGarbageCollected || INLINE_CAPACITY, "GarbageCollected collections without inline capacity cannot " "be finalized."); if (!INLINE_CAPACITY && LIKELY(!Base::Buffer())) { return; } ANNOTATE_DELETE_BUFFER(begin(), capacity(), size_); if (LIKELY(size_) && !(Allocator::kIsGarbageCollected && this->HasOutOfLineBuffer())) { TypeOperations::Destruct(begin(), end()); size_ = 0; // Partial protection against use-after-free. } // For garbage collected vector HeapAllocator::BackingFree() will bail out // during sweeping. Base::Destruct(); } template <typename VisitorDispatcher, typename A = Allocator> std::enable_if_t<A::kIsGarbageCollected> Trace(VisitorDispatcher) const; class GCForbiddenScope { STACK_ALLOCATED(); public: GCForbiddenScope() { Allocator::EnterGCForbiddenScope(); } ~GCForbiddenScope() { Allocator::LeaveGCForbiddenScope(); } }; protected: using Base::CheckUnusedSlots; using Base::ClearUnusedSlots; T** GetBufferSlot() { return Base::BufferSlot(); } const T* const* GetBufferSlot() const { return Base::BufferSlot(); } private: void ExpandCapacity(wtf_size_t new_min_capacity); T* ExpandCapacity(wtf_size_t new_min_capacity, T*); T* ExpandCapacity(wtf_size_t new_min_capacity, const T* data) { return ExpandCapacity(new_min_capacity, const_cast<T*>(data)); } template <typename U> U* ExpandCapacity(wtf_size_t new_min_capacity, U*); template <typename U> void AppendSlowCase(U&&); bool HasInlineBuffer() const { return INLINE_CAPACITY && !this->HasOutOfLineBuffer(); } void ReallocateBuffer(wtf_size_t); using Base::AllocateBuffer; using Base::AllocationSize; using Base::Buffer; using Base::BufferSafe; using Base::size_; using Base::SwapVectorBuffer; }; // // Vector out-of-line implementation // template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline Vector<T, inlineCapacity, Allocator>::Vector() { static_assert(!std::is_polymorphic<T>::value || !VectorTraits<T>::kCanInitializeWithMemset, "Cannot initialize with memset if there is a vtable"); static_assert(Allocator::kIsGarbageCollected || !IsDisallowNew<T>::value || !IsTraceable<T>::value, "Cannot put DISALLOW_NEW objects that " "have trace methods into an off-heap Vector"); static_assert( Allocator::kIsGarbageCollected || !IsMemberType<T>::value, "Cannot put Member into an off-heap Vector. Use HeapVector instead."); static_assert(Allocator::kIsGarbageCollected || !IsWeakMemberType<T>::value, "WeakMember is not allowed in Vector nor HeapVector."); static_assert(Allocator::kIsGarbageCollected || !IsPointerToGarbageCollectedType<T>::value, "Cannot put raw pointers to garbage-collected classes into " "an off-heap Vector. Use HeapVector<Member<T>> instead."); ANNOTATE_NEW_BUFFER(begin(), capacity(), 0); size_ = 0; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline Vector<T, inlineCapacity, Allocator>::Vector(wtf_size_t size) : Base(size) { static_assert(!std::is_polymorphic<T>::value || !VectorTraits<T>::kCanInitializeWithMemset, "Cannot initialize with memset if there is a vtable"); static_assert(Allocator::kIsGarbageCollected || !IsDisallowNew<T>::value || !IsTraceable<T>::value, "Cannot put DISALLOW_NEW objects that " "have trace methods into an off-heap Vector"); static_assert( Allocator::kIsGarbageCollected || !IsMemberType<T>::value, "Cannot put Member into an off-heap Vector. Use HeapVector instead."); static_assert(Allocator::kIsGarbageCollected || !IsWeakMemberType<T>::value, "WeakMember is not allowed in Vector nor HeapVector."); static_assert(Allocator::kIsGarbageCollected || !IsPointerToGarbageCollectedType<T>::value, "Cannot put raw pointers to garbage-collected classes into " "an off-heap Vector. Use HeapVector<Member<T>> instead."); ANNOTATE_NEW_BUFFER(begin(), capacity(), size); size_ = size; TypeOperations::Initialize(begin(), end()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline Vector<T, inlineCapacity, Allocator>::Vector(wtf_size_t size, const T& val) : Base(size) { static_assert(!std::is_polymorphic<T>::value || !VectorTraits<T>::kCanInitializeWithMemset, "Cannot initialize with memset if there is a vtable"); static_assert(Allocator::kIsGarbageCollected || !IsDisallowNew<T>::value || !IsTraceable<T>::value, "Cannot put DISALLOW_NEW objects that " "have trace methods into an off-heap Vector"); static_assert( Allocator::kIsGarbageCollected || !IsMemberType<T>::value, "Cannot put Member into an off-heap Vector. Use HeapVector instead."); static_assert(Allocator::kIsGarbageCollected || !IsWeakMemberType<T>::value, "WeakMember is not allowed in Vector nor HeapVector."); static_assert(Allocator::kIsGarbageCollected || !IsPointerToGarbageCollectedType<T>::value, "Cannot put raw pointers to garbage-collected classes into " "an off-heap Vector. Use HeapVector<Member<T>> instead."); ANNOTATE_NEW_BUFFER(begin(), capacity(), size); size_ = size; TypeOperations::UninitializedFill(begin(), end(), val); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> Vector<T, inlineCapacity, Allocator>::Vector(const Vector& other) : Base(other.capacity()) { ANNOTATE_NEW_BUFFER(begin(), capacity(), other.size()); size_ = other.size(); TypeOperations::UninitializedCopy(other.begin(), other.end(), begin()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <wtf_size_t otherCapacity> Vector<T, inlineCapacity, Allocator>::Vector( const Vector<T, otherCapacity, Allocator>& other) : Base(other.capacity()) { ANNOTATE_NEW_BUFFER(begin(), capacity(), other.size()); size_ = other.size(); TypeOperations::UninitializedCopy(other.begin(), other.end(), begin()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> Vector<T, inlineCapacity, Allocator>& Vector<T, inlineCapacity, Allocator>:: operator=(const Vector<T, inlineCapacity, Allocator>& other) { if (UNLIKELY(&other == this)) return *this; if (size() > other.size()) { Shrink(other.size()); } else if (other.size() > capacity()) { clear(); ReserveCapacity(other.size()); DCHECK(begin()); } MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, other.size()); TypeOperations::Copy(other.begin(), other.begin() + size(), begin()); TypeOperations::UninitializedCopy(other.begin() + size(), other.end(), end()); size_ = other.size(); return *this; } inline bool TypelessPointersAreEqual(const void* a, const void* b) { return a == b; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <wtf_size_t otherCapacity> Vector<T, inlineCapacity, Allocator>& Vector<T, inlineCapacity, Allocator>:: operator=(const Vector<T, otherCapacity, Allocator>& other) { // If the inline capacities match, we should call the more specific // template. If the inline capacities don't match, the two objects // shouldn't be allocated the same address. DCHECK(!TypelessPointersAreEqual(&other, this)); if (size() > other.size()) { Shrink(other.size()); } else if (other.size() > capacity()) { clear(); ReserveCapacity(other.size()); DCHECK(begin()); } MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, other.size()); TypeOperations::Copy(other.begin(), other.begin() + size(), begin()); TypeOperations::UninitializedCopy(other.begin() + size(), other.end(), end()); size_ = other.size(); return *this; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> Vector<T, inlineCapacity, Allocator>::Vector( Vector<T, inlineCapacity, Allocator>&& other) { size_ = 0; // It's a little weird to implement a move constructor using swap but this // way we don't have to add a move constructor to VectorBuffer. swap(other); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> Vector<T, inlineCapacity, Allocator>& Vector<T, inlineCapacity, Allocator>::operator=( Vector<T, inlineCapacity, Allocator>&& other) { // Explicitly clearing allows the backing to be freed // immediately. In the non-garbage-collected case this is // often just slightly moving it earlier as the old backing // would otherwise be freed in the destructor. For the // garbage-collected case this allows for freeing the backing // right away without introducing GC pressure. clear(); swap(other); return *this; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> Vector<T, inlineCapacity, Allocator>::Vector(std::initializer_list<T> elements) : Base(SafeCast<wtf_size_t>(elements.size())) { ANNOTATE_NEW_BUFFER(begin(), capacity(), elements.size()); size_ = static_cast<wtf_size_t>(elements.size()); TypeOperations::UninitializedCopy(elements.begin(), elements.end(), begin()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> Vector<T, inlineCapacity, Allocator>& Vector<T, inlineCapacity, Allocator>:: operator=(std::initializer_list<T> elements) { wtf_size_t input_size = SafeCast<wtf_size_t>(elements.size()); if (size() > input_size) { Shrink(input_size); } else if (input_size > capacity()) { clear(); ReserveCapacity(input_size); DCHECK(begin()); } MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, input_size); TypeOperations::Copy(elements.begin(), elements.begin() + size_, begin()); TypeOperations::UninitializedCopy(elements.begin() + size_, elements.end(), end()); size_ = input_size; return *this; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> bool Vector<T, inlineCapacity, Allocator>::Contains(const U& value) const { return Find(value) != kNotFound; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> wtf_size_t Vector<T, inlineCapacity, Allocator>::Find(const U& value) const { const T* b = begin(); const T* e = end(); for (const T* iter = b; iter < e; ++iter) { if (TypeOperations::CompareElement(*iter, value)) return static_cast<wtf_size_t>(iter - b); } return kNotFound; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> wtf_size_t Vector<T, inlineCapacity, Allocator>::ReverseFind( const U& value) const { const T* b = begin(); const T* iter = end(); while (iter > b) { --iter; if (TypeOperations::CompareElement(*iter, value)) return static_cast<wtf_size_t>(iter - b); } return kNotFound; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename A> std::enable_if_t<!A::kIsGarbageCollected> Vector<T, inlineCapacity, Allocator>::Fill(const T& val, wtf_size_t new_size) { if (size() > new_size) { Shrink(new_size); } else if (new_size > capacity()) { clear(); ReserveCapacity(new_size); DCHECK(begin()); } MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, new_size); std::fill(begin(), end(), val); TypeOperations::UninitializedFill(end(), begin() + new_size, val); size_ = new_size; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> void Vector<T, inlineCapacity, Allocator>::ExpandCapacity( wtf_size_t new_min_capacity) { wtf_size_t old_capacity = capacity(); wtf_size_t expanded_capacity = old_capacity; // We use a more aggressive expansion strategy for Vectors with inline // storage. This is because they are more likely to be on the stack, so the // risk of heap bloat is minimized. Furthermore, exceeding the inline // capacity limit is not supposed to happen in the common case and may // indicate a pathological condition or microbenchmark. if (INLINE_CAPACITY) { expanded_capacity *= 2; // Check for integer overflow, which could happen in the 32-bit build. CHECK_GT(expanded_capacity, old_capacity); } else { // This cannot integer overflow. // On 64-bit, the "expanded" integer is 32-bit, and any encroachment // above 2^32 will fail allocation in allocateBuffer(). On 32-bit, // there's not enough address space to hold the old and new buffers. In // addition, our underlying allocator is supposed to always fail on > // (2^31 - 1) allocations. expanded_capacity += (expanded_capacity / 4) + 1; } ReserveCapacity(std::max(new_min_capacity, std::max(kInitialVectorSize, expanded_capacity))); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> T* Vector<T, inlineCapacity, Allocator>::ExpandCapacity( wtf_size_t new_min_capacity, T* ptr) { if (ptr < begin() || ptr >= end()) { ExpandCapacity(new_min_capacity); return ptr; } size_t index = ptr - begin(); ExpandCapacity(new_min_capacity); return begin() + index; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> inline U* Vector<T, inlineCapacity, Allocator>::ExpandCapacity( wtf_size_t new_min_capacity, U* ptr) { ExpandCapacity(new_min_capacity); return ptr; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline void Vector<T, inlineCapacity, Allocator>::resize(wtf_size_t size) { if (size <= size_) { TypeOperations::Destruct(begin() + size, end()); ClearUnusedSlots(begin() + size, end()); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size); } else { if (size > capacity()) ExpandCapacity(size); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size); TypeOperations::Initialize(end(), begin() + size); } size_ = size; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> void Vector<T, inlineCapacity, Allocator>::Shrink(wtf_size_t size) { DCHECK_LE(size, size_); TypeOperations::Destruct(begin() + size, end()); ClearUnusedSlots(begin() + size, end()); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size); size_ = size; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> void Vector<T, inlineCapacity, Allocator>::Grow(wtf_size_t size) { DCHECK_GE(size, size_); if (size > capacity()) ExpandCapacity(size); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size); TypeOperations::Initialize(end(), begin() + size); size_ = size; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> void Vector<T, inlineCapacity, Allocator>::ReserveCapacity( wtf_size_t new_capacity) { if (UNLIKELY(new_capacity <= capacity())) return; if (!data()) { Base::AllocateBuffer(new_capacity); return; } if constexpr (Allocator::kIsGarbageCollected) { wtf_size_t old_capacity = capacity(); // Unpoison container annotations. Note that in the case of sizeof(T) < 8, // size_ = 1, old_capacity = 1, this may leave behind state in ASAN's shadow // memory. The additional transition after expanding ensures that this state // is cleared. // // Details see // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/asan/asan_poisoning.cpp#L354 MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), old_capacity, size_, old_capacity); if (Base::ExpandBuffer(new_capacity)) { // The following transition clears out old ASAN shadow memory state in the // case mentioned above. new_capacity = capacity(); DCHECK_LE(old_capacity, new_capacity); ANNOTATE_CHANGE_SIZE(begin(), new_capacity, old_capacity, new_capacity); // Finally, assuming new capacity, re-poison with the used size. ANNOTATE_CHANGE_SIZE(begin(), new_capacity, new_capacity, size_); return; } // In case expansion failed, there's no need to adjust container // annotations, as the buffer is freed right away. } // Reallocating a backing buffer may resurrect a dead object. CHECK(Allocator::IsAllocationAllowed()); ReallocateBuffer(new_capacity); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline void Vector<T, inlineCapacity, Allocator>::ReserveInitialCapacity( wtf_size_t initial_capacity) { DCHECK(!size_); DCHECK(capacity() == INLINE_CAPACITY); if (initial_capacity > INLINE_CAPACITY) { ANNOTATE_DELETE_BUFFER(begin(), capacity(), size_); Base::AllocateBuffer(initial_capacity); MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, begin(), capacity(), size_); } } template <typename T, wtf_size_t inlineCapacity, typename Allocator> void Vector<T, inlineCapacity, Allocator>::ShrinkCapacity( wtf_size_t new_capacity) { if (new_capacity >= capacity()) return; if (new_capacity < size()) Shrink(new_capacity); T* old_buffer = begin(); #ifdef ANNOTATE_CONTIGUOUS_CONTAINER wtf_size_t old_capacity = capacity(); #endif if (new_capacity > 0) { if (Base::ShrinkBuffer(new_capacity)) { return; } if (!Allocator::IsAllocationAllowed()) return; ReallocateBuffer(new_capacity); return; } Base::ResetBufferPointer(); #ifdef ANNOTATE_CONTIGUOUS_CONTAINER if (old_buffer != begin()) { MARKING_AWARE_ANNOTATE_NEW_BUFFER(Allocator, begin(), capacity(), size_); ANNOTATE_DELETE_BUFFER(old_buffer, old_capacity, size_); } #endif Base::DeallocateBuffer(old_buffer); } // Templatizing these is better than just letting the conversion happen // implicitly. template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> ALWAYS_INLINE void Vector<T, inlineCapacity, Allocator>::push_back(U&& val) { DCHECK(Allocator::IsAllocationAllowed()); if (LIKELY(size() != capacity())) { MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size_ + 1); ConstructTraits<T, VectorTraits<T>, Allocator>::ConstructAndNotifyElement( end(), std::forward<U>(val)); ++size_; return; } AppendSlowCase(std::forward<U>(val)); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename... Args> ALWAYS_INLINE T& Vector<T, inlineCapacity, Allocator>::emplace_back( Args&&... args) { DCHECK(Allocator::IsAllocationAllowed()); if (UNLIKELY(size() == capacity())) ExpandCapacity(size() + 1); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size_ + 1); T* t = ConstructTraits<T, VectorTraits<T>, Allocator>::ConstructAndNotifyElement( end(), std::forward<Args>(args)...); ++size_; return *t; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> void Vector<T, inlineCapacity, Allocator>::Append(const U* data, wtf_size_t data_size) { DCHECK(Allocator::IsAllocationAllowed()); wtf_size_t new_size = size_ + data_size; if (new_size > capacity()) { data = ExpandCapacity(new_size, data); DCHECK(begin()); } CHECK_GE(new_size, size_); T* dest = end(); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, new_size); TypeOperations::UninitializedCopy(data, &data[data_size], dest); size_ = new_size; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> NOINLINE void Vector<T, inlineCapacity, Allocator>::AppendSlowCase(U&& val) { DCHECK_EQ(size(), capacity()); typename std::remove_reference<U>::type* ptr = &val; ptr = ExpandCapacity(size() + 1, ptr); DCHECK(begin()); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size_ + 1); ConstructTraits<T, VectorTraits<T>, Allocator>::ConstructAndNotifyElement( end(), std::forward<U>(*ptr)); ++size_; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> inline void Vector<T, inlineCapacity, Allocator>::AppendVector( const Vector<U, otherCapacity, OtherAllocator>& val) { Append(val.begin(), val.size()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename Iterator> void Vector<T, inlineCapacity, Allocator>::AppendRange(Iterator begin, Iterator end) { for (Iterator it = begin; it != end; ++it) push_back(*it); } // This version of append saves a branch in the case where you know that the // vector's capacity is large enough for the append to succeed. template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> ALWAYS_INLINE void Vector<T, inlineCapacity, Allocator>::UncheckedAppend( U&& val) { #ifdef ANNOTATE_CONTIGUOUS_CONTAINER // Vectors in ASAN builds don't have inlineCapacity. push_back(std::forward<U>(val)); #else DCHECK_LT(size(), capacity()); ConstructTraits<T, VectorTraits<T>, Allocator>::ConstructAndNotifyElement( end(), std::forward<U>(val)); ++size_; #endif } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> inline void Vector<T, inlineCapacity, Allocator>::insert(wtf_size_t position, U&& val) { DCHECK(Allocator::IsAllocationAllowed()); CHECK_LE(position, size()); typename std::remove_reference<U>::type* data = &val; if (size() == capacity()) { data = ExpandCapacity(size() + 1, data); DCHECK(begin()); } MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size_ + 1); T* spot = begin() + position; TypeOperations::MoveOverlapping(spot, end(), spot + 1); ConstructTraits<T, VectorTraits<T>, Allocator>::ConstructAndNotifyElement( spot, std::forward<U>(*data)); ++size_; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> void Vector<T, inlineCapacity, Allocator>::insert(wtf_size_t position, const U* data, wtf_size_t data_size) { DCHECK(Allocator::IsAllocationAllowed()); CHECK_LE(position, size()); wtf_size_t new_size = size_ + data_size; if (new_size > capacity()) { data = ExpandCapacity(new_size, data); DCHECK(begin()); } CHECK_GE(new_size, size_); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, new_size); T* spot = begin() + position; TypeOperations::MoveOverlapping(spot, end(), spot + data_size); TypeOperations::UninitializedCopy(data, &data[data_size], spot); size_ = new_size; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> void Vector<T, inlineCapacity, Allocator>::InsertAt(T* position, U&& val) { insert(position - begin(), val); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> void Vector<T, inlineCapacity, Allocator>::InsertAt(T* position, const U* data, wtf_size_t data_size) { insert(position - begin(), data, data_size); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> inline void Vector<T, inlineCapacity, Allocator>::InsertVector( wtf_size_t position, const Vector<U, otherCapacity, OtherAllocator>& val) { insert(position, val.begin(), val.size()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> inline void Vector<T, inlineCapacity, Allocator>::push_front(U&& val) { insert(0, std::forward<U>(val)); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U> void Vector<T, inlineCapacity, Allocator>::push_front(const U* data, wtf_size_t data_size) { insert(0, data, data_size); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename U, wtf_size_t otherCapacity, typename OtherAllocator> inline void Vector<T, inlineCapacity, Allocator>::PrependVector( const Vector<U, otherCapacity, OtherAllocator>& val) { insert(0, val.begin(), val.size()); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline void Vector<T, inlineCapacity, Allocator>::EraseAt(wtf_size_t position) { CHECK_LT(position, size()); T* spot = begin() + position; spot->~T(); TypeOperations::MoveOverlapping(spot + 1, end(), spot); ClearUnusedSlots(end() - 1, end()); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size_ - 1); --size_; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline auto Vector<T, inlineCapacity, Allocator>::erase(iterator position) -> iterator { wtf_size_t index = static_cast<wtf_size_t>(position - begin()); EraseAt(index); return begin() + index; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline auto Vector<T, inlineCapacity, Allocator>::erase(iterator first, iterator last) -> iterator { DCHECK_LE(first, last); const wtf_size_t index = static_cast<wtf_size_t>(first - begin()); const wtf_size_t diff = static_cast<wtf_size_t>(std::distance(first, last)); EraseAt(index, diff); return begin() + index; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline void Vector<T, inlineCapacity, Allocator>::EraseAt(wtf_size_t position, wtf_size_t length) { SECURITY_DCHECK(position <= size()); if (!length) return; CHECK_LE(position + length, size()); T* begin_spot = begin() + position; T* end_spot = begin_spot + length; TypeOperations::Destruct(begin_spot, end_spot); TypeOperations::MoveOverlapping(end_spot, end(), begin_spot); ClearUnusedSlots(end() - length, end()); MARKING_AWARE_ANNOTATE_CHANGE_SIZE(Allocator, begin(), capacity(), size_, size_ - length); size_ -= length; } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline void Vector<T, inlineCapacity, Allocator>::Reverse() { for (wtf_size_t i = 0; i < size_ / 2; ++i) std::swap(at(i), at(size_ - 1 - i)); } template <typename T, wtf_size_t inlineCapacity, typename Allocator> inline void swap(Vector<T, inlineCapacity, Allocator>& a, Vector<T, inlineCapacity, Allocator>& b) { a.Swap(b); } template <typename T, wtf_size_t inlineCapacityA, wtf_size_t inlineCapacityB, typename Allocator> bool operator==(const Vector<T, inlineCapacityA, Allocator>& a, const Vector<T, inlineCapacityB, Allocator>& b) { if (a.size() != b.size()) return false; if (a.IsEmpty()) return true; return VectorTypeOperations<T, Allocator>::Compare(a.data(), b.data(), a.size()); } template <typename T, wtf_size_t inlineCapacityA, wtf_size_t inlineCapacityB, typename Allocator> inline bool operator!=(const Vector<T, inlineCapacityA, Allocator>& a, const Vector<T, inlineCapacityB, Allocator>& b) { return !(a == b); } namespace internal { template <typename Allocator, typename VisitorDispatcher, typename T> void TraceInlinedBuffer(VisitorDispatcher visitor, const T* buffer_begin, size_t capacity) { const T* buffer_end = buffer_begin + capacity; #ifdef ANNOTATE_CONTIGUOUS_CONTAINER // Vector can trace unused slots (which are already zeroed out). ANNOTATE_CHANGE_SIZE(buffer_begin, capacity, 0, capacity); #endif // ANNOTATE_CONTIGUOUS_CONTAINER for (const T* buffer_entry = buffer_begin; buffer_entry != buffer_end; buffer_entry++) { Allocator::template Trace<T, VectorTraits<T>>(visitor, *buffer_entry); } } template <typename Allocator, typename VisitorDispatcher, typename T, wtf_size_t inlineCapacity> void DeferredTraceImpl(VisitorDispatcher visitor, const void* object) { internal::TraceInlinedBuffer<Allocator>( visitor, reinterpret_cast<const T*>(object), inlineCapacity); } } // namespace internal // Only defined for HeapAllocator. Used when visiting vector object. template <typename T, wtf_size_t inlineCapacity, typename Allocator> template <typename VisitorDispatcher, typename A> std::enable_if_t<A::kIsGarbageCollected> Vector<T, inlineCapacity, Allocator>::Trace(VisitorDispatcher visitor) const { static_assert(Allocator::kIsGarbageCollected, "Garbage collector must be enabled."); const T* buffer = BufferSafe(); if (!buffer) { // Register the slot for heap compaction. Allocator::TraceVectorBacking(visitor, static_cast<T*>(nullptr), Base::BufferSlot()); return; } if (Base::IsOutOfLineBuffer(buffer)) { Allocator::TraceVectorBacking(visitor, buffer, Base::BufferSlot()); } else { // We should not visit inline buffers, but we still need to register the // slot for heap compaction. So, we pass nullptr to this method. Allocator::TraceVectorBacking(visitor, static_cast<T*>(nullptr), Base::BufferSlot()); // Bail out for concurrent marking. if (!VectorTraits<T>::kCanTraceConcurrently) { if (Allocator::DeferTraceToMutatorThreadIfConcurrent( visitor, buffer, internal::DeferredTraceImpl<Allocator, VisitorDispatcher, T, inlineCapacity>, inlineCapacity * sizeof(T))) { return; } } // Inline buffer requires tracing immediately. internal::TraceInlinedBuffer<Allocator>(visitor, buffer, inlineCapacity); } } template <typename T, wtf_size_t inlineCapacity, typename Allocator> void Vector<T, inlineCapacity, Allocator>::ReallocateBuffer( wtf_size_t new_capacity) { if (new_capacity <= INLINE_CAPACITY) { if (HasInlineBuffer()) { Base::ResetBufferPointer(); return; } // Shrinking to inline buffer from out-of-line one. T *old_begin = begin(), *old_end = end(); #ifdef ANNOTATE_CONTIGUOUS_CONTAINER const wtf_size_t old_capacity = capacity(); #endif Base::ResetBufferPointer(); TypeOperations::Move(old_begin, old_end, begin()); ClearUnusedSlots(old_begin, old_end); ANNOTATE_DELETE_BUFFER(old_begin, old_capacity, size_); Base::DeallocateBuffer(old_begin); return; } // Shrinking/resizing to out-of-line buffer. VectorBufferBase<T, Allocator> buffer = Base::AllocateTemporaryBuffer(new_capacity); ANNOTATE_NEW_BUFFER(buffer.Buffer(), buffer.capacity(), size_); // If there was a new out-of-line buffer allocated, there is no need in // calling write barriers for entries in that backing store as it is still // white. TypeOperations::Move(begin(), end(), buffer.Buffer(), HasInlineBuffer()); ClearUnusedSlots(begin(), end()); ANNOTATE_DELETE_BUFFER(begin(), capacity(), size_); Base::DeallocateBuffer(begin()); buffer.MoveBufferInto(*this); Allocator::BackingWriteBarrier(Base::BufferSlot()); } } // namespace WTF namespace base { #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ <= 7 // Workaround for g++7 and earlier family. // Due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80654, without this // absl::optional<WTF::Vector<T>> where T is non-copyable causes a compile // error. As we know it is not trivially copy constructible, explicitly declare // so. // // It completes the declaration in base/template_util.h that was provided // for std::vector template <typename T> struct is_trivially_copy_constructible<WTF::Vector<T>> : std::false_type {}; #endif } // namespace base using WTF::Vector; #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WTF_VECTOR_H_
{ "content_hash": "2738f0251db1067ad375bd62d8966299", "timestamp": "", "source": "github", "line_count": 2128, "max_line_length": 104, "avg_line_length": 37.952537593984964, "alnum_prop": 0.6620977427782524, "repo_name": "scheib/chromium", "id": "4473441931e675c86bf69801b76db8cd46d6f2bc", "size": "81632", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "third_party/blink/renderer/platform/wtf/vector.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.cn.jee.common.supcan.common.fonts; import com.cn.jee.common.supcan.annotation.common.fonts.SupFont; import com.cn.jee.common.utils.ObjectUtils; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; /** * 硕正TreeList Properties * @author WangZhen * @version 2013-11-04 */ @XStreamAlias("Font") public class Font { /** * 字体名称 微软雅黑 宋体 */ @XStreamAsAttribute private String faceName; /** * 字符集 134 */ @XStreamAsAttribute private String charSet; /** * Height(或size)是字体的尺寸,单位是字体的逻辑单位,通常采用小于0的数字, * 如果大于0,则高度不包含文字的内部行距(internal-leading)。 * 常用的尺寸是-8, -9, -10, -11, -12, -14, -16, -18, -20, -22, -24, -26, -28, -36, -48, -72; */ @XStreamAsAttribute private String height; /** * 字体加粗 weight=400/700 对应 非粗体/粗体; */ @XStreamAsAttribute private String weight; /** * 字体宽度 */ @XStreamAsAttribute private String width; /** * 字体斜体 */ @XStreamAsAttribute private String italic; /** * 字体下划线 */ @XStreamAsAttribute private String underline; public Font() { } public Font(SupFont supFont) { this(); ObjectUtils.annotationToObject(supFont, this); } public Font(String faceName) { this(); this.faceName = faceName; } public Font(String faceName, String charSet, String height) { this(faceName); this.charSet = charSet; this.height = height; } public Font(String faceName, String charSet, String height, String weight) { this(faceName, charSet, height); this.weight = weight; } public String getFaceName() { return faceName; } public void setFaceName(String faceName) { this.faceName = faceName; } public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getItalic() { return italic; } public void setItalic(String italic) { this.italic = italic; } public String getUnderline() { return underline; } public void setUnderline(String underline) { this.underline = underline; } }
{ "content_hash": "f76d0ee737594747705074ac6e9d079b", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 87, "avg_line_length": 16.93661971830986, "alnum_prop": 0.6864864864864865, "repo_name": "copy4dev/jee-base", "id": "8ef2cf6595b355e8a09464ab8b6cf1d76108340c", "size": "2709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/cn/jee/common/supcan/common/fonts/Font.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "3753" }, { "name": "ApacheConf", "bytes": "768" }, { "name": "Batchfile", "bytes": "936" }, { "name": "CSS", "bytes": "889012" }, { "name": "HTML", "bytes": "2486102" }, { "name": "Java", "bytes": "1081851" }, { "name": "JavaScript", "bytes": "7021996" }, { "name": "PHP", "bytes": "8060" } ], "symlink_target": "" }
using System; using NUnit.Framework; namespace ICSharpCode.NRefactory.CSharp.CodeCompletion { [TestFixture()] public class CodeCompletionOperatorTests : TestBase { [Test()] public void TestAddOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator+(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a + b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestSubtractOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator-(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a - b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestMultiplyOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator*(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a * b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestDivideOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator/(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a / b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestModulusOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator%(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a % b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestBitwiseAndOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator&(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a & b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestBitwiseOrOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator|(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a | b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestExclusiveOrOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator^(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a ^ b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestShiftLeftOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator<<(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a << b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestShiftRightOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator>>(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a >> b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestGreaterThanOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator>(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a > b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestGreaterThanOrEqualOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator>=(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a >= b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestEqualityOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator==(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a == b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestInEqualityOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator!=(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a != b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestLessThanOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator<(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a < b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestLessThanOrEqualOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator<=(A left, A right) { return new B (); } } class B { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); A b = new A (); $(a <= b).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestUnaryPlusOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator+(A left) { return new B (); } } class B : A { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); $(+a).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestUnaryMinusOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator-(A left) { return new B (); } } class B : A { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); $(-a).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestUnaryNotOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator!(A left) { return new B (); } } class B : A { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); $(!a).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } [Test()] public void TestUnaryBitwiseNotOperator () { CompletionDataList provider = CodeCompletionBugTests.CreateProvider ( @"class A { public static B operator~(A left) { return new B (); } } class B : A { public void BMethod () { } } class TestClass { public void Test () { A a = new A (); $(~a).$ } }"); Assert.IsNotNull (provider); Assert.IsNotNull (provider.Find ("BMethod")); } } }
{ "content_hash": "20af55d103f53336277f0b8883eac208", "timestamp": "", "source": "github", "line_count": 646, "max_line_length": 72, "avg_line_length": 13.789473684210526, "alnum_prop": 0.6109115401885945, "repo_name": "rfguri/vimfiles", "id": "d24cea6f5b24f0bae04417e61794a01b866dff38", "size": "10130", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "bundle/ycm/third_party/ycmd/third_party/OmniSharpServer/NRefactory/ICSharpCode.NRefactory.Tests/CSharp/CodeCompletion/CodeCompletionOperatorTests.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
FROM jenkins:2.19.1 ARG gituser=changeme ARG gitpass=changeme ARG dockerRegistryOrg=changeme ARG dockerRegistryUser=changeme ARG dockerRegistryPass=changeme ARG dockerRegistryEmail=changeme MAINTAINER Marcin Grzejszczak <mgrzejszczak@pivotal.io> COPY seed/init.groovy /usr/share/jenkins/ref/init.groovy COPY seed/jenkins_pipeline.groovy /usr/share/jenkins/jenkins_pipeline.groovy COPY seed/settings.xml /usr/share/jenkins/settings.xml COPY plugins.txt /usr/share/jenkins/plugins.txt COPY seed/k8s/* /usr/share/jenkins/cert/ USER root # Generated via `start.sh`. If you don't want to provide it just put empty # files there RUN printf "%s" "${gituser}" > /usr/share/jenkins/gituser && \ printf "%s" "${gitpass}" > /usr/share/jenkins/gitpass && \ printf "%s" "${gitsshkey}" > /usr/share/jenkins/gitsshkey && \ printf "%s" "${dockerRegistryUser}" > /usr/share/jenkins/dockerRegistryUser && \ printf "%s" "${dockerRegistryPass}" > /usr/share/jenkins/dockerRegistryPass && \ printf "%s" "${dockerRegistryEmail}" > /usr/share/jenkins/dockerRegistryEmail RUN chmod 400 /usr/share/jenkins/gitsshkey # Default mysql credentials - you can modify them as you please. You can # parametrize them so that values are not hardcoded RUN printf "%s" "rootpassword" > /usr/share/jenkins/mySqlRootPass && \ printf "%s" "username" > /usr/share/jenkins/mySqlPass && \ printf "%s" "password" > /usr/share/jenkins/mySqlUser USER root ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false \ -Djava.awt.headless=true \ -Dhudson.model.ParametersAction.keepUndefinedParameters=true # Install libs needed by the master worker for building apps RUN apt-get update && \ apt-get install -y ruby curl jq && \ apt-get clean # Install cf-cli RUN apt-get -y install apt-transport-https && \ wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | apt-key add - && \ echo "deb http://packages.cloudfoundry.org/debian stable main" | tee /etc/apt/sources.list.d/cloudfoundry-cli.list && \ apt-get -y update && \ apt-get -y install cf-cli # Install kubectl RUN curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl && \ chmod +x ./kubectl && \ mv ./kubectl /usr/local/bin/kubectl # Making docker in docker possible USER root RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get -y install apt-transport-https ca-certificates && \ echo "deb https://apt.dockerproject.org/repo debian-jessie main" | tee /etc/apt/sources.list.d/docker.list && \ apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D && \ DEBIAN_FRONTEND=noninteractive apt-get update && \ apt-get install --assume-yes docker-engine && \ echo "jenkins ALL=NOPASSWD: /usr/bin/docker" >> /etc/sudoers && \ echo "jenkins ALL=NOPASSWD: /usr/local/bin/docker-compose" >> /etc/sudoers && \ echo 'Defaults env_keep += "HOME"' >> /etc/sudoers # You can use Jenkins API to generate the list of plugins from a running # Jenkins instance: # # $ JENKINS_URL="http://user:pass@localhost:8080" # $ curl -sSL "${JENKINS_URL}/pluginManager/api/json?depth=1" | \ # jq -r '.plugins[] | .shortName +":"+ .version' | sort > plugins.txt # RUN install-plugins.sh $( paste -sd' ' /usr/share/jenkins/plugins.txt )
{ "content_hash": "a5c3fec8d04838ca5686f554fad4fb4f", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 179, "avg_line_length": 44.883116883116884, "alnum_prop": 0.7155671296296297, "repo_name": "ciberkleid/spring-cloud-pipelines", "id": "bc909ef6c01ae9cacdbb7b3977d17fd01c2babd6", "size": "3691", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "jenkins/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15018" }, { "name": "CSS", "bytes": "97317" }, { "name": "Groovy", "bytes": "162229" }, { "name": "HTML", "bytes": "32704" }, { "name": "JavaScript", "bytes": "233619" }, { "name": "Ruby", "bytes": "1587" }, { "name": "Shell", "bytes": "393831" } ], "symlink_target": "" }
This is a starter kit with "batteries included" to get you up and running with React and Flux more quickly. ## Usage Branches: * [`master`](https://github.com/SirCmpwn/react-starter-kit/tree/master) - empty starter kit * [`todo`](https://github.com/SirCmpwn/react-starter-kit/tree/todo) - simple Todo list example (you are here) To start your own React application based on this: git clone -b master https://github.com/SirCmpwn/react-starter-kit.git mv react-starter-kit my-awesome-app cd my-awesome-app ./bootstrap.sh ## What you get * Some no-brainer dependencies: * React * Flux (dispatcher) * Babel (ES6/ES7/JSX transpiling) * Underscore * A base Store class * An entry point ## Todo Example This isn't the usual TodoMVC style application. It's very very stripped down so that there's the minimal amount of code to read to grok it. You can get it like so: git clone -b todo https://github.com/SirCmpwn/react-starter-kit.git cd react-starter-kit npm install npm start # run dev server
{ "content_hash": "61e4bbf0e47fe00c55d9fc59a2f1a668", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 109, "avg_line_length": 29.055555555555557, "alnum_prop": 0.7170172084130019, "repo_name": "SirCmpwn/react-starter-kit", "id": "26340d02e46c436ccd136e7b83b75908e0e8a44f", "size": "1072", "binary": false, "copies": "1", "ref": "refs/heads/todo", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "230" }, { "name": "JavaScript", "bytes": "7051" } ], "symlink_target": "" }
param( # The filepath of the SVG to scale. [Parameter(Mandatory=$true)][string]$inputFile ) #Inkscape uses a baseline DPI of 90dpi = 100%, for some reason. $100scale = 90; $140scale = 126; $150scale = 135; $200scale = 180; $240scale = 216; $250scale = 225; $300scale = 270; $iosFolder = ".\do not commit\resources\ios"; $wp8Folder = ".\do not commit\resources\wp8"; $androidFolder = ".\do not commit\resources\android"; $androidFolderMdpi = ".\do not commit\resources\android\drawable-mdpi"; $androidFolderHdpi = ".\do not commit\resources\android\drawable-hdpi"; $androidFolderXhdpi = ".\do not commit\resources\android\drawable-xhdpi"; $androidFolderXXhdpi = ".\do not commit\resources\android\drawable-xxhdpi"; function ScaleImage($fullPath) { $fileName = [System.IO.Path]::GetFileNameWithoutExtension($fullPath); #Generate iOS images if(-not (Test-Path $iosFolder)) { New-Item -ItemType Directory -Force -Path $iosFolder | Out-Null; } $fullOutPath = CanonicalizePath "$($iosFolder)\$($fileName)"; StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).png`" -d $100scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath)@2x.png`" -d $200scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath)@3x.png`" -d $300scale" #Generate WP images if(-not (Test-Path $wp8Folder)) { New-Item -ItemType Directory -Force -Path $wp8Folder | Out-Null; } $fullOutPath = CanonicalizePath "$($wp8Folder)\$($fileName)"; StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-100.png`" -d $100scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-140.png`" -d $140scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-150.png`" -d $150scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-200.png`" -d $200scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-240.png`" -d $240scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-250.png`" -d $250scale" StartInkscape "-f `"$($fullPath)`" -e `"$($fullOutPath).scale-300.png`" -d $300scale" #loops are for suckers #Generate Android images if(-not( Test-Path $androidFolder)) { New-Item -ItemType Directory -Force -Path $androidFolder | Out-Null; } if(-not( Test-Path $androidFolderMdpi)) { New-Item -ItemType Directory -Force -Path $androidFolderMdpi | Out-Null; } if(-not( Test-Path $androidFolderHdpi)) { New-Item -ItemType Directory -Force -Path $androidFolderHdpi | Out-Null; } if(-not( Test-Path $androidFolderXHdpi)) { New-Item -ItemType Directory -Force -Path $androidFolderXHdpi | Out-Null; } if(-not( Test-Path $androidFolderXXhdpi)) { New-Item -ItemType Directory -Force -Path $androidFolderXXhdpi | Out-Null; } $mdpiPath = CanonicalizePath("$($androidFolderMdpi)\$($fileName)"); StartInkscape "-f `"$($fullPath)`" -e `"$($mdpiPath).png`" -d $100scale" $hdpiPath = CanonicalizePath("$($androidFolderHdpi)\$($fileName)"); StartInkscape "-f `"$($fullPath)`" -e `"$($hdpiPath).png`" -d $150scale" $xhdpiPath = CanonicalizePath("$($androidFolderXhdpi)\$($fileName)"); StartInkscape "-f `"$($fullPath)`" -e `"$($xhdpiPath).png`" -d $200scale" $xxhdpiPath = CanonicalizePath("$($androidFolderXXhdpi)\$($fileName)"); StartInkscape "-f `"$($fullPath)`" -e `"$($xxhdpiPath).png`" -d $300scale" } function StartInkscape($argString) { Write-Host "Processing svg with Inkscape...`n" $processInfo = New-Object System.Diagnostics.ProcessStartInfo; $processInfo.FileName = "inkscape.exe"; $processInfo.RedirectStandardError = $true; $processInfo.RedirectStandardOutput = $true; $processInfo.UseShellExecute = $false; $processInfo.Arguments = $argString; $process = New-Object System.Diagnostics.Process; $process.StartInfo = $processInfo; $process.Start() | Out-Null; $process.WaitForExit(); $stdout = $process.StandardOutput.ReadToEnd(); $stderr = $process.StandardError.ReadToEnd(); Write-Host $stdout Write-Host "Errors:`n$stderr" Write-Host "Done!`n"; } function CanonicalizePath($path) { $path = [System.IO.Path]::Combine( ((Get-Location).Path), ($path) ); $path = [System.IO.Path]::GetFullPath($path); return $path; } #Entry point is here: #Check for Inkscape if ((Get-Command "inkscape.exe" -ErrorAction SilentlyContinue) -eq $null) { Write-Host "Inkscape must be installed on the path (as inkscape.exe) for this script to work. Exiting..." return; } #normalize input path $fullPath = [System.IO.Path]::Combine( ((Get-Location).Path), ($inputFile) ); $fullPath = [System.IO.Path]::GetFullPath($fullPath); ScaleImage $fullPath;
{ "content_hash": "361704df9bb60fb2b577773304eee878", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 109, "avg_line_length": 42.901785714285715, "alnum_prop": 0.6568158168574402, "repo_name": "pingzing/k-christmas-2016", "id": "add4cf37d064de819a8d9b32f997cc654ce03200", "size": "4894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Generate-Assets.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "63639" }, { "name": "PowerShell", "bytes": "7314" } ], "symlink_target": "" }
 #include <aws/kinesisvideo/model/ChannelType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace KinesisVideo { namespace Model { namespace ChannelTypeMapper { static const int SINGLE_MASTER_HASH = HashingUtils::HashString("SINGLE_MASTER"); static const int FULL_MESH_HASH = HashingUtils::HashString("FULL_MESH"); ChannelType GetChannelTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == SINGLE_MASTER_HASH) { return ChannelType::SINGLE_MASTER; } else if (hashCode == FULL_MESH_HASH) { return ChannelType::FULL_MESH; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<ChannelType>(hashCode); } return ChannelType::NOT_SET; } Aws::String GetNameForChannelType(ChannelType enumValue) { switch(enumValue) { case ChannelType::SINGLE_MASTER: return "SINGLE_MASTER"; case ChannelType::FULL_MESH: return "FULL_MESH"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace ChannelTypeMapper } // namespace Model } // namespace KinesisVideo } // namespace Aws
{ "content_hash": "4a3ee967a4b9c801a2a34d478c86489a", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 92, "avg_line_length": 27.880597014925375, "alnum_prop": 0.6011777301927195, "repo_name": "cedral/aws-sdk-cpp", "id": "d3e18e7d415d211079eb616c31726a12490895e0", "size": "1987", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-kinesisvideo/source/model/ChannelType.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
<?php class ComproPago_Cash_Block_Form extends Mage_Payment_Block_Form { private $template = 'compropago/cash/form.phtml'; /** * ComproPago_Cash_Block_Form Constructor */ protected function _construct() { parent::_construct(); $this->setTemplate($this->template); } /** * Return the payment method * @return Mage_Payment_Model_Method_Abstract */ public function getMethod() { return parent::getMethod(); } /** * Render template for Payment Method Lebel in checkout * @return string */ public function getMethodLabelAfterHtml() { $mark = Mage::getConfig()->getBlockClassName('core/template'); $mark = new $mark; $mark->setTemplate('compropago/cash/mark.phtml'); return $mark->toHtml(); } }
{ "content_hash": "2ca6febb9fdfff623b12fe798e3a37f2", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 70, "avg_line_length": 23.333333333333332, "alnum_prop": 0.6011904761904762, "repo_name": "compropago/plugin-magento", "id": "313679c888166a0014e354d98137dba2ea9692e7", "size": "840", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/code/local/ComproPago/Cash/Block/Form.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "8961" }, { "name": "PHP", "bytes": "26791" }, { "name": "Shell", "bytes": "439" } ], "symlink_target": "" }
user node[:postgresql][:pguser] do action :create shell "/bin/bash" home "/home/#{node[:postgresql][:pguser]}" comment "Postgresql software owner" password "postgres" action :create end
{ "content_hash": "43fd79433a18bad2bf9e5d8753825cf4", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 43, "avg_line_length": 24, "alnum_prop": 0.7239583333333334, "repo_name": "ONSdigital/chef-cookbooks", "id": "5ea28c88f6e44c4d269b5797ed4d62951a17dd3d", "size": "348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cookbooks/otspostgresql-replication/recipes/users.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "140396" }, { "name": "Ruby", "bytes": "83752" }, { "name": "Shell", "bytes": "64497" } ], "symlink_target": "" }
public IList<IList<int>> SubsetsWithDup(int[] array){ List<IList<int>> res = new List<IList<int>>(); Array.Sort(array); BackTrack(res, array, new List<int>(), 0); return res; } public void BackTrack(List<IList<int>> res, int[] array, List<int> element, int index){ res.Add(new List<int>(element)); for(int i = index; i < array.Length; i++){ if(i > index && array[i] == array[i - 1]){ continue; } element.Add(array[i]); BackTrack(res, array, element, i + 1); element.RemoveAt(element.Count() - 1); } }
{ "content_hash": "95fb09a20323d2790b70382881793820", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 87, "avg_line_length": 34.11764705882353, "alnum_prop": 0.5741379310344827, "repo_name": "winterchow/winterchow.github.io", "id": "e8068241bbf5faa9e194effba0186c401dcfa375", "size": "580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Algorithm/Backtrack/SubsetII.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "26394" }, { "name": "Smalltalk", "bytes": "340" } ], "symlink_target": "" }
'use strict'; /** * @ngdoc service * @name helmeditor2App.MonomerLibraryService * @description * # MonomerLibraryService * Service in the helmeditor2App. */ angular.module('helmeditor2App.MonomerLibrary', ['cb.x2js']) .service('MonomerLibraryService', ['$http', 'x2js', function ($http, x2js) { // AngularJS will instantiate a singleton by calling 'new' on this function var self = this; self.initComplete = false; // the array of the polymer types in the database self.polymerTypes = []; // Hierarchy of monomer types, retrievable through the monomer library. See // milestone 1 documentation for reference var categorizedDB; var encodedDB; var linkedDB; // 'categories' property is an array of sub-categories, 'monomers' is the array of monomers $http.get('MonomerDBGZEncoded.xml', { transformResponse: function (info) { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers return x2js.xml_str2json(info); // jscs:enable requireCamelCaseOrUpperCaseIdentifiers } }).then(function (response) { encodedDB = response.data; // now get the categorization $http.get('DefaultMonomerCategorizationTemplate.xml', { transformResponse: function (info) { // jscs:disable requireCamelCaseOrUpperCaseIdentifiers return (x2js.xml_str2json(info)); // jscs:enable requireCamelCaseOrUpperCaseIdentifiers } }).then(function (response) { categorizedDB = response.data; // now link the two linkDatabases(); // create the new linked DB that reference the polymers by name // also flatten it, so that each level is an object with a label and an // array of either more objects (sub-levels) or just monomers linkedDB = {}; for (var i = 0; i < categorizedDB.Template.Polymer.length; i++) { // set up the properties (if they exist) linkedDB[categorizedDB.Template.Polymer[i]._name] = { _name: categorizedDB.Template.Polymer[i]._name, _shape: categorizedDB.Template.Polymer[i]._shape, _title: categorizedDB.Template.Polymer[i]._title, _fontColor: categorizedDB.Template.Polymer[i]._fontColor }; // and handle the children; linkedDB[categorizedDB.Template.Polymer[i]._name].categories = flattenGroup(categorizedDB.Template.Polymer[i], categorizedDB.Template.Polymer[i]); } self.initComplete = true; }); }); // extends/overrides the properties of the first object with those in the second // private helper function var extend = function(a, b) { var ret = {}; for (var keyA in a) { if (keyA !== 'Fragment' && keyA !== 'Monomer' && keyA !== 'FragmentGroup' && keyA !== 'MonomerGroup') { ret[keyA] = a[keyA]; } } for (var keyB in b) { // don't add the actual monomers in, that's handled elsewhere if (keyB !== 'Fragment' && keyB !== 'Monomer' && keyB !== 'FragmentGroup' && keyB !== 'MonomerGroup') { ret[keyB] = b[keyB]; } } return ret; }; // given a group, used recursively to flatten the group appropriately // returns an array of nested objects with arrays, or of Monomers // also passed the object of attributes to be included, if not specified // private helper function var flattenGroup = function (group, attrs) { // the base case is that there is simply an array of Monomer or Fragments if (group.Monomer || group.Fragment) { var monomers = group.Monomer || group.Fragment; if (!(monomers instanceof Array)) { monomers = [monomers]; } // add each monomer back, after extending the properties from the group var newMonomers = []; for (var i = 0; i < monomers.length; i++) { newMonomers.push(extend(attrs, monomers[i])); } return newMonomers; } // otherwise, we're dealing with a FragmentGroup or MonomerGroup else { // need to do this whole things for FragmentGroup and MonomerGroup var fragmentGroups = group.FragmentGroup; var monomerGroups = group.MonomerGroup; // make sure we have an array if (!fragmentGroups) { fragmentGroups = []; } else if (!(fragmentGroups instanceof Array)) { fragmentGroups = [fragmentGroups]; } if (!monomerGroups) { monomerGroups = []; } else if (!(monomerGroups instanceof Array)) { monomerGroups = [monomerGroups]; } // and flatten each of them var categories = []; var obj; for (var j = 0; j < fragmentGroups.length; j++) { obj = extend(attrs, fragmentGroups[j]); // recursively flatten into categories if groups if (fragmentGroups[j].MonomerGroup || fragmentGroups[j].FragmentGroup) { obj.categories = flattenGroup(fragmentGroups[j], obj); } // or monomers if not groups else { obj.monomers = flattenGroup(fragmentGroups[j], obj); } // add it categories.push(obj); } // repeat for the monomer groups for (var k = 0; k < monomerGroups.length; k++) { obj = extend(attrs, monomerGroups[k]); // recursively flatten into categories if groups if (monomerGroups[k].MonomerGroup || monomerGroups[k].FragmentGroup) { obj.categories = flattenGroup(monomerGroups[k], obj); } // or monomers if not groups else { obj.monomers = flattenGroup(monomerGroups[k], obj); } // add it categories.push(obj); } // return it return categories; } }; // links the two databases together, adding categorization detail to encoded database // private helper function var linkDatabases = function () { // first go through and create the 'Other' listing in each type createOtherCategories(); // now we need to go through the encoded database and add the data to the right place var encodedTypes = encodedDB.MONOMER_DB.PolymerList.Polymer; for (var i = 0; i < encodedTypes.length; i++) { var polymerType = encodedTypes[i]; // remember the type to be used later var type = polymerType._polymerType; var categorizedPolymerGroup; for (var j = 0; j < categorizedDB.Template.Polymer.length; j++) { var categorizedPolymer = categorizedDB.Template.Polymer[j]; if (categorizedPolymer._name.match(type)) { categorizedPolymerGroup = categorizedPolymer; break; } } // now go through all of the monomers in the encoded database and try to add them // to the categorized database var monomers = polymerType.Monomer; for (var k = 0; k < monomers.length; k++) { var monomer = monomers[k]; // if it wasn't added, we know we need to add it to the "other" group if (!addMonomerToGroup(monomer, categorizedPolymerGroup)) { addMonomerToOther(monomer, categorizedPolymerGroup); } } } // create the list of polymer types for (var l = 0; l < categorizedDB.Template.Polymer.length; l++) { self.polymerTypes.push(categorizedDB.Template.Polymer[l]._name); } // signal complete self.initComplete = true; }; // goes through the categorized database and adds the 'Other' category // private helper function var createOtherCategories = function () { // start at the top, and go through each category (RNA, PEPTIDE, CHEM) var categorizedPolymers = categorizedDB.Template.Polymer; for (var i = 0; i < categorizedPolymers.length; i++) { var polymerList = categorizedPolymers[i]; // prepare the categorized list to have an "Other" in the lowest level of MonomerGroup var current = polymerList.MonomerGroup; while (!(current instanceof Array)) { current = current.MonomerGroup; } // add it current.push({ Monomer: [], _name: 'Other', _shape: 'Rectangle' }); } }; // adds the given monomer to the correct location in the given group // private helper function var addMonomerToGroup = function (monomer, group) { // search for the ID in the given group return recursiveSearchAndAdd(monomer, group); }; // recursively searches down properties and indices to find the bottom // (an array of Monomer or Fragment objects) // returns true if the element was added // private helper function var recursiveSearchAndAdd = function (monomer, group) { // base case - array of Monomers or Fragment objects if (group.Monomer instanceof Array || group.Fragment instanceof Array) { var list = group.Monomer || group.Fragment; // go through all elements in the array and see if the ID matches for (var i = 0; i < list.length; i++) { // console.log(monomer.MonomerID); // it was found, so add the details and return true if (!list[i]._notation && list[i]._name === monomer.MonomerID) { list[i].encodedMonomer = monomer; return true; } // otherwise just go on to the next } } // also need to handle the case where there's a single element, not an array if ((group.Monomer && group.Monomer._name) || (group.Fragment && group.Fragment._name)) { var el = group.Monomer || group.Fragment; if (el._name === monomer.MonomerID) { el.encodedMonomer = monomer; return true; } } // if we have more groups underneath, we need to go deeper else if (group instanceof Array || group.FragmentGroup || group.MonomerGroup) { for (var key in group) { // jump out if it was added somehow if (recursiveSearchAndAdd(monomer, group[key])) { return true; } // otherwise keep going } // if we got here, we never found it, so return false; return false; } // also here we failed, too, finally return false; }; // adds the monomer to the "Other" group within the larger group provided // private helper function var addMonomerToOther = function (monomer, group) { var current = group.MonomerGroup; while (!(current instanceof Array)) { current = current.MonomerGroup; } // the other should be the last one in the group, but search just to be safe for (var i = 0; i < current.length; i++) { if (current[i]._name === 'Other') { current[i].Monomer.push({ _backgroundColor: 'White', _fontColor: 'Black', _name: monomer.MonomerID, encodedMonomer: monomer }); } } }; // return the default encoded database var getEncodedDB = function () { return encodedDB; }; // return the default categorization database var getCategorizedDB = function () { return categorizedDB; }; // return the linked (flattened/normalized) database var getLinkedDB = function () { return linkedDB; }; // returns the hierarchy of monomers by the given type (RNA, PEPTIDE, CHEM) // return an array of all sub-groupings, each grouping is an object with title, and any // sub-groupings under that var getMonomersByType = function (type) { return linkedDB[type]; }; // returns a list of monomers that match either the ID or the name // public function var searchMonomers = function (type, text) { // jump out if we don't have anything to search by if (text === null || text === '') { return []; } var results = []; var searchText = text.toLowerCase(); // go through all of the monomers, and push them on if the contain the text var group = getMonomersByType(type); results = searchRecursive(group, searchText); return results; }; // recursive method to either return the monomers that match, or // concatenate results of recursive calls on all categories var searchRecursive = function (group, text) { var results = []; // hanlde the case that we have monomers if (group.monomers) { for (var i = 0; i < group.monomers.length; i++) { if (group.monomers[i]._name.toLowerCase().indexOf(text) >= 0 || (group.monomers[i].encodedMonomer && group.monomers[i].encodedMonomer.MonomerName.toLowerCase().indexOf(text) >= 0)) { results.push(group.monomers[i]); } } } // otherwise need to concatenate the results from later calls else { for (var j = 0; j < group.categories.length; j++) { results = results.concat(searchRecursive(group.categories[j], text)); } } // return it return results; }; // retrieves the monomer specified by ID, from the encoded monomer database (does not include fragments) var getMonomerById = function (type, id) { var group = getMonomersByType(type); return searchRecursiveExact(group, id); }; var searchRecursiveExact = function (group, id) { // do we have monomers directly if (group.monomers) { for (var i = 0; i < group.monomers.length; i++) { if (!group.monomers[i]._notation && group.monomers[i]._name.toLowerCase() === id.toLowerCase()) { // found it return group.monomers[i]; } } } // otherwise, search deeper while we don't have an answer else { var res = null; var j = 0; while (!res && j < group.categories.length) { res = searchRecursiveExact(group.categories[j], id); j++; } return res; } }; // and return the methods we actually want to expose self.getCategorizedDB = getCategorizedDB; self.getEncodedDB = getEncodedDB; self.getLinkedDB = getLinkedDB; self.getMonomersByType = getMonomersByType; self.searchMonomers = searchMonomers; self.getMonomerById = getMonomerById; }]);
{ "content_hash": "d4fbec30ddaf37c726c3246c191f9bcb", "timestamp": "", "source": "github", "line_count": 395, "max_line_length": 156, "avg_line_length": 36.789873417721516, "alnum_prop": 0.6054913294797688, "repo_name": "CSCIE-599/HELM-Editor-UI", "id": "6f298005d7df3e6c929f3ab9fb18afb78fbae450", "size": "14532", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/scripts/services/monomerlibraryservice.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "1410" }, { "name": "HTML", "bytes": "8227" }, { "name": "JavaScript", "bytes": "19843" } ], "symlink_target": "" }
(function($_) { /** * @namespace * @name Asdf.Utils */ var o = $_.Core.namespace($_, 'Selector'); var expando = "expando" + 1 * new Date(); var booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attrs = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attrs + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attrs ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, matchFunction = { "ATTR": function(match){ match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); },"CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { throw new Error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { throw new Error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = $_.R.FN_NATIVE, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ) , funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; var _rbuggyMathches = []; /** * @type {number} * @private * @desc element id */ var _sid =1; var opposite = { 'parentNode': 'childNode', 'previousSibling':'nextSibling', 'childNode':'parentNode', 'nextSibling': 'previousSibling' }; var combinators = { ' ': function(node, token, eachCallback){ var item, i=0; var type = token[0].type; if(type === 'ID'){ item = $_.Element.getElementById(node, token[0].matches[0]); if(!item|| !_matchSelector(item, _matchFn(token.slice(1)))) return ; return eachCallback(item); } item = (type === 'CLASS')? ($_.Element.getElementsByClassName(node, $_.A.reduce(token, function(acc, v){ if(v.type === 'CLASS') {acc.push(v.matches[0]);i++;} return acc; },[]).join(' '))): type==='TAG'?$_.Element.getElementsByTagName(node, token[0].matches[0]):[]; return $_.A.each(item, function(el) { if(_matchSelector(el, _matchFn(token.slice(i||1)))) eachCallback(el); }); }, '>': function(node, token, eachCallback){ var item = $_.Element.children(node); return $_.A.each(item, function(el) { if( _matchSelector(el, _matchFn(token))) eachCallback(el); }); }, '+':function(node, token, eachCallback){ var item = $_.Element.next(node); if(!item|| !_matchSelector(item, _matchFn(token))) return ; return eachCallback(item); }, '~':function(node, token, eachCallback){ var item = $_.Element.nexts(node); return $_.A.each(item, function(el) { if( _matchSelector(el, _matchFn(token))) eachCallback(el); }); } }; var filters = { 'ID': function(id){ var attrId = id.replace( runescape, funescape ); return $_.Bom.features.getById? function(elem){ return elem.getAttribute("id") === attrId; }:function(elem){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; } }, 'TAG': function(tag){ var nodeName = tag.replace( runescape, funescape ).toLowerCase(); return tag === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, 'CLASS': $_.F.memoize(function(className){ var pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ); return function( elem ){ return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); } }, function(c){return c+ ' '}), 'ATTR': function(name, op, value){ return function(elem) { var res = $_.Element.attr(elem, name); if (res == null) { return op === '!=' } if(!op) return true; return op === "=" ? res === value : op === "!=" ? res !== value : op === "^=" ? value && res.indexOf( value ) === 0 : op === "*=" ? value && res.indexOf( value ) > -1 : op === "$=" ? value && res.slice( -value.length ) === value : op === "~=" ? ( " " + res.replace( rwhitespace, " " ) + " " ).indexOf( value ) > -1 : op === "|=" ? res === value || res.slice( 0, value.length + 1 ) === value + "-" : false; } }, 'CHILD':function(type, what, argument, first, last){ var fn = $_.Element['is'+$_.S.capitalize(type)+$_.S.capitalize(what)]; if(!fn) throw new Error('unsupported pseudo:'+type+'_'+what); return $_.F.partial(fn, undefined, argument); }, 'PSEUDO':function(pseudo, argument){ var fn = $_.Element['is'+$_.S.capitalize(pseudo)]; if(!fn) throw new Error('unsupported pseudo:'+pseudo); return $_.O.isUndefined(argument)?fn:$_.F.partial(fn, undefined, argument); } }; var _matchFn = $_.F.memoize(function (tokens){ return $_.A.map(tokens, function(token){ return filters[token.type].apply(null, token.matches); }); }, function(tokens){ return toSelector(tokens); }); function _matchSelector(node, fns) { for (var i = 0; i < fns.length; i++) { var fn = fns[i]; if (!fn(node)) return false; } return true; } var filter = $_.O.keys(filters); function _tokenize(selector){ var str = selector,res = [], matched, match, tokens; var f = function(type){ if((match = matchExpr[type].exec(str)) && (!matchFunction[type]|| (match = matchFunction[type](match)))){ matched = match.shift(); tokens.push({ value:matched, type:type, matches:match }); str = str.slice(matched.length); } }; while(str){ if(!matched||(match = rcomma.exec(str))) { if (match) str = str.slice(match[0].length) || str; res.push((tokens = [])); } matched = false; if((match = rcombinators.exec(str))){ matched = match.shift(); tokens.push({ value:matched, type:match[0].replace(rtrim, ' ') }); str = str.slice(matched.length) } $_.A.each(filter, f); if(!matched){ break; } } if(str) throw new Error(); return res; } var tokenize = $_.F.compose($_.F.memoize(_tokenize, function(str){return str+' '}), $_.O.clone); function getId(el){ return (el._sid)? el._sid:(el._sid=_sid++); } function _findUniqueMerge(res, combinator, token){ var _cacheMap = $_.A.toMap(res, function(el){return getId(el)}, $_.F.alwaysTrue); var eachCallback = function(el){ var sid = getId(el); if(_cacheMap[sid]) return; _cacheMap[sid] = true; res.push(el); }; $_.N.times(res.length, function(){ var node = res.shift(); combinator(node, token, eachCallback); }); } function compareToken(t1,t2) { var m = { 'ID':0, 'TAG':2, 'CLASS':1, 'ATTR':3, 'PSEUDO':4 }; var res = m[t1.type] - m[t2.type]; if(res === 0){ if(t1.value < t2.value) return -1; else if(t1.value > t2.value) return 1; return 0; } return res; } function select(expression, element, results){ results = results||[]; element = element || document; expression = expression.replace(rtrim, '$1'); var tokens = tokenize(expression); var types = filter; var needSort = results.length>0||tokens.length>1; results = $_.A.reduce(tokens, function(res, token){ var i = 0,j = 0, t, combinator= combinators[' '],r = [element]; while(t=token[i++]){ var type = t.type; if(!$_.A.include(types, type)){ _findUniqueMerge(r, combinator, token.slice(j, i-1).sort(compareToken)); combinator = combinators[type]; j = i; } } _findUniqueMerge(r, combinator, token.slice(j).sort(compareToken)); return $_.A.merge(res,r); }, results); return (!needSort)?results:results.sort($_.Element.compareNode); } function toSelector(tokens){ return $_.A.reduce(tokens, function(str, i){ return str+ i.value; }, ''); } $_.O.extend(o, { tokenize:tokenize, toSelector:toSelector, select:select }) })(Asdf);
{ "content_hash": "7bc409d448e91aa7eb208ebeeffce01f", "timestamp": "", "source": "github", "line_count": 370, "max_line_length": 172, "avg_line_length": 42.975675675675674, "alnum_prop": 0.4507892585371989, "repo_name": "Asdfjs/Asdf", "id": "8189a6c365af55aa2efe8b84e171317b63342b34", "size": "15901", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/dom/Selector.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18667" }, { "name": "HTML", "bytes": "142323" }, { "name": "JavaScript", "bytes": "1094930" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * CodeIgniter Template Class * * Build your CodeIgniter pages much easier with partials, breadcrumbs, layouts and themes * * @package CodeIgniter * @subpackage Libraries * @category Libraries * @author Philip Sturgeon * @license http://philsturgeon.co.uk/code/dbad-license * @link http://getsparks.org/packages/template/show */ class Template { private $_module = ''; private $_controller = ''; private $_method = ''; private $_theme = NULL; private $_theme_path = NULL; private $_layout = FALSE; // By default, dont wrap the view with anything private $_layout_subdir = ''; // Layouts and partials will exist in views/layouts // but can be set to views/foo/layouts with a subdirectory private $_title = ''; private $_metadata = array(); private $_partials = array(); private $_breadcrumbs = array(); private $_title_separator = ' | '; private $_parser_enabled = TRUE; private $_parser_body_enabled = TRUE; private $_theme_locations = array(); private $_is_mobile = FALSE; // Minutes that cache will be alive for private $cache_lifetime = 0; private $_ci; private $_data = array(); private $_template_path = ''; /** * Constructor - Sets Preferences * * The constructor can be passed an array of config values */ function __construct($config = array()) { $this->_ci =& get_instance(); $config['layout'] = $this->_ci->config->item('layout'); $config['template_path'] = $this->_ci->config->item('template_path'); if ( ! empty($config)) { $this->initialize($config); } log_message('debug', 'Template class Initialized'); } // -------------------------------------------------------------------- /** * Initialize preferences * * @access public * @param array * @return void */ function initialize($config = array()) { foreach ($config as $key => $val) { if ($key == 'theme' AND $val != '') { $this->set_theme($val); continue; } $this->{'_'.$key} = $val; } //print_r($this); // No locations set in config? if ($this->_theme_locations === array()) { // Let's use this obvious default $this->_theme_locations = array(APPPATH . 'themes/'); } // Theme was set if ($this->_theme) { $this->set_theme($this->_theme); } // If the parse is going to be used, best make sure it's loaded if ($this->_parser_enabled === TRUE) { class_exists('CI_Parser') OR $this->_ci->load->library('parser'); } // Modular Separation / Modular Extensions has been detected if (method_exists( $this->_ci->router, 'fetch_module' )) { $this->_module = $this->_ci->router->fetch_module(); } // What controllers or methods are in use $this->_controller = $this->_ci->router->fetch_class(); $this->_method = $this->_ci->router->fetch_method(); // Load user agent library if not loaded class_exists('CI_User_agent') OR $this->_ci->load->library('user_agent'); // We'll want to know this later $this->_is_mobile = $this->_ci->agent->is_mobile(); } // -------------------------------------------------------------------- /** * Magic Get function to get data * * @access public * @param string * @return mixed */ public function __get($name) { return isset($this->_data[$name]) ? $this->_data[$name] : NULL; } // -------------------------------------------------------------------- /** * Magic Set function to set data * * @access public * @param string * @return mixed */ public function __set($name, $value) { $this->_data[$name] = $value; } // -------------------------------------------------------------------- /** * Set data using a chainable metod. Provide two strings or an array of data. * * @access public * @param string * @return mixed */ public function set($name, $value = NULL) { // Lots of things! Set them all if (is_array($name) OR is_object($name)) { foreach ($name as $item => $value) { $this->_data[$item] = $value; } } // Just one thing, set that else { $this->_data[$name] = $value; } return $this; } // -------------------------------------------------------------------- /** * Build the entire HTML output combining partials, layouts and views. * * @access public * @param string * @return mixed */ public function build($view, $data = array(), $return = FALSE) { // Set whatever values are given. These will be available to all view files is_array($data) OR $data = (array) $data; // Merge in what we already have with the specific data $this->_data = array_merge($this->_data, $data); // We don't need you any more buddy unset($data); if (empty($this->_title)) { $this->_title = $this->_guess_title(); } // Output template variables to the template $template['title'] = $this->_title; $template['breadcrumbs'] = $this->_breadcrumbs; $template['metadata'] = implode("\n\t\t", $this->_metadata); $template['partials'] = array(); // Assign by reference, as all loaded views will need access to partials $this->_data['template'] =& $template; foreach ($this->_partials as $name => $partial) { // We can only work with data arrays is_array($partial['data']) OR $partial['data'] = (array) $partial['data']; // If it uses a view, load it if (isset($partial['view'])) { $template['partials'][$name] = $this->_find_view($partial['view'], $partial['data']); } // Otherwise the partial must be a string else { if ($this->_parser_enabled === TRUE) { $partial['string'] = $this->_ci->parser->parse_string($partial['string'], $this->_data + $partial['data'], TRUE, TRUE); } $template['partials'][$name] = $partial['string']; } } // Disable sodding IE7's constant cacheing!! $this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT'); $this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate'); $this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0'); $this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); $this->_ci->output->set_header('Pragma: no-cache'); // Let CI do the caching instead of the browser $this->_ci->output->cache($this->cache_lifetime); // Test to see if this file $this->_body = $this->_find_view($view, array(), $this->_parser_body_enabled); // Want this file wrapped with a layout file? if ($this->_layout) { // Added to $this->_data['template'] by refference $template['body'] = $this->_body; // Find the main body and 3rd param means parse if its a theme view (only if parser is enabled) $this->_body = self::_load_view($this->_layout, $this->_data, TRUE, self::_find_view_folder()); } // Want it returned or output to browser? if ( ! $return) { $this->_ci->output->set_output($this->_body); } return $this->_body; } /** * Set the title of the page * * @access public * @param string * @return mixed */ public function title() { // If we have some segments passed if ($title_segments =& func_get_args()) { $this->_title = implode($this->_title_separator, $title_segments); } return $this; } /** * Put extra javascipt, css, meta tags, etc before all other head data * * @access public * @param string $line The line being added to head * @return mixed */ public function prepend_metadata($line) { array_unshift($this->_metadata, $line); return $this; } /** * Put extra javascipt, css, meta tags, etc after other head data * * @access public * @param string $line The line being added to head * @return mixed */ public function append_metadata($line) { $this->_metadata[] = $line; return $this; } /** * Set metadata for output later * * @access public * @param string $name keywords, description, etc * @param string $content The content of meta data * @param string $type Meta-data comes in a few types, links for example * @return mixed */ public function set_metadata($name, $content, $type = 'meta') { $name = htmlspecialchars(strip_tags($name)); $content = htmlspecialchars(strip_tags($content)); // Keywords with no comments? ARG! comment them if ($name == 'keywords' AND ! strpos($content, ',')) { $content = preg_replace('/[\s]+/', ', ', trim($content)); } switch($type) { case 'meta': $this->_metadata[$name] = '<meta name="'.$name.'" content="'.$content.'" />'; break; case 'link': $this->_metadata[$content] = '<link rel="'.$name.'" href="'.$content.'" />'; break; } return $this; } /** * Which theme are we using here? * * @access public * @param string $theme Set a theme for the template library to use * @return mixed */ public function set_theme($theme = NULL) { $this->_theme = $theme; foreach ($this->_theme_locations as $location) { if ($this->_theme AND file_exists($location.$this->_theme)) { $this->_theme_path = rtrim($location.$this->_theme.'/'); break; } } return $this; } /** * Get the current theme path * * @access public * @return string The current theme path */ public function get_theme_path() { return $this->_theme_path; } /** * Which theme layout should we using here? * * @access public * @param string $view * @return mixed */ public function set_layout($view, $_layout_subdir = '') { $this->_layout = $view; $_layout_subdir AND $this->_layout_subdir = $_layout_subdir; return $this; } /** * Set a view partial * * @access public * @param string * @param string * @param boolean * @return mixed */ public function set_partial($name, $view, $data = array()) { $this->_partials[$name] = array('view' => $view, 'data' => $data); return $this; } /** * Set a view partial * * @access public * @param string * @param string * @param boolean * @return mixed */ public function inject_partial($name, $string, $data = array()) { $this->_partials[$name] = array('string' => $string, 'data' => $data); return $this; } /** * Helps build custom breadcrumb trails * * @access public * @param string $name What will appear as the link text * @param string $url_ref The URL segment * @return mixed */ public function set_breadcrumb($name, $uri = '') { $this->_breadcrumbs[] = array('name' => $name, 'uri' => $uri ); return $this; } /** * Set a the cache lifetime * * @access public * @param string * @param string * @param boolean * @return mixed */ public function set_cache($minutes = 0) { $this->cache_lifetime = $minutes; return $this; } /** * enable_parser * Should be parser be used or the view files just loaded normally? * * @access public * @param string $view * @return mixed */ public function enable_parser($bool) { $this->_parser_enabled = $bool; return $this; } /** * enable_parser_body * Should be parser be used or the body view files just loaded normally? * * @access public * @param string $view * @return mixed */ public function enable_parser_body($bool) { $this->_parser_body_enabled = $bool; return $this; } /** * theme_locations * List the locations where themes may be stored * * @access public * @param string $view * @return array */ public function theme_locations() { return $this->_theme_locations; } /** * add_theme_location * Set another location for themes to be looked in * * @access public * @param string $view * @return array */ public function add_theme_location($location) { $this->_theme_locations[] = $location; } /** * theme_exists * Check if a theme exists * * @access public * @param string $view * @return bool */ public function theme_exists($theme = NULL) { $theme OR $theme = $this->_theme; foreach ($this->_theme_locations as $location) { if (is_dir($location.$theme)) { return TRUE; } } return FALSE; } /** * get_layouts * Get all current layouts (if using a theme you'll get a list of theme layouts) * * @access public * @param string $view * @return array */ public function get_layouts() { $layouts = array(); foreach(glob(self::_find_view_folder().'layouts/*.*') as $layout) { $layouts[] = pathinfo($layout, PATHINFO_BASENAME); } return $layouts; } /** * get_layouts * Get all current layouts (if using a theme you'll get a list of theme layouts) * * @access public * @param string $view * @return array */ public function get_theme_layouts($theme = NULL) { $theme OR $theme = $this->_theme; $layouts = array(); foreach ($this->_theme_locations as $location) { // Get special web layouts if( is_dir($location.$theme.'/views/web/layouts/') ) { foreach(glob($location.$theme . '/views/web/layouts/*.*') as $layout) { $layouts[] = pathinfo($layout, PATHINFO_BASENAME); } break; } // So there are no web layouts, assume all layouts are web layouts if(is_dir($location.$theme.'/views/layouts/')) { foreach(glob($location.$theme . '/views/layouts/*.*') as $layout) { $layouts[] = pathinfo($layout, PATHINFO_BASENAME); } break; } } return $layouts; } /** * layout_exists * Check if a theme layout exists * * @access public * @param string $view * @return array */ public function layout_exists($layout) { // If there is a theme, check it exists in there if ( ! empty($this->_theme) AND in_array($layout, self::get_theme_layouts())) { return TRUE; } // Otherwise look in the normal places return file_exists(self::_find_view_folder().'layouts/' . $layout . self::_ext($layout)); } // find layout files, they could be mobile or web private function _find_view_folder() { if ($this->_ci->load->get_var('template_views')) { return $this->_ci->load->get_var('template_views'); } // Base view folder $view_folder = APPPATH.$this->_template_path; // Using a theme? Put the theme path in before the view folder if ( ! empty($this->_theme)) { $view_folder = $this->_theme_path.'views/'; } // Would they like the mobile version? if ($this->_is_mobile === TRUE AND is_dir($view_folder.'mobile/')) { // Use mobile as the base location for views $view_folder .= 'mobile/'; } // Use the web version else if (is_dir($view_folder.'web/')) { $view_folder .= 'web/'; } // Things like views/backend/web/view backend = subdir if ($this->_layout_subdir) { $view_folder .= $this->_layout_subdir.'/'; } // If using themes store this for later, available to all views $this->_ci->load->vars('template_views', $view_folder); return $view_folder; } // A module view file can be overriden in a theme private function _find_view($view, array $data, $parse_view = TRUE) { // Only bother looking in themes if there is a theme if ( ! empty($this->_theme)) { foreach ($this->_theme_locations as $location) { $theme_views = array( $this->_theme . '/views/modules/' . $this->_module . '/' . $view, $this->_theme . '/views/' . $view ); foreach ($theme_views as $theme_view) { if (file_exists($location . $theme_view . self::_ext($theme_view))) { return self::_load_view($theme_view, $this->_data + $data, $parse_view, $location); } } } } // Not found it yet? Just load, its either in the module or root view return self::_load_view($view, $this->_data + $data, $parse_view); } private function _load_view($view, array $data, $parse_view = TRUE, $override_view_path = NULL) { // Sevear hackery to load views from custom places AND maintain compatibility with Modular Extensions if ($override_view_path !== NULL) { if ($this->_parser_enabled === TRUE AND $parse_view === TRUE) { // Load content and pass through the parser $content = $this->_ci->parser->parse_string($this->_ci->load->file( $override_view_path.$view.self::_ext($view), TRUE ), $data); } else { $this->_ci->load->vars($data); // Load it directly, bypassing $this->load->view() as ME resets _ci_view $content = $this->_ci->load->file( $override_view_path.$view.self::_ext($view), TRUE ); } } // Can just run as usual else { // Grab the content of the view (parsed or loaded) $content = ($this->_parser_enabled === TRUE AND $parse_view === TRUE) // Parse that bad boy ? $this->_ci->parser->parse($view, $data, TRUE) // None of that fancy stuff for me! : $this->_ci->load->view($view, $data, TRUE); } return $content; } private function _guess_title() { $this->_ci->load->helper('inflector'); // Obviously no title, lets get making one $title_parts = array(); // If the method is something other than index, use that if ($this->_method != 'index') { $title_parts[] = $this->_method; } // Make sure controller name is not the same as the method name if ( ! in_array($this->_controller, $title_parts)) { $title_parts[] = $this->_controller; } // Is there a module? Make sure it is not named the same as the method or controller if ( ! empty($this->_module) AND ! in_array($this->_module, $title_parts)) { $title_parts[] = $this->_module; } // Glue the title pieces together using the title separator setting $title = humanize(implode($this->_title_separator, $title_parts)); return $title; } private function _ext($file) { return pathinfo($file, PATHINFO_EXTENSION) ? '' : '.php'; } } // END Template class
{ "content_hash": "4f772f978227470937861e90d773173b", "timestamp": "", "source": "github", "line_count": 777, "max_line_length": 124, "avg_line_length": 23.08880308880309, "alnum_prop": 0.5934782608695652, "repo_name": "rrajesh011/pricometer", "id": "a0bcac286af6ac24c782c51ebc175d7412ac7ebe", "size": "17940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/libraries/Template.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3128" }, { "name": "CSS", "bytes": "381333" }, { "name": "HTML", "bytes": "6836" }, { "name": "JavaScript", "bytes": "505609" }, { "name": "PHP", "bytes": "1678616" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>msets-extra: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.15.0 / msets-extra - 1.2.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> msets-extra <small> 1.2.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-07 04:41:25 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-07 04:41:25 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.0 Formal proof management system dune 3.1.1 Fast, portable, and opinionated build system ocaml 4.12.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.12.1 Official release 4.12.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;thomas@tuerk-brechen.de&quot; homepage: &quot;https://github.com/thtuerk/MSetsExtra&quot; dev-repo: &quot;git+https://github.com/thtuerk/MSetsExtra.git&quot; bug-reports: &quot;https://github.com/thtuerk/MSetsExtra/issues&quot; authors: [&quot;FireEye Formal Methods Team &lt;formal-methods@fireeye.com&gt;&quot; &quot;Thomas Tuerk &lt;thomas@tuerk-brechen.de&gt;&quot;] license: &quot;LGPL-2.1-only&quot; build: [ [&quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.6&quot;} ] tags: [ &quot;keyword:finite sets&quot; &quot;keyword:fold with abort&quot; &quot;keyword:extracting efficient code&quot; &quot;keyword:data structures&quot; &quot;category:Computer Science/Data Types and Data Structures&quot; &quot;category:Miscellaneous/Extracted Programs/Data structures&quot; &quot;logpath:MSetsExtra&quot; &quot;date:2019-09-19&quot; ] synopsis: &quot;Extensions of MSets for Efficient Execution&quot; description: &quot;&quot;&quot; Coq&#39;s MSet library provides various, reasonably efficient finite set implementations. Nevertheless, FireEye was struggling with performance issues. This library contains extensions to Coq&#39;s MSet library that helped the FireEye Formal Methods team (formal-methods@fireeye.com), solve these performance issues. There are - Fold With Abort efficient folding with possibility to start late and stop early - Interval Sets a memory efficient representation of sets of numbers - Unsorted Lists with Duplicates&quot;&quot;&quot; url { src: &quot;https://github.com/thtuerk/MSetsExtra/archive/1.2.0.tar.gz&quot; checksum: &quot;sha256=e886237194cde8602dbf191d3db7b1c28c6231c1c42996ca1b1819db3ab339ef&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-msets-extra.1.2.0 coq.8.15.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.0). The following dependencies couldn&#39;t be met: - coq-msets-extra -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-msets-extra.1.2.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "f93d94f523f999745ab7cc5c02955e6d", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 159, "avg_line_length": 42.375, "alnum_prop": 0.5631653199948699, "repo_name": "coq-bench/coq-bench.github.io", "id": "25839dd0084fa4700ab296e37c0ec53efdf19750", "size": "7822", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.12.1-2.0.8/released/8.15.0/msets-extra/1.2.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.pentaho.di.repository.kdr; import java.util.List; import java.util.Map; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.BaseRepositoryMeta; import org.pentaho.di.repository.RepositoriesMeta; import org.pentaho.di.repository.RepositoryCapabilities; import org.pentaho.di.repository.RepositoryMeta; import org.w3c.dom.Node; /* * Created on 31-mar-2004 */ public class KettleDatabaseRepositoryMeta extends BaseRepositoryMeta implements RepositoryMeta { /** The id as specified in the repository plugin meta, used for backward compatibility only */ public static String REPOSITORY_TYPE_ID = "KettleDatabaseRepository"; private DatabaseMeta databaseMeta; public KettleDatabaseRepositoryMeta() { super( REPOSITORY_TYPE_ID ); } public KettleDatabaseRepositoryMeta( String id, String name, String description, DatabaseMeta connection ) { super( id, name, description ); this.databaseMeta = connection; } public KettleDatabaseRepositoryMeta( String id ) { super( id, "", "" ); this.databaseMeta = null; } public RepositoryCapabilities getRepositoryCapabilities() { return new RepositoryCapabilities() { public boolean supportsUsers() { return true; } public boolean managesUsers() { return true; } public boolean isReadOnly() { return false; } public boolean supportsRevisions() { return false; } public boolean supportsMetadata() { return true; } public boolean supportsLocking() { return true; } public boolean hasVersionRegistry() { return false; } public boolean supportsAcls() { return false; } public boolean supportsReferences() { return true; } }; } public void setName( String name ) { this.name = name; } public String getName() { return name; } public void setDescription( String description ) { this.description = description; } public String getDescription() { return description; } public Boolean isDefault() { return isDefault; } public void setDefault( Boolean isDefault ) { this.isDefault = isDefault; } public void setConnection( DatabaseMeta connection ) { this.databaseMeta = connection; } public DatabaseMeta getConnection() { return databaseMeta; } public String getXML() { StringBuilder retval = new StringBuilder( 100 ); retval.append( " " ).append( XMLHandler.openTag( XML_TAG ) ); retval.append( super.getXML() ); retval.append( " " ).append( XMLHandler.addTagValue( "connection", databaseMeta != null ? databaseMeta.getName() : null ) ); retval.append( " " ).append( XMLHandler.closeTag( XML_TAG ) ); return retval.toString(); } public void loadXML( Node repnode, List<DatabaseMeta> databases ) throws KettleException { super.loadXML( repnode, databases ); try { String conn = XMLHandler.getTagValue( repnode, "connection" ); databaseMeta = DatabaseMeta.findDatabase( databases, conn ); } catch ( Exception e ) { throw new KettleException( "Unable to load Kettle database repository meta object", e ); } } public RepositoryMeta clone() { return new KettleDatabaseRepositoryMeta( REPOSITORY_TYPE_ID, getName(), getDescription(), getConnection() ); } @Override public void populate( Map<String, Object> properties, RepositoriesMeta repositoriesMeta ) { String displayName = (String) properties.get( "displayName" ); String description = (String) properties.get( "description" ); String databaseConnection = (String) properties.get( "databaseConnection" ); Boolean isDefault = (Boolean) properties.get( "isDefault" ); DatabaseMeta databaseMeta = repositoriesMeta.searchDatabase( databaseConnection ); if ( databaseMeta != null ) { setConnection( databaseMeta ); } setName( displayName ); setDescription( description ); setDefault( isDefault ); } }
{ "content_hash": "436c94dbccc0ce55e362126d5316a123", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 112, "avg_line_length": 27.44078947368421, "alnum_prop": 0.6880843922320786, "repo_name": "brosander/pentaho-kettle", "id": "34a46cb4a188115510d07bec0332ec5099cbc171", "size": "5075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "engine/src/org/pentaho/di/repository/kdr/KettleDatabaseRepositoryMeta.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "14028" }, { "name": "CSS", "bytes": "20530" }, { "name": "GAP", "bytes": "4005" }, { "name": "HTML", "bytes": "69511" }, { "name": "Java", "bytes": "37786915" }, { "name": "JavaScript", "bytes": "16314" }, { "name": "Shell", "bytes": "18925" }, { "name": "XSLT", "bytes": "5600" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/ll_data" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.jlnu.lang.realtimeinfo.xrecyclerview.XRecyclerView android:id="@+id/news_item_recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> <LinearLayout android:id="@+id/ll_cover" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </LinearLayout>
{ "content_hash": "f6836f638fb178ebdccb76bdfe5740df", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 34.68, "alnum_prop": 0.6585928489042676, "repo_name": "897190301/RealTimeInfo", "id": "28a32b8259c8841ab83287ad97bed66877db6c88", "size": "867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/fragment_news_item.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "129775" } ], "symlink_target": "" }
namespace base { template <typename StructType> class JSONValueConverter; namespace internal { template<typename StructType> class FieldConverterBase { public: explicit FieldConverterBase(const std::string& path) : field_path_(path) {} virtual ~FieldConverterBase() {} virtual bool ConvertField(const base::Value& value, StructType* obj) const = 0; const std::string& field_path() const { return field_path_; } private: std::string field_path_; DISALLOW_COPY_AND_ASSIGN(FieldConverterBase); }; template <typename FieldType> class ValueConverter { public: virtual ~ValueConverter() {} virtual bool Convert(const base::Value& value, FieldType* field) const = 0; }; template <typename StructType, typename FieldType> class FieldConverter : public FieldConverterBase<StructType> { public: explicit FieldConverter(const std::string& path, FieldType StructType::* field, ValueConverter<FieldType>* converter) : FieldConverterBase<StructType>(path), field_pointer_(field), value_converter_(converter) { } virtual bool ConvertField( const base::Value& value, StructType* dst) const OVERRIDE { return value_converter_->Convert(value, &(dst->*field_pointer_)); } private: FieldType StructType::* field_pointer_; scoped_ptr<ValueConverter<FieldType> > value_converter_; DISALLOW_COPY_AND_ASSIGN(FieldConverter); }; template <typename FieldType> class BasicValueConverter; template <> class BasicValueConverter<int> : public ValueConverter<int> { public: BasicValueConverter() {} virtual bool Convert(const base::Value& value, int* field) const OVERRIDE { return value.GetAsInteger(field); } private: DISALLOW_COPY_AND_ASSIGN(BasicValueConverter); }; template <> class BasicValueConverter<std::string> : public ValueConverter<std::string> { public: BasicValueConverter() {} virtual bool Convert( const base::Value& value, std::string* field) const OVERRIDE { return value.GetAsString(field); } private: DISALLOW_COPY_AND_ASSIGN(BasicValueConverter); }; template <> class BasicValueConverter<string16> : public ValueConverter<string16> { public: BasicValueConverter() {} virtual bool Convert( const base::Value& value, string16* field) const OVERRIDE { return value.GetAsString(field); } private: DISALLOW_COPY_AND_ASSIGN(BasicValueConverter); }; template <> class BasicValueConverter<double> : public ValueConverter<double> { public: BasicValueConverter() {} virtual bool Convert(const base::Value& value, double* field) const OVERRIDE { return value.GetAsDouble(field); } private: DISALLOW_COPY_AND_ASSIGN(BasicValueConverter); }; template <> class BasicValueConverter<bool> : public ValueConverter<bool> { public: BasicValueConverter() {} virtual bool Convert(const base::Value& value, bool* field) const OVERRIDE { return value.GetAsBoolean(field); } private: DISALLOW_COPY_AND_ASSIGN(BasicValueConverter); }; template <typename FieldType> class ValueFieldConverter : public ValueConverter<FieldType> { public: typedef bool(*ConvertFunc)(const base::Value* value, FieldType* field); ValueFieldConverter(ConvertFunc convert_func) : convert_func_(convert_func) {} virtual bool Convert(const base::Value& value, FieldType* field) const OVERRIDE { return convert_func_(&value, field); } private: ConvertFunc convert_func_; DISALLOW_COPY_AND_ASSIGN(ValueFieldConverter); }; template <typename FieldType> class CustomFieldConverter : public ValueConverter<FieldType> { public: typedef bool(*ConvertFunc)(const StringPiece& value, FieldType* field); CustomFieldConverter(ConvertFunc convert_func) : convert_func_(convert_func) {} virtual bool Convert(const base::Value& value, FieldType* field) const OVERRIDE { std::string string_value; return value.GetAsString(&string_value) && convert_func_(string_value, field); } private: ConvertFunc convert_func_; DISALLOW_COPY_AND_ASSIGN(CustomFieldConverter); }; template <typename NestedType> class NestedValueConverter : public ValueConverter<NestedType> { public: NestedValueConverter() {} virtual bool Convert( const base::Value& value, NestedType* field) const OVERRIDE { return converter_.Convert(value, field); } private: JSONValueConverter<NestedType> converter_; DISALLOW_COPY_AND_ASSIGN(NestedValueConverter); }; template <typename Element> class RepeatedValueConverter : public ValueConverter<ScopedVector<Element> > { public: RepeatedValueConverter() {} virtual bool Convert( const base::Value& value, ScopedVector<Element>* field) const OVERRIDE { const base::ListValue* list = NULL; if (!value.GetAsList(&list)) { // The field is not a list. return false; } field->reserve(list->GetSize()); for (size_t i = 0; i < list->GetSize(); ++i) { base::Value* element = NULL; if (!list->Get(i, &element)) continue; scoped_ptr<Element> e(new Element); if (basic_converter_.Convert(*element, e.get())) { field->push_back(e.release()); } else { DVLOG(1) << "failure at " << i << "-th element"; return false; } } return true; } private: BasicValueConverter<Element> basic_converter_; DISALLOW_COPY_AND_ASSIGN(RepeatedValueConverter); }; template <typename NestedType> class RepeatedMessageConverter : public ValueConverter<ScopedVector<NestedType> > { public: RepeatedMessageConverter() {} virtual bool Convert(const base::Value& value, ScopedVector<NestedType>* field) const OVERRIDE { const base::ListValue* list = NULL; if (!value.GetAsList(&list)) return false; field->reserve(list->GetSize()); for (size_t i = 0; i < list->GetSize(); ++i) { base::Value* element = NULL; if (!list->Get(i, &element)) continue; scoped_ptr<NestedType> nested(new NestedType); if (converter_.Convert(*element, nested.get())) { field->push_back(nested.release()); } else { DVLOG(1) << "failure at " << i << "-th element"; return false; } } return true; } private: JSONValueConverter<NestedType> converter_; DISALLOW_COPY_AND_ASSIGN(RepeatedMessageConverter); }; template <typename NestedType> class RepeatedCustomValueConverter : public ValueConverter<ScopedVector<NestedType> > { public: typedef bool(*ConvertFunc)(const base::Value* value, NestedType* field); RepeatedCustomValueConverter(ConvertFunc convert_func) : convert_func_(convert_func) {} virtual bool Convert(const base::Value& value, ScopedVector<NestedType>* field) const OVERRIDE { const base::ListValue* list = NULL; if (!value.GetAsList(&list)) return false; field->reserve(list->GetSize()); for (size_t i = 0; i < list->GetSize(); ++i) { base::Value* element = NULL; if (!list->Get(i, &element)) continue; scoped_ptr<NestedType> nested(new NestedType); if ((*convert_func_)(element, nested.get())) { field->push_back(nested.release()); } else { DVLOG(1) << "failure at " << i << "-th element"; return false; } } return true; } private: ConvertFunc convert_func_; DISALLOW_COPY_AND_ASSIGN(RepeatedCustomValueConverter); }; } // namespace internal template <class StructType> class JSONValueConverter { public: JSONValueConverter() { StructType::RegisterJSONConverter(this); } void RegisterIntField(const std::string& field_name, int StructType::* field) { fields_.push_back(new internal::FieldConverter<StructType, int>( field_name, field, new internal::BasicValueConverter<int>)); } void RegisterStringField(const std::string& field_name, std::string StructType::* field) { fields_.push_back(new internal::FieldConverter<StructType, std::string>( field_name, field, new internal::BasicValueConverter<std::string>)); } void RegisterStringField(const std::string& field_name, string16 StructType::* field) { fields_.push_back(new internal::FieldConverter<StructType, string16>( field_name, field, new internal::BasicValueConverter<string16>)); } void RegisterBoolField(const std::string& field_name, bool StructType::* field) { fields_.push_back(new internal::FieldConverter<StructType, bool>( field_name, field, new internal::BasicValueConverter<bool>)); } void RegisterDoubleField(const std::string& field_name, double StructType::* field) { fields_.push_back(new internal::FieldConverter<StructType, double>( field_name, field, new internal::BasicValueConverter<double>)); } template <class NestedType> void RegisterNestedField( const std::string& field_name, NestedType StructType::* field) { fields_.push_back(new internal::FieldConverter<StructType, NestedType>( field_name, field, new internal::NestedValueConverter<NestedType>)); } template <typename FieldType> void RegisterCustomField( const std::string& field_name, FieldType StructType::* field, bool (*convert_func)(const StringPiece&, FieldType*)) { fields_.push_back(new internal::FieldConverter<StructType, FieldType>( field_name, field, new internal::CustomFieldConverter<FieldType>(convert_func))); } template <typename FieldType> void RegisterCustomValueField( const std::string& field_name, FieldType StructType::* field, bool (*convert_func)(const base::Value*, FieldType*)) { fields_.push_back(new internal::FieldConverter<StructType, FieldType>( field_name, field, new internal::ValueFieldConverter<FieldType>(convert_func))); } void RegisterRepeatedInt(const std::string& field_name, ScopedVector<int> StructType::* field) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<int> >( field_name, field, new internal::RepeatedValueConverter<int>)); } void RegisterRepeatedString(const std::string& field_name, ScopedVector<std::string> StructType::* field) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<std::string> >( field_name, field, new internal::RepeatedValueConverter<std::string>)); } void RegisterRepeatedString(const std::string& field_name, ScopedVector<string16> StructType::* field) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<string16> >( field_name, field, new internal::RepeatedValueConverter<string16>)); } void RegisterRepeatedDouble(const std::string& field_name, ScopedVector<double> StructType::* field) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<double> >( field_name, field, new internal::RepeatedValueConverter<double>)); } void RegisterRepeatedBool(const std::string& field_name, ScopedVector<bool> StructType::* field) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<bool> >( field_name, field, new internal::RepeatedValueConverter<bool>)); } template <class NestedType> void RegisterRepeatedCustomValue( const std::string& field_name, ScopedVector<NestedType> StructType::* field, bool (*convert_func)(const base::Value*, NestedType*)) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<NestedType> >( field_name, field, new internal::RepeatedCustomValueConverter<NestedType>( convert_func))); } template <class NestedType> void RegisterRepeatedMessage(const std::string& field_name, ScopedVector<NestedType> StructType::* field) { fields_.push_back( new internal::FieldConverter<StructType, ScopedVector<NestedType> >( field_name, field, new internal::RepeatedMessageConverter<NestedType>)); } bool Convert(const base::Value& value, StructType* output) const { const DictionaryValue* dictionary_value = NULL; if (!value.GetAsDictionary(&dictionary_value)) return false; for(size_t i = 0; i < fields_.size(); ++i) { const internal::FieldConverterBase<StructType>* field_converter = fields_[i]; base::Value* field = NULL; if (dictionary_value->Get(field_converter->field_path(), &field)) { if (!field_converter->ConvertField(*field, output)) { DVLOG(1) << "failure at field " << field_converter->field_path(); return false; } } } return true; } private: ScopedVector<internal::FieldConverterBase<StructType> > fields_; DISALLOW_COPY_AND_ASSIGN(JSONValueConverter); }; } // namespace base #endif // BASE_JSON_JSON_VALUE_CONVERTER_H_
{ "content_hash": "ef6ec2a4a6a87bec53ca73e3e6da293f", "timestamp": "", "source": "github", "line_count": 442, "max_line_length": 80, "avg_line_length": 30.27601809954751, "alnum_prop": 0.6642504857270961, "repo_name": "keishi/chromium", "id": "2d605e47f61910cc66883c0a1ee17e02bd16a34e", "size": "16341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "base/json/json_value_converter.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1172794" }, { "name": "C", "bytes": "67452317" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "132681259" }, { "name": "F#", "bytes": "381" }, { "name": "Go", "bytes": "19048" }, { "name": "Java", "bytes": "361412" }, { "name": "JavaScript", "bytes": "16603687" }, { "name": "Objective-C", "bytes": "9609581" }, { "name": "PHP", "bytes": "97796" }, { "name": "Perl", "bytes": "918683" }, { "name": "Python", "bytes": "6407891" }, { "name": "R", "bytes": "524" }, { "name": "Shell", "bytes": "4192593" }, { "name": "Tcl", "bytes": "277077" } ], "symlink_target": "" }
package com.amazonaws.services.glue.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.glue.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * BatchGetTriggersRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class BatchGetTriggersRequestMarshaller { private static final MarshallingInfo<List> TRIGGERNAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("TriggerNames").build(); private static final BatchGetTriggersRequestMarshaller instance = new BatchGetTriggersRequestMarshaller(); public static BatchGetTriggersRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(BatchGetTriggersRequest batchGetTriggersRequest, ProtocolMarshaller protocolMarshaller) { if (batchGetTriggersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(batchGetTriggersRequest.getTriggerNames(), TRIGGERNAMES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "6eba008c610e8a2dd8b0a7978985f56a", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 158, "avg_line_length": 32.733333333333334, "alnum_prop": 0.7399864222674813, "repo_name": "jentfoo/aws-sdk-java", "id": "c6e04e6b6835ed540b2a5632d02495a7a0e1d6a5", "size": "2053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/BatchGetTriggersRequestMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
package br.ufes.inf.lprm.scene.base.evaluators.implementation; import br.ufes.inf.lprm.situation.model.Situation; import org.drools.core.base.ValueType; import org.drools.core.common.DefaultFactHandle; import org.drools.core.common.EventFactHandle; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.InternalWorkingMemory; import org.drools.core.rule.VariableRestriction; import org.drools.core.rule.VariableRestriction.ObjectVariableContextEntry; import org.drools.core.rule.VariableRestriction.VariableContextEntry; import org.drools.core.spi.FieldValue; import org.drools.core.spi.InternalReadAccessor; import java.lang.reflect.Field; /** * Created by hborjaille on 9/8/16. */ public class DuringEvaluator extends org.drools.core.base.evaluators.DuringEvaluatorDefinition.DuringEvaluator { private long startMinDev, startMaxDev; private long endMinDev, endMaxDev; public DuringEvaluator(final ValueType type, final boolean isNegated, final long[] parameters, final String paramText) { super( type, isNegated, parameters, paramText); extractParams(); } private void extractParams() { try { Field startMinDev = this.getClass().getSuperclass().getDeclaredField("startMinDev"); Field startMaxDev = this.getClass().getSuperclass().getDeclaredField("startMaxDev"); Field endMinDev = this.getClass().getSuperclass().getDeclaredField("endMinDev"); Field endMaxDev = this.getClass().getSuperclass().getDeclaredField("endMaxDev"); startMinDev.setAccessible(true); startMaxDev.setAccessible(true); endMinDev.setAccessible(true); endMaxDev.setAccessible(true); this.startMinDev = startMinDev.getLong(this); this.startMaxDev = startMaxDev.getLong(this); this.endMinDev = 0;//endMinDev.getLong(this); this.endMaxDev = endMaxDev.getLong(this); } catch (Exception e) { throw new RuntimeException( e.getMessage() ); } } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor extractor, InternalFactHandle factHandle, FieldValue value) { throw new RuntimeException( "The 'during' operator can only be used to compare one event to another, and never to compare to literal constraints." ); } @Override public boolean evaluateCachedRight(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle left) { if ( context.rightNull || context.declaration.getExtractor().isNullValue( workingMemory, left.getObject() )) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS; if (left.getObject() instanceof Situation) { Situation sit = (Situation) left.getObject(); leftStartTS = sit.getActivation().getTimestamp(); leftEndTS = !sit.isActive() ? sit.getDeactivation().getTimestamp() : Long.MAX_VALUE; } else { leftStartTS = ((EventFactHandle) left).getStartTimestamp(); leftEndTS = ((EventFactHandle) left).getEndTimestamp(); } rightStartTS = ((VariableRestriction.TemporalVariableContextEntry) context).startTS; rightEndTS = ((VariableRestriction.TemporalVariableContextEntry) context).endTS; long distStart = rightStartTS - leftStartTS; long distEnd = leftEndTS - rightEndTS; return this.getOperator().isNegated() ^ (distStart >= this.startMinDev && distStart <= this.startMaxDev && distEnd >= this.endMinDev && distEnd <= this.endMaxDev); } @Override public boolean evaluateCachedLeft(InternalWorkingMemory workingMemory, VariableContextEntry context, InternalFactHandle right) { if ( context.leftNull || context.extractor.isNullValue( workingMemory, right.getObject() ) ) { return false; } long rightStartTS, rightEndTS; if (right.getObject() instanceof Situation) { Situation sit = (Situation) right.getObject(); rightStartTS = sit.getActivation().getTimestamp(); rightEndTS = !sit.isActive() ? sit.getDeactivation().getTimestamp() : Long.MAX_VALUE; } else { rightStartTS = ((EventFactHandle) right).getStartTimestamp(); rightEndTS = ((EventFactHandle) right).getEndTimestamp(); } long distStart = rightStartTS - ((VariableRestriction.TemporalVariableContextEntry) context).startTS; long distEnd = ((VariableRestriction.TemporalVariableContextEntry) context).endTS - rightEndTS; return this.getOperator().isNegated() ^ (distStart >= this.startMinDev && distStart <= this.startMaxDev && distEnd >= this.endMinDev && distEnd <= this.endMaxDev); } @Override public boolean evaluate(InternalWorkingMemory workingMemory, InternalReadAccessor leftExtractor, InternalFactHandle left, InternalReadAccessor rightExtractor, InternalFactHandle right) { if ( leftExtractor.isNullValue( workingMemory, left.getObject() ) || rightExtractor.isNullValue( workingMemory, right.getObject() ) ) { return false; } long leftStartTS, leftEndTS, rightStartTS, rightEndTS; if (left.getObject() instanceof Situation) { Situation sit = (Situation) left.getObject(); leftStartTS = sit.getActivation().getTimestamp(); leftEndTS = !sit.isActive() ? sit.getDeactivation().getTimestamp() : Long.MAX_VALUE; } else { leftStartTS = ((EventFactHandle) left).getStartTimestamp(); leftEndTS = ((EventFactHandle) left).getEndTimestamp(); } if (right.getObject() instanceof Situation) { Situation sit = (Situation) right.getObject(); rightStartTS = sit.getActivation().getTimestamp(); rightEndTS = !sit.isActive() ? sit.getDeactivation().getTimestamp() : Long.MAX_VALUE; } else { rightStartTS = ((EventFactHandle) right).getStartTimestamp(); rightEndTS = ((EventFactHandle) right).getEndTimestamp(); } long distStart = leftStartTS - rightStartTS; long distEnd = rightEndTS - leftEndTS; return this.getOperator().isNegated() ^ (distStart >= this.startMinDev && distStart <= this.startMaxDev && distEnd >= this.endMinDev && distEnd <= this.endMaxDev); } }
{ "content_hash": "2026999985534aef6035a21ac7b61ffe", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 190, "avg_line_length": 44.70469798657718, "alnum_prop": 0.6668668368112896, "repo_name": "pextralabs/scene-platform", "id": "89cf6f8f796ab29e20bd554d7c321c4a0436f348", "size": "6661", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "scene-core/src/main/java/br/ufes/inf/lprm/scene/base/evaluators/implementation/DuringEvaluator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "189316" }, { "name": "Scala", "bytes": "3883" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <!-- WARNING - this file is generated from scripts/gensite.py, please don't edit directly. Edit the xml files in pages/ --> <!-- Generated from scripts/gensite.py, please don't edit directly. Edit the source file in the pages directory. --> <!-- This section is from pages/header.tmpl --> <head> <title>Leaf Peeping - Groton Trails</title> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="style.css" /> <link rel="stylesheet" href="print.css" media="print" /> <link href="https://fonts.googleapis.com/css?family=Neucha|Open+Sans" rel="stylesheet"> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin=""></script> <script src="javascripts/trailmap.js"></script> <link rel="icon" sizes="196x196" type="image/png" href="/images/GTN-green-196.png" > <link rel="icon" sizes="32x32" type="image/png" href="/images/GTN-green-32.png" > <link rel="icon" sizes="16x16" type="image/png" href="/images/GTN-green-16.png" > <link rel="apple-touch-icon" sizes="180x180" href="/images/GTN-green-180.png"> <link rel="apple-touch-icon" sizes="152x152" href="/images/GTN-green-152.png"> <link rel="apple-touch-icon" sizes="120x120" href="/images/GTN-green-120.png"> <link rel="apple-touch-icon" sizes="60x60" href="/images/GTN-green-60.png" > <link rel="apple-touch-icon" sizes="76x76" href="/images/GTN-green-76.png" > <link rel="manifest" href="manifest.json"> </head> <body> <!-- this section from pages/nav.tmpl --> <header role="banner"> <nav> <a href="Welcome.html">Welcome</a> <div class="dropdown"> <div onclick="dropdown('DropdownMaps')" class="dropbtn current">Maps</div> <div id="DropdownMaps" class="dropdown-content"> <a href="Interactive_Maps.html">Interactive Map</a> <a href="groton-town-forest-map.html">Town Forest Map</a> <a href="long-trails-map.html">Long Trails Map</a> <a href="printed_maps.html"> Printable Maps</a> </div> </div> <div class="dropdown"> <div onclick="dropdown('DropdownActivities')" class="dropbtn current">Activities</div> <div id="DropdownActivities" class="dropdown-content"> <a href="accessible-trail-walks.html">Accessible&nbsp;Trail&nbsp;Walks</a> <a href="bird-watching.html">Bird&nbsp;Watching</a> <a href="cross-country-skiing.html">Cross&nbsp;Country&nbsp;Skiing</a> <a href="field-walks.html">Field&nbsp;Walks</a> <a href="glacial-hikes.html">Glacial&nbsp;Hikes</a> <a href="horseback-riding.html">Horseback&nbsp;Riding</a> <a href="kid-friendly-walks.html">Kid&nbsp;Friendly&nbsp;Walks</a> <a href="leaf-peeping.html">Leaf&nbsp;Peeping</a> <a href="light-walks.html">Light&nbsp;Walks</a> <a href="mountain-biking.html">Mountain&nbsp;Biking&nbsp;Trails</a> <a href="camping.html">Places&nbsp;To&nbsp;Camp</a> <a href="places-to-get-lost.html">Places&nbsp;To&nbsp;Get&nbsp;Lost&nbsp;In</a> <a href="swimming.html">Places&nbsp;to&nbsp;Swim</a> <a href="river-walks.html">River&nbsp;Walks</a> </div> </div> <div class="dropdown"> <div onclick="dropdown('DropdownProperties')" class="dropbtn current">Properties</div> <div id="DropdownProperties" class="dropdown-content"> <a href="groton-town-forest.html">Groton&nbsp;Town&nbsp;Forest</a> </div> </div> <a href="about.html"> About&nbsp;Us</a> </nav> </header> <section class="title"> <p></p><img src="images/GTN.png" width="64px" height="64px"/> <h1>Leaf Peeping</h1> </section> <page title="Leaf Peeping"> <section class="quote"> <p><q>Nature’s first green is gold</q><br/>-Robert Frost</p> </section> <section class="post"> <H2>Scarlet Hill</H2> <section class="text"> <p>The Scarlet Hill walk starts out in a gorgeous field with views of grazing horses. The field opens up into rolling hillsides with a speckling of trees. Take your time and examine the uncut grass to observe the many gorgeous wildflowers. There is a quick but steep path up Scarlet Hill that leads to an amazing overlook. This Eastward overlook has a view of the MIT Haystack Observatory and miles of trees. The view of trees framed by the faint outline of blue mountains coupled with a picturesque view of the stables, makes for a gorgeous walk. </p> <p>The Scarlet Hill is a quick 10 minute hike. Park at the end of Shattuck Street and wear boots because some parts of the trail may be wet. </p> </section> <section class="photos-map"> <img class="mobile-only" height="350" src="images/scarlet-hill-barn.jpg" width="350"/> <img class="desktop" height="350" src="images/scarlet-hill-barn-wide.jpg" width="700"/> <img class="desktop" height="350" src="images/scarlet-hill-tree.jpg" width="350"/> <div class="postmap" id="scarlet"/> </section> <section class="links"> <a href="Media/Scarlet%20Hill%20Trail%20Map%20-%20Groton%20MA.pdf">Printable Map</a> </section> </section> <section class="post"> <H2>Gibbet Hill</H2> <section class="text"> <p>The Gibbet Hill walk is short, but steep. The walk up the hill takes less than 10 minutes and it has wonderful views at the top past the castle. </p> <p>This is an enchanting walk up to a castle of stone and views that stretch for miles. After a quick climb up the hill an old burned down castle emerges. The castle is framed by seemingly ancient trees and a grassy hilltop. The castle is a wonderful place to have a picnic and watch the sunset because there are places to sit and lots of shade. Shortly after the castle is a captivating westward view. The view looks across the lush green fields that fade into a forest of green in the spring and a fiery arramy in the fall. This view captivates the onlooker as houses, that seem to be painted on, peek through the trees. The truly picturesque lookout point on top of Gibbet Hill can truly be appreciated by all. </p> <p>There is very limited street parking. Please consider other locations during peak weekends in November or if visiting before 4:00 pm, park at the back of the Gibbet Hill Restaurant parking lot.</p> </section> <section class="photos-map"> <img class="mobile-only" height="350" src="images/gibbet-hill-overlook.jpg" width="350"/> <img class="desktop" height="350" src="images/gibbet-hill-overlook-wide.jpg" width="700"/> <img class="desktop" height="350" src="images/gibbet-hill-castle.jpg" width="350"/> <div class="postmap" id="gibbet"/> </section> <section class="links"> <a href="http://www.gibbethillgrill.com/wp-content/uploads/2016/03/gibbet-hill-history3.24.16.pdf"> Gibbet Hill History and Trail Map</a> <br/> <a href="https://www.youtube.com/watch?v=QonKbX3-A2g">Top 10 Videos - Gibbet Hill</a> </section> </section> <script> createSimpleMap('gibbet',[42.60793,-71.56050],16,{ parking: [42.60654,-71.55991],parking2:[42.60721,-71.56408],leaf:[42.60946,-71.56022]}); createSimpleMap('scarlet',[42.61130,-71.55120],16,{ parking:[42.61233,-71.55449],leaf:[42.61021,-71.54860]}); </script> </page> <!-- this section from pages/menuscript.tmpl --> <script> function dropdown(id) { if ( id != "DropdownProperties") { document.getElementById("DropdownProperties").classList.remove("show") } if ( id != "DropdownActivities") { document.getElementById("DropdownActivities").classList.remove("show") } if ( id != "DropdownMaps") { document.getElementById("DropdownMaps").classList.remove("show") } document.getElementById(id).classList.toggle("show"); } window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } </script> <footer> <p>Map &copy; <a href="https://www.mapbox.com">Mapbox</a>, <a href="https://openstreetmap.org">OpenStreetMap</a>, <a href="http://leafletjs.com">Leaflet</a> </footer> <script> </script> </body> </html>
{ "content_hash": "20c3ee2dca391206b3a722a4399fc789", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 156, "avg_line_length": 46.54545454545455, "alnum_prop": 0.6452907986111112, "repo_name": "grotontrails/grotontrails.github.io", "id": "52dc216bdec9217b054ce645f34ec23c547fb260", "size": "9218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "leaf-peeping.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4678" }, { "name": "CartoCSS", "bytes": "42435" }, { "name": "HTML", "bytes": "293257" }, { "name": "JavaScript", "bytes": "153493" }, { "name": "Python", "bytes": "12038" } ], "symlink_target": "" }
#ifndef __DEBUGGER_H__ #define __DEBUGGER_H__ #include <pthread.h> #include <map> #include "concurrency.h" namespace safs { class debug_task { public: virtual ~debug_task() { } virtual void run() = 0; }; class debugger { // We have to use map instead of unordered_map here because // we want to preserve the order of the tasks. std::map<int, debug_task *> tasks; spin_lock lock; atomic_integer task_id_gen; public: debugger(); ~debugger(); int register_task(debug_task *task) { int id = task_id_gen.inc(1); lock.lock(); tasks.insert(std::pair<int, debug_task *>(id, task)); lock.unlock(); return id; } void remove_task(int task_id) { lock.lock(); tasks.erase(task_id); lock.unlock(); } void run(); }; bool is_debug_enabled(); } #endif
{ "content_hash": "81cde984e8ae40850bfc33e93bd5b2b5", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 60, "avg_line_length": 13.719298245614034, "alnum_prop": 0.6457800511508951, "repo_name": "flashxio/FlashX", "id": "2871fe4d5290fb58daea317eca270e11ff776983", "size": "1496", "binary": false, "copies": "2", "ref": "refs/heads/release", "path": "libsafs/debugger.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3649" }, { "name": "C++", "bytes": "3702274" }, { "name": "CMake", "bytes": "9623" }, { "name": "Makefile", "bytes": "31838" }, { "name": "Perl", "bytes": "16384" }, { "name": "Python", "bytes": "1099" }, { "name": "R", "bytes": "3751" }, { "name": "Shell", "bytes": "12078" } ], "symlink_target": "" }
""" :Copyright: 2006-2020 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ # Test against an admin app because that doesn't require setup of brand # party. After all, both admin and party apps should react the same. def test_healthcheck_ok(admin_client): expected_media_type = 'application/health+json' response = admin_client.get('/health') assert response.status_code == 200 assert response.content_type == expected_media_type assert response.mimetype == expected_media_type assert response.get_json() == { 'status': 'ok', 'details': { 'rdbms': [{'status': 'ok'}], }, }
{ "content_hash": "e9b8227cc41d6fe0f6708ba89ceddf09", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 71, "avg_line_length": 28.956521739130434, "alnum_prop": 0.6561561561561562, "repo_name": "m-ober/byceps", "id": "d0212dc95eee73529e7156f0bb3ed698a10b421d", "size": "666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/blueprints/healthcheck/test_health_ok.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "38499" }, { "name": "Dockerfile", "bytes": "1302" }, { "name": "HTML", "bytes": "369989" }, { "name": "JavaScript", "bytes": "9483" }, { "name": "Python", "bytes": "1152996" } ], "symlink_target": "" }
/* * overload.cc * demostrate how to use function overloading. */ #include <iostream> using namespace std; /* square function for int, float and double */ int square( int x ); float square( float x ); double square( double x ); int main() { int x; float y; double z; cout << "?: "; cin >> x; cout << " integer " << square( x ) << endl; cout << "?: "; cin >> y; cout << " float " << square( y ) << endl; cout << "?: "; cin >> z; cout << "double " << square( z ) << endl; return 0; } int square( int x ) { return x * x; } float square( float y ) { return y * y; } double square( double z ) { return z * z; }
{ "content_hash": "8d73ee52b0de40e12820a6eb990a52dd", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 47, "avg_line_length": 16.564102564102566, "alnum_prop": 0.5464396284829721, "repo_name": "alexhilton/miscellaneous", "id": "60048de0a164579b6d0fe2733be73c4cd4fd07e6", "size": "646", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cc-work/basics/overload.cc", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "2857" }, { "name": "C", "bytes": "973615" }, { "name": "C++", "bytes": "181958" }, { "name": "CSS", "bytes": "20109" }, { "name": "Groovy", "bytes": "130" }, { "name": "HTML", "bytes": "171760" }, { "name": "Java", "bytes": "236452" }, { "name": "JavaScript", "bytes": "45233" }, { "name": "Makefile", "bytes": "291" }, { "name": "Perl", "bytes": "58226" }, { "name": "Perl6", "bytes": "772" }, { "name": "Python", "bytes": "84195" }, { "name": "R", "bytes": "2989" }, { "name": "Shell", "bytes": "8778" } ], "symlink_target": "" }
package com.example.androidtestarchitecture.util; import com.loopj.android.http.AsyncHttpClient; public class ConnectionManager { private static AsyncHttpClient httpClientInstance = null; public static AsyncHttpClient getInstance() { if ( httpClientInstance == null ) { httpClientInstance = new AsyncHttpClient(); httpClientInstance.setMaxRetriesAndTimeout(5, 30000); } return httpClientInstance; } public ConnectionManager() {} }
{ "content_hash": "bc87d9c8aed0c5344a22543c218e19da", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 58, "avg_line_length": 25.333333333333332, "alnum_prop": 0.7763157894736842, "repo_name": "lvcmenezes/architecture", "id": "25385dd8ce4a6a4c591faedd94356f15f1a85e91", "size": "456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/example/androidtestarchitecture/util/ConnectionManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17757" } ], "symlink_target": "" }
using System; namespace ComponentGlue.Tests.Attributes { [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class CustomResolveAttribute : Attribute { } }
{ "content_hash": "f3799bb7deae4abcf52679df657f61f3", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 116, "avg_line_length": 25.88888888888889, "alnum_prop": 0.7982832618025751, "repo_name": "smack0007/ComponentGlue", "id": "33ecaebebc3e79e70320022fcad8099f60a08c25", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ComponentGlue.Tests/Attributes/CustomResolveAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "91041" }, { "name": "Shell", "bytes": "457" } ], "symlink_target": "" }
module Skyrequest class Connector attr_accessor :cache, :index, :counter @@skycaches = [] #class variable def initialize() #Sky::Connector.new @cache = {} end def skylogger(request, user, time) @@skylogger ||= Logger.new("#{Rails.root}/log/skylogger.log") @@skylogger.info "\nRequest: #{request["value"]}\nUsername: #{user}\nZeitpunkt: #{time} \nResponse: #{request}" end def save_cache #save variables after new controller action @@skycaches << self end def cache return @cache end def save(data) #write skylogic answer into cache @cache[0] = data end def seterrors #rename integer errors into strings unless @cache.empty? case @cache[0]["status"] when 0 @cache[0]["status"] = "OK" when 1 @cache[0]["status"] = "Warning" when 2 @cache[0]["status"] = "Error" else @cache[0]["status"] = "Unknown Status" end end end def self.all #debug return @@skycaches end def changeids #newest request always on top unless @cache.empty? @temp_cache = {} @max_cache = @cache.count @keys = 0 while @keys < @max_cache #write cache into temp_cache @temp_cache[@keys] = @cache[@keys] @keys += 1 end while @keys > -1 #write temp_cache back into cache but increase index by 1 @cache[@keys] = @temp_cache[@keys-1] @keys -= 1 end @cache.delete(7) #don't let cache get bigger than 7 end end end end
{ "content_hash": "23b9ea3ae549aad32974ac6d57f717f9", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 90, "avg_line_length": 22.333333333333332, "alnum_prop": 0.6139755766621439, "repo_name": "RomanFrei/IPA-Roman", "id": "4689d90b3e02f83c16c03147199188f0781406cb", "size": "1474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/skyrequest.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "17885" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <appengine-web-app xmlns="http://appengine.google.com/ns/1.0"> <application>search-java-demo</application> <version>1</version> <threadsafe>true</threadsafe> <system-properties> <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/> </system-properties> </appengine-web-app>
{ "content_hash": "b897812a00daae6c214b70e5ab6e8713", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 62, "avg_line_length": 29.76923076923077, "alnum_prop": 0.6640826873385013, "repo_name": "GoogleCloudPlatform/appengine-search-python-java", "id": "0b669e448860ccf6f9497658542861b4ef39e663", "size": "387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/war/WEB-INF/appengine-web.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6302" }, { "name": "HTML", "bytes": "26799" }, { "name": "Java", "bytes": "15487" }, { "name": "JavaScript", "bytes": "8822" }, { "name": "Python", "bytes": "88625" } ], "symlink_target": "" }
<?php namespace Admin\PartenaireBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="Admin\PartenaireBundle\Entity\PartenaireRepository") * @ORM\Table(name="admin_partenaire") */ class Partenaire { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", length=150, nullable=false) */ protected $name; /** * @ORM\Column(type="text") */ protected $commentaire = ""; protected $domaines; }
{ "content_hash": "6524ba8c85870b4c68243064130b1c4e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 84, "avg_line_length": 17.766666666666666, "alnum_prop": 0.6585365853658537, "repo_name": "youkive/appPartenaire", "id": "73e388a63653628bddfe34541337c52e44a532ca", "size": "533", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Admin/PartenaireBundle/Entity/Partenaire.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "56" }, { "name": "PHP", "bytes": "55426" } ], "symlink_target": "" }
package rstats_test import ( "math" "math/rand" "sync" "testing" "github.com/lucindo/rstats" ) func equalf(a, b float64) bool { return !((a < b) || (a > b)) } func inequalf(a, b float64) bool { return !equalf(a, b) } func TestEmpty(t *testing.T) { stats := rstats.New() zero := float64(0.0) stString := "count 0 min +Inf max -Inf mean 0.00 (std dev 0.000 variance 0.00)" if stats.Count() != 0 { t.Error("Count of empty stats should be zero") } if inequalf(stats.Min(), math.Inf(0)) { t.Error("Min of empty should be equal of math.Inf(0)") } if inequalf(stats.Max(), math.Inf(-1)) { t.Error("Max of empty should be equal of math.Inf(-1)") } if inequalf(stats.Mean(), zero) { t.Error("Mean of empty should be equal to zero") } if inequalf(stats.Variance(), zero) { t.Error("Variance of empty should be equal to zero") } if inequalf(stats.StandardDeviation(), zero) { t.Error("StandardDeviation of empty should be equal to zero") } if inequalf(stats.Skewness(), zero) { t.Error("Skewness of empty should be equal to zero") } if inequalf(stats.Kurtosis(), zero) { t.Error("Kurtosis of empty should be equal to zero") } if stats.String() != stString { t.Errorf("String of empty should be equal to:\n'%s'\nbut got:\n'%s'", stString, stats.String()) } } func TestSameValue(t *testing.T) { stats := rstats.New() zero := float64(0.0) random := rand.Float64() count := uint64(10000) for i := uint64(0); i < count; i++ { stats.Add(random) } if stats.Count() != count { t.Errorf("Count should be %d, got %d", count, stats.Count()) } if inequalf(stats.Min(), random) { t.Error("Min should be equal to random") } if inequalf(stats.Max(), random) { t.Error("Max should be equal to random") } if inequalf(stats.Mean(), random) { t.Error("Mean should be equal to random") } if inequalf(stats.Variance(), zero) { t.Error("Variance should be equal to zero") } if inequalf(stats.StandardDeviation(), zero) { t.Error("StandardDeviation should be equal to zero") } if inequalf(stats.Skewness(), zero) { t.Error("Skewness should be equal to zero") } if inequalf(stats.Kurtosis(), zero) { t.Error("Kurtosis should be equal to zero") } } func TestBasic(t *testing.T) { stats := rstats.New() stats.Add(1.0) stats.Add(2.0) if inequalf(stats.Mean(), 1.5) { t.Errorf("Mean should be 1.5, got %v", stats.Mean()) } stats.Add(3) if inequalf(stats.Mean(), 2.0) { t.Errorf("Mean should be 2.0, got %v", stats.Mean()) } if inequalf(stats.StandardDeviation(), 1) { t.Errorf("StandardDeviation should be 1.0, got %v", stats.StandardDeviation()) } if inequalf(stats.Variance(), 1) { t.Errorf("Variance should be 1.0, got %v", stats.Variance()) } // TODO: add more basic tests } func TestStatsStruct(t *testing.T) { stats := rstats.New() random := rand.Float64() count := uint64(10000) for i := uint64(0); i < count; i++ { stats.Add(random) } statsStruct := new(rstats.StatsStruct) rstats.GetStatsStruct(statsStruct, stats) if statsStruct.Count != stats.Count() { t.Errorf("Count should be %d, got %d", statsStruct.Count, stats.Count()) } if inequalf(statsStruct.Min, stats.Min()) { t.Errorf("Min should be %f, got %f", statsStruct.Min, stats.Min()) } if inequalf(statsStruct.Max, stats.Max()) { t.Errorf("Max should be %f, got %f", statsStruct.Max, stats.Max()) } if inequalf(statsStruct.Mean, stats.Mean()) { t.Errorf("Mean should be %f, got %f", statsStruct.Mean, stats.Mean()) } if inequalf(statsStruct.Variance, stats.Variance()) { t.Errorf("Variance should be %f, got %f", statsStruct.Variance, stats.Variance()) } if inequalf(statsStruct.StandardDeviation, stats.StandardDeviation()) { t.Errorf("StandardDeviation should be %f, got %f", statsStruct.StandardDeviation, stats.StandardDeviation()) } if inequalf(statsStruct.Skewness, stats.Skewness()) { t.Errorf("Skewness should be %f, got %f", statsStruct.Skewness, stats.Skewness()) } if inequalf(statsStruct.Kurtosis, stats.Kurtosis()) { t.Errorf("Kurtosis should be %f, got %f", statsStruct.Kurtosis, stats.Kurtosis()) } } func TestConcurrency(t *testing.T) { stats := rstats.New() zero := float64(0.0) random := rand.Float64() count := uint64(1000) gorotines := 100 var group sync.WaitGroup for g := 0; g < gorotines; g++ { group.Add(1) go func(stats *rstats.Stats, group *sync.WaitGroup) { for i := uint64(0); i < count; i++ { stats.Add(random) } group.Done() }(stats, &group) } group.Wait() if stats.Count() != count*uint64(gorotines) { t.Errorf("Count should be %d, got %d", count, stats.Count()) } if inequalf(stats.Min(), random) { t.Error("Min should be equal to random") } if inequalf(stats.Max(), random) { t.Error("Max should be equal to random") } if inequalf(stats.Mean(), random) { t.Error("Mean should be equal to random") } if inequalf(stats.Variance(), zero) { t.Error("Variance should be equal to zero") } if inequalf(stats.StandardDeviation(), zero) { t.Error("StandardDeviation should be equal to zero") } if inequalf(stats.Skewness(), zero) { t.Error("Skewness should be equal to zero") } if inequalf(stats.Kurtosis(), zero) { t.Error("Kurtosis should be equal to zero") } } func BenchmarkStats(b *testing.B) { stats := rstats.New() for n := 0; n < b.N; n++ { stats.Add(1.0) } }
{ "content_hash": "26e48441c4f8f0651b4d93805432bc83", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 110, "avg_line_length": 23.017094017094017, "alnum_prop": 0.6581878945414036, "repo_name": "lucindo/rstats", "id": "f55f6a8f0a115f03ec58a7faf13be052163b508f", "size": "5386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rstats_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "9586" } ], "symlink_target": "" }
from datetime import datetime from getopt import getopt, GetoptError import json import os from subprocess import Popen, PIPE import sys from tempfile import NamedTemporaryFile SAVEDIR = "fragments/" GENERATOR = "mop/build/fragments" REPODIR = "mop/data/fragments/" DEFAULT_REPO = "lipids" DEFAULT_SHELL_SIZE = 1 class ValidationError(Exception): pass def molecule_to_lgf(molecule): lgf = "" lgf += atoms_to_lgf(molecule["atoms"]) lgf += bonds_to_lgf(molecule["bonds"]) return lgf def atoms_to_lgf(atoms): lgf = "@nodes\n" lgf += "partial_charge\tlabel\tlabel2\tatomType\tcoordX\tcoordY\t" + \ "coordZ\tinitColor\t\n" for atom in atoms: lgf += "0\t%s\tX\t%s\t0\t0\t0\t0\t\n" % (atom["id"], atom["type"]) return lgf def bonds_to_lgf(bonds): lgf = "@edges\n" lgf += "\t\tlabel\n" for i, bond in enumerate(bonds): lgf += "%s\t%s\t%s\t\n" % (bond["a1"], bond["a2"], i) return lgf def generate_fragments(lgf, repo, shell, outfile, atom_ids): repo_path = os.path.normpath("%s/%s" % (REPODIR, repo)) molecules = [] with NamedTemporaryFile() as fp: fp.write(lgf) fp.seek(0) for file in os.listdir(repo_path): name, ext = os.path.splitext(file) if ext == ".lgf": mf = generate_molecule_fragments( name, "%s/%s" % (repo_path, file), shell, fp.name ) if len(mf["fragments"]) > 0: molecules.append(mf) found_ids = set() for molecule in molecules: for fragment in molecule["fragments"]: for pair in fragment["pairs"]: found_ids.add(pair["id1"]) missing_atoms = set(atom_ids) - found_ids res = json.dumps({ "molecules": molecules, "missing_atoms": list(missing_atoms) }, default=(lambda o: o.__dict__)) outpath = os.path.normpath("%s/%s" % (SAVEDIR, outfile)) with open(outpath, "w") as fp: fp.write(res) return {'off': outfile, 'missing_atoms': list(missing_atoms)} def generate_molecule_fragments(molid, molfile, shell, infile): p = Popen( "%s -s %s -atb_id %s %s %s" % (GENERATOR, shell, molid, infile, molfile), shell=True, stdout=PIPE, stderr=PIPE ) out, err = p.communicate() if len(err) > 0: raise ValidationError(err) try: return json.loads(out) except ValueError as e: raise ValidationError("Generator returned invalid JSON: %s" % e) def main(argv): repo = DEFAULT_REPO shell = DEFAULT_SHELL_SIZE ffid = datetime.now().strftime("%Y%m%d%H%M%S%f") while os.path.exists("%s/%s.off" % (SAVEDIR, ffid)): ffid = str(int(ffid) - 1) outfile = "%s.off" % ffid try: opts, args = getopt( argv[1:], "r:s:o:", ["repository=", "shell_size=", "ofile="] ) except (GetoptError, IndexError) as e: raise ValidationError("Invalid script invocation: %s" % e) for o, v in opts: if o in ("-r", "--repository"): rp = os.path.normpath(v) repo_path = os.path.normpath("%s/%s" % (REPODIR, rp)) if os.path.exists(repo_path): repo = rp else: raise ValidationError("Provided repository (%s) does not exist" % rp) elif o in ("-s", "--shell_size"): try: shell = int(v) if shell < 1: raise ValidationError("Shell size needs to be a positive integer") except ValueError as e: raise ValidationError("Shell size needs to be an integer") elif o in ("-o", "--ofile"): op = os.path.normpath("%s/%s" % (SAVEDIR, v)) dir, _ = os.path.split(op) if os.path.exists(dir): outfile = v else: raise ValidationError("Output folder does not exist") try: data = args[0] jd = json.loads(data) except IndexError as e: raise ValidationError("Invalid script invocation: JSON query not set") except ValueError as e: raise ValidationError("JSON query is invalid: %s" % e) lgf = molecule_to_lgf(jd["molecule"]) atom_ids = map(lambda a: a["id"], jd["molecule"]["atoms"]) out = generate_fragments(lgf, repo, shell, outfile, atom_ids) print json.dumps(out, default=lambda o: o.__dict__) if __name__ == "__main__": try: main(sys.argv) except Exception as e: print json.dumps({"error": "Invalid query: %s" % e})
{ "content_hash": "df9fd79938fca98d73ab614b0b466920", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 77, "avg_line_length": 27.10967741935484, "alnum_prop": 0.6149452641599239, "repo_name": "jimivdw/OMFraF", "id": "55687e69607e094e9fdf6d7b0515ffaa7a4b124d", "size": "4220", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/bin/fragment_generator.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "29610" } ], "symlink_target": "" }
const bcrypt = require('bcrypt'); module.exports = { hashPassword(password) { return bcrypt.hashSync(password, bcrypt.genSaltSync(10)); }, verifyPassword(password, hash) { return bcrypt.compareSync(password, hash) } };
{ "content_hash": "2c39c8bc38e6dac9c5d75ec43d1ae5a8", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 65, "avg_line_length": 25.2, "alnum_prop": 0.6547619047619048, "repo_name": "fletchto99/CTFort", "id": "20a68de8ff39e39230a6ce6ba0f15ccc4929faeb", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/app/shared/security.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1010" }, { "name": "HTML", "bytes": "9218" }, { "name": "JavaScript", "bytes": "19932" }, { "name": "TypeScript", "bytes": "7642" } ], "symlink_target": "" }
using System.Collections.Generic; using DromundKaasII.Engine.GameObjects.Skills; using Microsoft.Xna.Framework; namespace DromundKaasII.Engine.GameObjects.Actors.NPCs { /// <summary> /// Catch-all class for all Npc's. /// </summary> public abstract class Npc : Actor { /// <summary> /// Initializes a new Npc. /// </summary> /// <param name="MapPosition">The Npc's position.</param> /// <param name="SkillChain">The skills the Npc can pick from.</param> public Npc(Vector2 MapPosition, Dictionary<string, Skill> SkillChain) : base(MapPosition, SkillChain) { } } }
{ "content_hash": "500ab55ddea732d058912f3fd1d3a9db", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 78, "avg_line_length": 28.695652173913043, "alnum_prop": 0.6272727272727273, "repo_name": "yasvisu/Dromund-Kaas-II", "id": "330a1f95d051f674810a02cc0c0cffcd7d936a98", "size": "662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DromundKaasII/DromundKaas/Engine/GameObjects/Actors/NPCs/Npc.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "166236" } ], "symlink_target": "" }
;( function( window ) { 'use strict'; /** * based on from https://github.com/inuyaksa/jquery.nicescroll/blob/master/jquery.nicescroll.js */ function hasParent( e, p ) { if (!e) return false; var el = e.target||e.srcElement||e||false; while (el && el != p) { el = el.parentNode||false; } return (el!==false); }; /** * extend obj function */ function extend( a, b ) { for( var key in b ) { if( b.hasOwnProperty( key ) ) { a[key] = b[key]; } } return a; } /** * SelectFx function */ function SelectFx( el, options ) { this.el = el; this.options = extend( {}, this.options ); extend( this.options, options ); this._init(); } /** * SelectFx options */ SelectFx.prototype.options = { // if true all the links will open in a new tab. // if we want to be redirected when we click an option, we need to define a data-link attr on the option of the native select element newTab : true, // when opening the select element, the default placeholder (if any) is shown stickyPlaceholder : true, // callback when changing the value onChange : function( val ) { return false; } } /** * init function * initialize and cache some vars */ SelectFx.prototype._init = function() { var selectDisabled = false; if (this.el.hasAttribute("disabled")) { this.el.className = this.el.className + " disabled"; selectDisabled = true; }; // check if we are using a placeholder for the native select box // we assume the placeholder is disabled and selected by default var selectedOpt = this.el.querySelector( 'option[selected]' ); this.hasDefaultPlaceholder = selectedOpt && selectedOpt.disabled; // get selected option (either the first option with attr selected or just the first option) this.selectedOpt = selectedOpt || this.el.querySelector( 'option' ); // create structure this._createSelectEl(); // all options this.selOpts = [].slice.call( this.selEl.querySelectorAll( 'li[data-option]' ) ); // total options this.selOptsCount = this.selOpts.length; // current index this.current = this.selOpts.indexOf( this.selEl.querySelector( 'li.cs-selected' ) ) || -1; // placeholder elem this.selPlaceholder = this.selEl.querySelector( 'span.cs-placeholder' ); if (!selectDisabled) { // init events this._initEvents(); } } /** * creates the structure for the select element */ SelectFx.prototype._createSelectEl = function() { var self = this, options = '', createOptionHTML = function(el) { var optclass = '', classes = '', link = ''; if( el.selectedOpt && !this.foundSelected && !this.hasDefaultPlaceholder ) { classes += 'cs-selected '; this.foundSelected = true; } // extra classes if( el.getAttribute( 'data-class' ) ) { classes += el.getAttribute( 'data-class' ); } // link options if( el.getAttribute( 'data-link' ) ) { link = 'data-link=' + el.getAttribute( 'data-link' ); } if( classes !== '' ) { optclass = 'class="' + classes + '" '; } return '<li ' + optclass + link + ' data-option data-value="' + el.value + '"><span>' + el.textContent + '</span></li>'; }; [].slice.call( this.el.children ).forEach( function(el) { if( el.disabled ) { return; } var tag = el.tagName.toLowerCase(); if( tag === 'option' ) { options += createOptionHTML(el); } else if( tag === 'optgroup' ) { options += '<li class="cs-optgroup"><span>' + el.label + '</span><ul>'; [].slice.call( el.children ).forEach( function(opt) { options += createOptionHTML(opt); } ) options += '</ul></li>'; } } ); var opts_el = '<div class="cs-options"><ul>' + options + '</ul></div>'; this.selEl = document.createElement( 'div' ); this.selEl.className = this.el.className; this.selEl.tabIndex = this.el.tabIndex; this.selEl.innerHTML = '<span class="cs-placeholder">' + this.selectedOpt.textContent + '</span>' + opts_el; this.el.parentNode.appendChild( this.selEl ); this.selEl.appendChild( this.el ); } /** * initialize the events */ SelectFx.prototype._initEvents = function() { var self = this; // open/close select this.selPlaceholder.addEventListener( 'click', function() { self._toggleSelect(); } ); // clicking the options this.selOpts.forEach( function(opt, idx) { opt.addEventListener( 'click', function() { self.current = idx; self._changeOption(); // close select elem self._toggleSelect(); } ); } ); // close the select element if the target it´s not the select element or one of its descendants.. document.addEventListener( 'click', function(ev) { var target = ev.target; if( self._isOpen() && target !== self.selEl && !hasParent( target, self.selEl ) ) { self._toggleSelect(); } } ); // keyboard navigation events this.selEl.addEventListener( 'keydown', function( ev ) { var keyCode = ev.keyCode || ev.which; switch (keyCode) { // up key case 38: ev.preventDefault(); self._navigateOpts('prev'); break; // down key case 40: ev.preventDefault(); self._navigateOpts('next'); break; // space key case 32: ev.preventDefault(); if( self._isOpen() && typeof self.preSelCurrent != 'undefined' && self.preSelCurrent !== -1 ) { self._changeOption(); } self._toggleSelect(); break; // enter key case 13: ev.preventDefault(); if( self._isOpen() && typeof self.preSelCurrent != 'undefined' && self.preSelCurrent !== -1 ) { self._changeOption(); self._toggleSelect(); } break; // esc key case 27: ev.preventDefault(); if( self._isOpen() ) { self._toggleSelect(); } break; } } ); } /** * navigate with up/dpwn keys */ SelectFx.prototype._navigateOpts = function(dir) { if( !this._isOpen() ) { this._toggleSelect(); } var tmpcurrent = typeof this.preSelCurrent != 'undefined' && this.preSelCurrent !== -1 ? this.preSelCurrent : this.current; if( dir === 'prev' && tmpcurrent > 0 || dir === 'next' && tmpcurrent < this.selOptsCount - 1 ) { // save pre selected current - if we click on option, or press enter, or press space this is going to be the index of the current option this.preSelCurrent = dir === 'next' ? tmpcurrent + 1 : tmpcurrent - 1; // remove focus class if any.. this._removeFocus(); // add class focus - track which option we are navigating classie.add( this.selOpts[this.preSelCurrent], 'cs-focus' ); } } /** * open/close select * when opened show the default placeholder if any */ SelectFx.prototype._toggleSelect = function() { // remove focus class if any.. this._removeFocus(); if( this._isOpen() ) { if( this.current !== -1 ) { // update placeholder text this.selPlaceholder.textContent = this.selOpts[ this.current ].textContent; } classie.remove( this.selEl, 'cs-active' ); } else { if( this.hasDefaultPlaceholder && this.options.stickyPlaceholder ) { // everytime we open we wanna see the default placeholder text this.selPlaceholder.textContent = this.selectedOpt.textContent; } classie.add( this.selEl, 'cs-active' ); } } /** * change option - the new value is set */ SelectFx.prototype._changeOption = function() { // if pre selected current (if we navigate with the keyboard)... if( typeof this.preSelCurrent != 'undefined' && this.preSelCurrent !== -1 ) { this.current = this.preSelCurrent; this.preSelCurrent = -1; } // current option var opt = this.selOpts[ this.current ]; // update current selected value this.selPlaceholder.textContent = opt.textContent; // change native select element´s value this.el.value = opt.getAttribute( 'data-value' ); // remove class cs-selected from old selected option and add it to current selected option var oldOpt = this.selEl.querySelector( 'li.cs-selected' ); if( oldOpt ) { classie.remove( oldOpt, 'cs-selected' ); } classie.add( opt, 'cs-selected' ); // if there´s a link defined if( opt.getAttribute( 'data-link' ) ) { // open in new tab? if( this.options.newTab ) { window.open( opt.getAttribute( 'data-link' ), '_blank' ); } else { window.location = opt.getAttribute( 'data-link' ); } } // callback this.options.onChange( this.el.value ); } /** * returns true if select element is opened */ SelectFx.prototype._isOpen = function(opt) { return classie.has( this.selEl, 'cs-active' ); } /** * removes the focus class from the option */ SelectFx.prototype._removeFocus = function(opt) { var focusEl = this.selEl.querySelector( 'li.cs-focus' ) if( focusEl ) { classie.remove( focusEl, 'cs-focus' ); } } /** * add to global namespace */ window.SelectFx = SelectFx; } )( window );
{ "content_hash": "e7af1fa6710d1da166e47108e8851ea9", "timestamp": "", "source": "github", "line_count": 323, "max_line_length": 139, "avg_line_length": 28.591331269349844, "alnum_prop": 0.6051976177585273, "repo_name": "songhongyu/idaiyan", "id": "db34eff865ee6ca05c86f53a72ca425712ae1522", "size": "9454", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "backend/web/static/vendor/selectFx/selectFx.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "312" }, { "name": "Batchfile", "bytes": "1541" }, { "name": "CSS", "bytes": "1047289" }, { "name": "HTML", "bytes": "1943794" }, { "name": "JavaScript", "bytes": "3869118" }, { "name": "PHP", "bytes": "3038119" } ], "symlink_target": "" }
u"""async requests to server over http :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkconfig from pykern import pkjson from pykern.pkcollections import PKDict from pykern.pkdebug import pkdp, pkdexc, pkdlog import asyncio import contextlib import copy import re import sirepo.sim_data import sirepo.util import time import tornado.httpclient import random CODES = PKDict( elegant=[ PKDict( name='bunchComp - fourDipoleCSR', reports=[ 'bunchReport1', 'elementAnimation10-5', ], ), PKDict( name='SPEAR3', reports=[ 'bunchReport2', 'elementAnimation62-3', ], ), ], jspec=[ PKDict( name='Booster Ring', reports=[ 'particleAnimation', 'rateCalculationReport', ], ), ], srw=[ PKDict( name='Tabulated Undulator Example', reports=[ 'intensityReport', 'trajectoryReport', 'multiElectronAnimation', 'powerDensityReport', 'sourceIntensityReport', ], ), PKDict( name='Bending Magnet Radiation', reports=[ 'initialIntensityReport', 'intensityReport', 'powerDensityReport', 'sourceIntensityReport', 'trajectoryReport', ], ), ], synergia=[ PKDict( name='IOTA 6-6 Bare', reports=[ 'beamEvolutionAnimation', 'bunchReport1', ], ), ], warppba=[ PKDict( name='Laser Pulse', reports=[ 'fieldAnimation', 'laserPreviewReport', ], ), ], warpvnd=[ PKDict( name='EGun Example', reports=[ 'fieldAnimation', ], ), ], ) cfg = None def default_command(): _init() random.seed() asyncio.run(_run_all()) async def _cancel_on_exception(task): try: await task except Exception as e: task.cancel() raise class _Client(PKDict): _global_lock = asyncio.Lock() _login_locks = PKDict() def __init__(self, **kwargs): super().__init__( _client=tornado.httpclient.AsyncHTTPClient(), _headers=PKDict({'User-Agent': 'test_http'}), **kwargs ) def copy(self): n = type(self)() for k, v in self.items(): if k != '_client': n[k] = copy.deepcopy(v) return n async def get(self, uri): uri = self._uri(uri) with _timer(uri): return self.parse_response( await self._client.fetch( uri, headers=self._headers, method='GET', connect_timeout=1e8, request_timeout=1e8, ) ) async def login(self): r = await self.post('/simulation-list', PKDict()) assert r.srException.routeName == 'missingCookies' r = await self.post('/simulation-list', PKDict()) assert r.srException.routeName == 'login' async with self._global_lock: self._login_locks.pksetdefault(self.email, asyncio.Lock()) async with self._login_locks[self.email]: r = await self.post('/auth-email-login', PKDict(email=self.email)) t = sirepo.util.create_token( self.email, ).decode() r = await self.post( self._uri('/auth-email-authorized/{}/{}'.format(self.sim_type, t)), data=PKDict(token=t, email=self.email), ) assert r.state != 'srException', 'r={}'.format(r) if r.authState.needCompleteRegistration: r = await self.post( '/auth-complete-registration', PKDict(displayName=self.email), ) r = await self.post('/simulation-list', PKDict()) self._sid = PKDict([(x.name, x.simulationId) for x in r]) self._sim_db = PKDict() self._sim_data = sirepo.sim_data.get_class(self.sim_type) return self def parse_response(self, resp): self.resp = resp assert self.resp.code == 200, 'resp={}'.format(resp) self.json = None if 'Set-Cookie' in resp.headers: self._headers.Cookie = resp.headers['Set-Cookie'] if 'json' in resp.headers['content-type']: self.json = pkjson.load_any(resp.body) return self.json try: b = resp.body.decode() except UnicodeDecodeError: # Binary data files can't be decoded return if 'html' in resp.headers['content-type']: m = re.search('location = "(/[^"]+)', b) if m: if 'error' in m.group(1): self.json = PKDict(state='error', error='server error') else: self.json = PKDict(state='redirect', uri=m.group(1)) return self.json return b async def post(self, uri, data): data.simulationType = self.sim_type uri = self._uri(uri) with _timer( 'uri={} email={} simulationId={} report={}'.format( uri, self.email, data.get('simulationId'), data.get('report') ), ): return self.parse_response( await self._client.fetch( uri, body=pkjson.dump_bytes(data), headers=self._headers.pksetdefault( 'Content-type', 'application/json' ), method='POST', connect_timeout=1e8, request_timeout=1e8, ), ) async def sim_db(self, sim_name): try: return self._sim_db[sim_name] except KeyError: self._sim_db[sim_name] = await self.get( '/simulation/{}/{}/0'.format( self.sim_type, self._sid[sim_name], ), ) return self._sim_db[sim_name] async def sim_run(self, name, report, timeout=90): async def _run(self): c = None i = self._sid[name] d = await self.sim_db(name) pkdlog('sid={} report={} state=start', i, report) r = await self._run_simulation(d, i, report) try: p = self._sim_data.is_parallel(report) if r.state == 'completed': return c = r.get('nextRequest') for _ in range(timeout): if r.state in ('completed', 'error'): c = None break assert 'nextRequest' in r, \ 'expected "nextRequest" in response={}'.format(r) r = await self.post('/run-status', r.nextRequest) await asyncio.sleep(1) else: pkdlog('sid={} report={} timeout={}', i, report, timeout) except asyncio.CancelledError: return except Exception: pkdlog('r={}', r) raise finally: if c: await self.post('/run-cancel', c) s = 'cancel' if c else r.get('state') e = False if s == 'error': e = True s = r.get('error', '<unknown error>') pkdlog('sid={} report={} state={}', i, report, s) assert not e, \ 'unexpected error state, error={} sid={}, report={}'.format(s, i, report) if p: g = self._sim_data.frame_id(d, r, report, 0) f = await self.get('/simulation-frame/' + g) assert 'title' in f, \ 'no title in frame={}'.format(f) await self.get( '/download-data-file/{}/{}/{}/{}'.format( self.sim_type, i, report, 0, ), ) c = None try: c = await self._run_simulation(d, i, report) f = await self.get('/simulation-frame/' + g) assert f.state == 'error', \ 'expecting error instead of frame={}'.format(f) except asyncio.CancelledError: return finally: if c: await self.post('/run-cancel', c.get('nextRequest')) return await _run(self.copy()) async def _run_simulation(self, data, simulation_id, report): # TODO(e-carlin): why is this true? if 'animation' in report.lower() and self.sim_type != 'srw': report = 'animation' return await self.post( '/run-simulation', PKDict( # works for sequential simulations, too forceRun=True, models=data.models, report=report, simulationId=simulation_id, simulationType=self.sim_type, ), ) def _uri(self, uri): if uri.startswith('http'): return uri assert uri.startswith('/') # Elegant frame_id's sometimes have spaces in them so need to # make them url safe. But, the * in the url should not be made # url safe return cfg.server_uri + uri.replace(' ', '%20') def _init(): global cfg if cfg: return cfg = pkconfig.init( server_uri=('http://127.0.0.1:8000', str, 'where to send requests'), ) async def _run(email, sim_type): await _run_sequential_parallel( await _Client(email=email, sim_type=sim_type).login(), ) async def _run_all(): l = [] for a in ( ('one@b.c', 'elegant'), ('one@b.c', 'jspec'), ('one@b.c', 'srw',), ('one@b.c', 'synergia'), ('one@b.c', 'warppba'), ('one@b.c', 'warpvnd'), ('two@b.c', 'elegant'), ('two@b.c', 'jspec'), ('two@b.c', 'srw',), ('two@b.c', 'synergia'), ('two@b.c', 'warppba'), ('two@b.c', 'warpvnd'), ('three@b.c', 'elegant'), ('three@b.c', 'jspec'), ('three@b.c', 'srw',), ('three@b.c', 'synergia'), ('three@b.c', 'warppba'), ('three@b.c', 'warpvnd'), ): l.append(_run(*a)) await _cancel_on_exception(asyncio.gather(*l)) async def _run_sequential_parallel(client): c = [] s = CODES[client.sim_type] e = s[random.randrange(len(s))] random.shuffle(e.reports) for r in e.reports: c.append(client.sim_run(e.name, r)) await _cancel_on_exception(asyncio.gather(*c)) @contextlib.contextmanager def _timer(description): s = time.time() yield if 'run-status' not in description: pkdlog('{} elapsed_time={}', description, time.time() - s)
{ "content_hash": "c7dee182b4c28ad55afb3b7351f40a4b", "timestamp": "", "source": "github", "line_count": 380, "max_line_length": 93, "avg_line_length": 31.23421052631579, "alnum_prop": 0.46229673940517313, "repo_name": "mrakitin/sirepo", "id": "dd36c60ed5b7c3a3234c5880291235ebeb31b650", "size": "11893", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sirepo/pkcli/test_http.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "152" }, { "name": "CSS", "bytes": "261041" }, { "name": "HTML", "bytes": "335926" }, { "name": "JavaScript", "bytes": "2681704" }, { "name": "Opal", "bytes": "38855" }, { "name": "Python", "bytes": "1949902" }, { "name": "Shell", "bytes": "17536" } ], "symlink_target": "" }
@interface PSDateFieldEditor : NSTextView { NSArray *allCompletions; } - (id)initWithCompletions:(NSArray *)dateCompletions; @end
{ "content_hash": "e2b1e6355b4ff80cb28302d95644feaf", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 53, "avg_line_length": 19.428571428571427, "alnum_prop": 0.7573529411764706, "repo_name": "nriley/Pester", "id": "8d46e388066f320d9b0db655a24133afa597015f", "size": "304", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/PSDateFieldEditor.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "14557" }, { "name": "JavaScript", "bytes": "34030" }, { "name": "Objective-C", "bytes": "484994" }, { "name": "Shell", "bytes": "4127" } ], "symlink_target": "" }
#include "Tudat/JsonInterface/Propagation/variable.h" #include "Tudat/JsonInterface/Propagation/acceleration.h" #include "Tudat/JsonInterface/Propagation/torque.h" #include "Tudat/JsonInterface/Propagation/referenceFrames.h" #include "Tudat/JsonInterface/Environment/gravityFieldVariation.h" namespace tudat { namespace propagators { // VariableSettings //! Create a `json` object from a shared pointer to a `SingleDependentVariableSaveSettings` object. void to_json( nlohmann::json& jsonObject, const std::shared_ptr< VariableSettings >& variableSettings ) { if ( ! variableSettings ) { return; } using namespace json_interface; using K = Keys::Variable; const VariableType variableType = variableSettings->variableType_; switch ( variableType ) { case independentVariable: case cpuTimeVariable: case stateVariable: { jsonObject[ K::type ] = variableType; return; } case dependentVariable: { jsonObject = std::dynamic_pointer_cast< SingleDependentVariableSaveSettings >( variableSettings ); return; } case stateTransitionMatrix: { jsonObject[ K::type ] = variableType; return; } case sensitivityMatrix: { jsonObject[ K::type ] = variableType; return; } default: handleUnimplementedEnumValue( variableType, variableTypes, unsupportedVariableTypes ); } } //! Create a shared pointer to a `VariableSettings` object from a `json` object. void from_json( const nlohmann::json& jsonObject, std::shared_ptr< VariableSettings >& variableSettings ) { using namespace basic_astrodynamics; using namespace reference_frames; using namespace json_interface; using K = Keys::Variable; const VariableType variableType = getValue< VariableType >( jsonObject, K::type, dependentVariable ); switch ( variableType ) { case independentVariable: case cpuTimeVariable: case stateVariable: { variableSettings = std::make_shared< VariableSettings >( variableType ); return; } case dependentVariable: { variableSettings = getAs< std::shared_ptr< SingleDependentVariableSaveSettings > >( jsonObject ); return; } case stateTransitionMatrix: { variableSettings = std::make_shared< VariableSettings >( variableType ); return; } case sensitivityMatrix: { variableSettings = std::make_shared< VariableSettings >( variableType ); return; } default: handleUnimplementedEnumValue( variableType, variableTypes, unsupportedVariableTypes ); } } // SingleDependentVariableSaveSettings //! Create a `json` object from a shared pointer to a `SingleDependentVariableSaveSettings` object. void to_json( nlohmann::json& jsonObject, const std::shared_ptr< SingleDependentVariableSaveSettings >& dependentVariableSettings ) { if ( !dependentVariableSettings ) { return; } using namespace json_interface; using K = Keys::Variable; const PropagationDependentVariables dependentVariableType = dependentVariableSettings->dependentVariableType_; jsonObject[ K::dependentVariableType ] = dependentVariableType; jsonObject[ K::body ] = dependentVariableSettings->associatedBody_; if ( dependentVariableSettings->componentIndex_ >= 0 ) { jsonObject[ K::componentIndex ] = dependentVariableSettings->componentIndex_; } switch ( dependentVariableType ) { case single_acceleration_norm_dependent_variable: case single_acceleration_dependent_variable: { std::shared_ptr< SingleAccelerationDependentVariableSaveSettings > accelerationVariableSettings = std::dynamic_pointer_cast< SingleAccelerationDependentVariableSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( accelerationVariableSettings ); jsonObject[ K::accelerationType ] = accelerationVariableSettings->accelerationModelType_; jsonObject[ K::bodyExertingAcceleration ] = dependentVariableSettings->secondaryBody_; return; } case spherical_harmonic_acceleration_terms_dependent_variable: { std::shared_ptr< SphericalHarmonicAccelerationTermsDependentVariableSaveSettings > sphericalHarmonicsSettings = std::dynamic_pointer_cast< SphericalHarmonicAccelerationTermsDependentVariableSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( sphericalHarmonicsSettings ); jsonObject[ K::bodyExertingAcceleration ] = dependentVariableSettings->secondaryBody_; jsonObject[ K::componentIndices ] = sphericalHarmonicsSettings->componentIndices_; jsonObject[ K::componentIndex ] = dependentVariableSettings->componentIndex_; return; } case single_torque_norm_dependent_variable: case single_torque_dependent_variable: { std::shared_ptr< SingleTorqueDependentVariableSaveSettings > torqueVariableSettings = std::dynamic_pointer_cast< SingleTorqueDependentVariableSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( torqueVariableSettings ); jsonObject[ K::torqueType ] = torqueVariableSettings->torqueModelType_; jsonObject[ K::bodyExertingTorque ] = dependentVariableSettings->secondaryBody_; return; } case intermediate_aerodynamic_rotation_matrix_variable: { std::shared_ptr< IntermediateAerodynamicRotationVariableSaveSettings > aerodynamicRotationVariableSettings = std::dynamic_pointer_cast< IntermediateAerodynamicRotationVariableSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( aerodynamicRotationVariableSettings ); jsonObject[ K::baseFrame ] = aerodynamicRotationVariableSettings->baseFrame_; jsonObject[ K::targetFrame ] = aerodynamicRotationVariableSettings->targetFrame_; return; } case relative_body_aerodynamic_orientation_angle_variable: { std::shared_ptr< BodyAerodynamicAngleVariableSaveSettings > aerodynamicAngleVariableSettings = std::dynamic_pointer_cast< BodyAerodynamicAngleVariableSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( aerodynamicAngleVariableSettings ); jsonObject[ K::angle ] = aerodynamicAngleVariableSettings->angle_; return; } case single_gravity_field_variation_acceleration: { std::shared_ptr< SingleVariationSphericalHarmonicAccelerationSaveSettings > variationalSphericalHarmonicsAccelerationSettings = std::dynamic_pointer_cast< SingleVariationSphericalHarmonicAccelerationSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( variationalSphericalHarmonicsAccelerationSettings ); jsonObject[ K::bodyExertingAcceleration ] = variationalSphericalHarmonicsAccelerationSettings->secondaryBody_; jsonObject[ K::deformationType ] = variationalSphericalHarmonicsAccelerationSettings->deformationType_; jsonObject[ K::identifier ] = variationalSphericalHarmonicsAccelerationSettings->identifier_; return; } case single_gravity_field_variation_acceleration_terms: { std::shared_ptr< SingleVariationSingleTermSphericalHarmonicAccelerationSaveSettings > variationalSphericalHarmonicsAccelerationTermsSettings = std::dynamic_pointer_cast< SingleVariationSingleTermSphericalHarmonicAccelerationSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( variationalSphericalHarmonicsAccelerationTermsSettings ); jsonObject[ K::bodyExertingAcceleration ] = variationalSphericalHarmonicsAccelerationTermsSettings->secondaryBody_; jsonObject[ K::componentIndices ] = variationalSphericalHarmonicsAccelerationTermsSettings->componentIndices_; jsonObject[ K::deformationType ] = variationalSphericalHarmonicsAccelerationTermsSettings->deformationType_; jsonObject[ K::identifier ] = variationalSphericalHarmonicsAccelerationTermsSettings->identifier_; return; } case acceleration_partial_wrt_body_translational_state: { std::shared_ptr< AccelerationPartialWrtStateSaveSettings > accelerationPartialSettings = std::dynamic_pointer_cast< AccelerationPartialWrtStateSaveSettings >( dependentVariableSettings ); assertNonnullptrPointer( accelerationPartialSettings ); jsonObject[ K::bodyExertingAcceleration ] = accelerationPartialSettings->secondaryBody_; jsonObject[ K::componentIndices ] = accelerationPartialSettings->accelerationModelType_; jsonObject[ K::deformationType ] = accelerationPartialSettings->derivativeWrtBody_; jsonObject[ K::thirdBody ] = accelerationPartialSettings->thirdBody_; return; } default: { assignIfNotEmpty( jsonObject, K::relativeToBody, dependentVariableSettings->secondaryBody_ ); return; } } } //! Create a shared pointer to a `SingleDependentVariableSaveSettings` object from a `json` object. void from_json( const nlohmann::json& jsonObject, std::shared_ptr< SingleDependentVariableSaveSettings >& dependentVariableSettings ) { using namespace basic_astrodynamics; using namespace reference_frames; using namespace json_interface; using K = Keys::Variable; const PropagationDependentVariables dependentVariableType = getValue< PropagationDependentVariables >( jsonObject, K::dependentVariableType ); const std::string bodyName = getValue< std::string >( jsonObject, K::body ); const int componentIndex = getValue< int >( jsonObject, K::componentIndex, -1 ); switch ( dependentVariableType ) { case single_acceleration_norm_dependent_variable: case single_acceleration_dependent_variable: { dependentVariableSettings = std::make_shared< SingleAccelerationDependentVariableSaveSettings >( getValue< AvailableAcceleration >( jsonObject, K::accelerationType ), bodyName, getValue< std::string >( jsonObject, K::bodyExertingAcceleration ), dependentVariableType == single_acceleration_norm_dependent_variable, componentIndex ); return; } case spherical_harmonic_acceleration_terms_dependent_variable: { dependentVariableSettings = std::make_shared< SphericalHarmonicAccelerationTermsDependentVariableSaveSettings >( getValue< std::string >( jsonObject, K::body ), getValue< std::string >( jsonObject, K::bodyExertingAcceleration ), getValue< std::vector< std::pair< int, int > > >( jsonObject, K::componentIndices ), componentIndex ); return; } case single_torque_norm_dependent_variable: case single_torque_dependent_variable: { dependentVariableSettings = std::make_shared< SingleTorqueDependentVariableSaveSettings >( getValue< AvailableTorque >( jsonObject, K::torqueType ), bodyName, getValue< std::string >( jsonObject, K::bodyExertingTorque ), dependentVariableType == single_torque_norm_dependent_variable, componentIndex ); return; } case intermediate_aerodynamic_rotation_matrix_variable: { dependentVariableSettings = std::make_shared< IntermediateAerodynamicRotationVariableSaveSettings >( bodyName, getValue< AerodynamicsReferenceFrames >( jsonObject, K::baseFrame ), getValue< AerodynamicsReferenceFrames >( jsonObject, K::targetFrame ), componentIndex ); return; } case relative_body_aerodynamic_orientation_angle_variable: { dependentVariableSettings = std::make_shared< BodyAerodynamicAngleVariableSaveSettings >( bodyName, getValue< AerodynamicsReferenceFrameAngles >( jsonObject, K::angle ), getValue< std::string >( jsonObject, K::bodyExertingAcceleration, "" ) ); return; } case single_gravity_field_variation_acceleration: { dependentVariableSettings = std::make_shared< SingleVariationSphericalHarmonicAccelerationSaveSettings >( getValue< std::string >( jsonObject, K::body ), getValue< std::string >( jsonObject, K::bodyExertingAcceleration ), getValue< gravitation::BodyDeformationTypes >( jsonObject, K::deformationType ), getValue< std::string >( jsonObject, K::identifier, "" ) ); return; } case single_gravity_field_variation_acceleration_terms: { dependentVariableSettings = std::make_shared< SingleVariationSingleTermSphericalHarmonicAccelerationSaveSettings >( getValue< std::string >( jsonObject, K::body ), getValue< std::string >( jsonObject, K::bodyExertingAcceleration ), getValue< std::vector< std::pair< int, int > > >( jsonObject, K::componentIndices ), getValue< gravitation::BodyDeformationTypes >( jsonObject, K::deformationType ), getValue< std::string >( jsonObject, K::identifier, "" ) ); return; } case acceleration_partial_wrt_body_translational_state: { dependentVariableSettings = std::make_shared< AccelerationPartialWrtStateSaveSettings >( getValue< std::string >( jsonObject, K::body ), getValue< std::string >( jsonObject, K::bodyExertingAcceleration ), getValue< basic_astrodynamics::AvailableAcceleration >( jsonObject, K::accelerationType ), getValue< std::string >( jsonObject, K::derivativeWrtBody ), getValue< std::string >( jsonObject, K::thirdBody, "" ) ); return; } default: { dependentVariableSettings = std::make_shared< SingleDependentVariableSaveSettings >( dependentVariableType, bodyName, getValue< std::string >( jsonObject, K::relativeToBody, "" ), componentIndex ); return; } } } } // namespace propagators } // namespace tudat
{ "content_hash": "9aa100fa12af0f2b98a23e9bb77f27e3", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 135, "avg_line_length": 44.84662576687116, "alnum_prop": 0.6868673050615595, "repo_name": "DominicDirkx/tudat", "id": "d2f443170d913af4ec502c256dd4c058054dcd84", "size": "15052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tudat/JsonInterface/Propagation/variable.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8026" }, { "name": "C++", "bytes": "12614398" }, { "name": "CMake", "bytes": "185505" }, { "name": "HCL", "bytes": "30891" }, { "name": "MATLAB", "bytes": "2799" } ], "symlink_target": "" }
<?php namespace Store\ProductBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class VariantImageType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('file', null, array( 'label' => 'Fichier : ', )) //->add('variant') ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Store\ProductBundle\Entity\VariantImage' )); } /** * @return string */ public function getName() { return 'store_productbundle_variantimage'; } }
{ "content_hash": "5bd84dbd59062e05fd3c3fbf7888dffc", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 76, "avg_line_length": 23.595238095238095, "alnum_prop": 0.6094853683148335, "repo_name": "ikwattro/makeupcosmetics", "id": "182d1ff9a2271ecc3e5dffb55f8b211f5ada025f", "size": "991", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Store/ProductBundle/Form/VariantImageType.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "24490" }, { "name": "JavaScript", "bytes": "131514" }, { "name": "PHP", "bytes": "468884" }, { "name": "Ruby", "bytes": "16207" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>W30593_text</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <div style="margin-left: auto; margin-right: auto; width: 800px; overflow: hidden;"> <div style="float: left;"> <a href="page2.html">&laquo;</a> </div> <div style="float: right;"> </div> </div> <hr/> <div style="position: absolute; margin-left: 81px; margin-top: 27px;"> <p class="styleSans29.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Oil and Gas Division max/5 <br/>Lynn D. Helms - Director Bruce E. Hicks - Assistant Director <br/>Department of Mineral Resources Lynn D. Helms - Director <br/>North Dakota Industrial Commission www.dmr.nd.gov/oilgas <br/> <br/> </p> </div> <div style="position: absolute; margin-left: 136px; margin-top: 549px;"> <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">SHEILA SINGER Date: 2/2/2015 EOG RESOURCES, INC. <br/>600 17TH ST., SUITE 1000 N <br/>DENVER, CO 80202 USA <br/>RE: CORES AND SAMPLES <br/>Well Name: LIBERTY LR 29-2321H Well File No.: 30593 <br/>Location: NWSE 23-151-91 County: MOUNTRAIL Permit Type: Development - HORIZONTAL <br/>Field: PARSHALL Target Horizon: BAKKEN Dear SHEILA SINGER: <br/>North Dakota Century Code Section 38-08-04 provides for the preservation of cores and samples and their shipment to the State Geologist when requested. The following is required on the above referenced well: <br/>1) All cores, core chips and samples must be submitted to the State Geologist as provided for under North Dakota Century Code: Section 38-08-04 and North Dakota Administrative Code: Section 43-02-03-3 8.1 . </p> </div> <div style="position: absolute; margin-left: 164px; margin-top: 1594px;"> <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">2) Samples: The Operator is to begin collecting sample drill cuttings no IOWer than the: Base of the Last Charles Salt — Sample cuttings shall be collected at: </p> </div> <div style="position: absolute; margin-left: 384px; margin-top: 1759px;"> <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">o 30' maximum intervals through all vertical and build sections. 0 100’ maximum intervals through any horizontal sections. </p> </div> <div style="position: absolute; margin-left: 219px; margin-top: 1869px;"> <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">— Samples must be washed, dried, placed in standard sample envelopes (3” x 4.5”), packed in the correct order into standard sample boxes (3.5” x 5.25” x 15.25”). <br/>— Samples boxes are to be carefully identified with a label that indicates the operator, well name, well file number, American Petroleum Institute (API) number, location and depth of samples; and forwarded in to the state core and sample library within 30 days of the completion of drilling operations. </p> </div> <div style="position: absolute; margin-left: 164px; margin-top: 2199px;"> <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">3) Cores: Any cores cut shall be preserved in correct order, boxed in standard core boxes (4.5”, 4.5”, 35.75”), and the entire core forwarded to the state core and samples library within 180 days of completion of drilling operations. Any extension of time must have approval on a Form 4 Sundry Notice. </p> </div> <div style="position: absolute; margin-left: 109px; margin-top: 2419px;"> <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">All cores, core chips, and samples must be shipped, prepaid, to the state core and samples library at the following address: </p> </div> <div style="position: absolute; margin-left: 879px; margin-top: 2501px;"> <p class="styleSans10.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">ND Geological Survey Core Library 2835 Campus Road, Stop 8156 Grand Forks, ND 58202 </p> </div> <div style="position: absolute; margin-left: 109px; margin-top: 2721px;"> <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">North Dakota Century Code Section 38-08-16 allows for a civil penalty for any violation of Chapter 38 08 not to exceed $12,500 for each offense, and each day’s violation is a separate offense. </p> </div> <div style="position: absolute; margin-left: 1154px; margin-top: 2859px;"> <p class="styleSans25.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sincerely <br/>Stephen Fried <br/>Genlnoicf </p> </div> <div style="position: absolute; margin-left: 54px; margin-top: 3134px;"> <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">vvv-vo-u- <br/>600 E Boulevard Ave — Dept 405, Bismarck, North Dakota 58505—0840 Phone (701)328-8020 Fax (701)328-8022 </p> </div> </body> </html>
{ "content_hash": "932772ec0af4ca26e97ad398c437b487", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 892, "avg_line_length": 86.73015873015873, "alnum_prop": 0.7258418740849195, "repo_name": "datamade/elpc_bakken", "id": "23813d616d7e547e135efa73583dd6965f83cd6f", "size": "5499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ocr_extracted/W30593_text/page3.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17512999" }, { "name": "HTML", "bytes": "421900941" }, { "name": "Makefile", "bytes": "991" }, { "name": "Python", "bytes": "7186" } ], "symlink_target": "" }
module GroundSquadsHelper end
{ "content_hash": "8495c3556c31172482d22539dad3d437", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 25, "avg_line_length": 15, "alnum_prop": 0.9, "repo_name": "glesage/ps2_command_room", "id": "6d19893c1563cff518fcf6f1961d8f64b3e775af", "size": "30", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/helpers/ground_squads_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4759" }, { "name": "CoffeeScript", "bytes": "2954" }, { "name": "HTML", "bytes": "33974" }, { "name": "JavaScript", "bytes": "661" }, { "name": "Ruby", "bytes": "76350" } ], "symlink_target": "" }
<?php namespace Pixeloid\AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * RegistrantType * * @ORM\Table() * @ORM\Entity(repositoryClass="Pixeloid\AppBundle\Entity\RegistrantTypeRepository") */ class RegistrantType { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name=''; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return RegistrantType */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } public function __toString(){ return $this->name; } }
{ "content_hash": "f2fde56589d5af3c0dc8cc04acbd6cd5", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 84, "avg_line_length": 15.231884057971014, "alnum_prop": 0.5099904852521409, "repo_name": "pixeloid/event_microsite", "id": "d1b5be1f730e6c4d76558dea25d8ed4657d5a187", "size": "1051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Pixeloid/AppBundle/Entity/RegistrantType.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "37380013" }, { "name": "HTML", "bytes": "2868863" }, { "name": "JavaScript", "bytes": "7555943" }, { "name": "PHP", "bytes": "718370" }, { "name": "Ruby", "bytes": "2976" } ], "symlink_target": "" }
/* Script: karma.conf.js This file is part of EasyRTC. */ /*global module */ module.exports = function (config) { 'use strict'; config.set({ frameworks: ['jasmine', 'requirejs'], // base path, that will be used to resolve files and exclude basePath: '../../', // list of files / patterns to load in the browser files: [ { pattern: 'test/api/bower_components/**/*', included: false }, { pattern: 'test/api/spec/**/*', included: false }, { pattern: 'api/**/*', included: false }, // Run Karma require bootstrap 'test/api/bootstrap/karma.js' ], // list of files to exclude exclude: [], preprocessors: { 'api/**/*.js': ['coverage'] }, // use dots reporter, as travis terminal does not support escaping sequences // possible values: 'dots', 'progress' // CLI --reporters progress reporters: ['coverage', 'progress'], coverageReporter: { type: 'html', dir: 'test/reports/test-api-coverage/' }, // web server port // CLI --port 9876 port: 9876, // enable / disable colors in the output (reporters and logs) // CLI --colors --no-colors colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG // CLI --log-level debug logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes // CLI --auto-watch --no-auto-watch autoWatch: true, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) // CLI --browsers Chrome,Firefox,Safari browsers: ['Chrome_without_security'], customLaunchers: { firefoxLauncher: { base: 'Firefox', prefs: { 'security.ssl.enable_ocsp_stapling': false } }, Chrome_without_security: { base: 'Chrome', flags: [ '--ignore-certificate-errors=true', '--user-data-dir=./tmp', '--allow-insecure-localhost', '--allow-running-insecure-content', '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream' ] }, }, // If browser does not capture in given timeout [ms], kill it // CLI --capture-timeout 5000 captureTimeout: 5000, // Auto run tests on start (when browsers are captured) and exit // CLI --single-run --no-single-run singleRun: true, // report which specs are slower than 500ms // CLI --report-slower-than 500 reportSlowerThan: 500, plugins: [ 'karma-jasmine', 'karma-requirejs', 'karma-coverage', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-ie-launcher' ] }); };
{ "content_hash": "e46f5711609a9120ffc8b43884aa99b6", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 124, "avg_line_length": 27.3671875, "alnum_prop": 0.4855837853268627, "repo_name": "priologic/easyrtc", "id": "351e01f07481933ab27891c6a1bd63d741b8eba2", "size": "3503", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/api/karma.conf.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "237" }, { "name": "CSS", "bytes": "17802" }, { "name": "Dockerfile", "bytes": "1065" }, { "name": "HTML", "bytes": "2607" }, { "name": "JavaScript", "bytes": "1073771" }, { "name": "Shell", "bytes": "267" }, { "name": "TypeScript", "bytes": "12614" } ], "symlink_target": "" }
import Vue from 'vue' import Vuex from 'vuex' import * as actions from './actions' import * as getters from './getters' import state from './state' import mutations from './mutations' import createLogger from 'vuex/dist/logger' Vue.use(Vuex) const debug = process.env.NODE_ENV !== 'production' export default new Vuex.Store({ actions, getters, mutations, state, strict: debug, plugins: debug ? [createLogger()] : [] })
{ "content_hash": "5246107b1d0e70814361f8cc3a11769f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 51, "avg_line_length": 21.7, "alnum_prop": 0.7027649769585254, "repo_name": "lovewxz/vue-mingyi-admin", "id": "fc277de17b1cedb30e258639e815cd1eaf5ffe60", "size": "434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/vuex/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33" }, { "name": "HTML", "bytes": "187" }, { "name": "JavaScript", "bytes": "28670" }, { "name": "Vue", "bytes": "61159" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>elpi: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+2 / elpi - 1.2.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> elpi <small> 1.2.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-02-24 14:39:15 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-02-24 14:39:15 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-elpi&quot; maintainer: &quot;Enrico Tassi &lt;enrico.tassi@inria.fr&gt;&quot; authors: [ &quot;Enrico Tassi&quot; ] license: &quot;LGPL 2.1&quot; homepage: &quot;https://github.com/LPCIC/coq-elpi&quot; bug-reports: &quot;https://github.com/LPCIC/coq-elpi/issues&quot; dev-repo: &quot;git+https://github.com/LPCIC/coq-elpi&quot; build: [ make &quot;COQBIN=%{bin}%/&quot; &quot;ELPIDIR=%{prefix}%/lib/elpi&quot; ] install: [ make &quot;install&quot; &quot;COQBIN=%{bin}%/&quot; &quot;ELPIDIR=%{prefix}%/lib/elpi&quot; ] depends: [ &quot;elpi&quot; {&gt;= &quot;1.8.0&quot; &amp; &lt; &quot;1.9.0~&quot;} &quot;coq&quot; { (&gt;= &quot;8.10.0&quot; &amp; &lt; &quot;8.11~&quot;) | (= &quot;8.10.dev&quot;) } ] synopsis: &quot;Elpi extension language for Coq&quot; description: &quot;&quot;&quot; Coq-elpi provides a Coq plugin that embeds ELPI. It also provides a way to embed Coq&#39;s terms into λProlog using the Higher-Order Abstract Syntax approach and a way to read terms back. In addition to that it exports to ELPI a set of Coq&#39;s primitives, e.g. printing a message, accessing the environment of theorems and data types, defining a new constant and so on. For convenience it also provides a quotation and anti-quotation for Coq&#39;s syntax in λProlog. E.g. `{{nat}}` is expanded to the type name of natural numbers, or `{{A -&gt; B}}` to the representation of a product by unfolding the `-&gt;` notation. Finally it provides a way to define new vernacular commands and new tactics.&quot;&quot;&quot; url { src: &quot;https://github.com/LPCIC/coq-elpi/archive/v1.2.0.tar.gz&quot; checksum: &quot;sha256=58aef9596e6ad74d9f230abc34171dafaa39da93a4f1bf6f07f69904360c2c9c&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-elpi.1.2.0 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2). The following dependencies couldn&#39;t be met: - coq-elpi -&gt; coq = 8.10.dev no matching version Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-elpi.1.2.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "5b57d7c0e1d914ee92708849551d7cf4", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 159, "avg_line_length": 43.05747126436781, "alnum_prop": 0.552989855846236, "repo_name": "coq-bench/coq-bench.github.io", "id": "25bb270e35a8b56f3f078012fa61bd3639b6c05d", "size": "7519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.7.1+2/elpi/1.2.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package de.dentrassi.kura.addons.drools.component.wires; import static org.osgi.service.component.annotations.ConfigurationPolicy.REQUIRE; import java.util.Map; import org.eclipse.kura.configuration.ConfigurableComponent; import org.eclipse.kura.wire.WireComponent; import org.eclipse.kura.wire.WireEmitter; import org.eclipse.kura.wire.WireHelperService; import org.kie.api.runtime.KieSession; import org.osgi.framework.ServiceReference; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.wireadmin.Producer; import de.dentrassi.kura.addons.drools.Configuration; import de.dentrassi.kura.addons.drools.component.wires.internal.DroolsWirePublisherImpl; @Component(enabled = true, configurationPolicy = REQUIRE, service = { ConfigurableComponent.class, WireComponent.class, WireEmitter.class, Producer.class }, property = { "service.pid=de.dentrassi.kura.addons.drools.component.wires.DroolsListen" }) public class DroolsListen extends AbstractDroolsWireComponent implements WireEmitter { private String globalName; private KieSession session; @Override @Reference public void setWireHelperService(final WireHelperService wireHelperService) { super.setWireHelperService(wireHelperService); } @Override @Activate protected void activate(final Map<String, ?> properties) throws Exception { this.globalName = Configuration.asString(properties, "global.name"); if (this.globalName == null || this.globalName.isEmpty()) { return; } super.activate(properties); } @Override @Deactivate protected void deactivate() { super.deactivate(); } @Override @Modified protected void modified(final Map<String, ?> properties) throws Exception { super.modified(properties); } @Override protected void setKieSession(final ServiceReference<KieSession> serviceReference, final KieSession session) { if (this.session == session) { return; } if (this.session != null) { // remove from old session this.session.setGlobal(this.globalName, null); } // set new session this.session = session; if (this.session != null) { // add to new session this.session.setGlobal(this.globalName, createPublisher()); } } private DroolsWirePublisher createPublisher() { return new DroolsWirePublisherImpl(this.wireSupport); } }
{ "content_hash": "1142c481c6a2a777d62f0b0fd3de4143", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 119, "avg_line_length": 31.568181818181817, "alnum_prop": 0.7159827213822895, "repo_name": "ctron/kura-addons", "id": "6f34216f554a37089e0e245ca8b3074fcbf36e3f", "size": "3395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "drools/de.dentrassi.kura.addons.drools.component/src/main/java/de/dentrassi/kura/addons/drools/component/wires/DroolsListen.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "130777" } ], "symlink_target": "" }
using System.Web.Services.Configuration; using System.Xml.Serialization; namespace System.Web.Services.Description { [XmlFormatExtension ("address", "http://schemas.xmlsoap.org/wsdl/http/", typeof (Port))] public sealed class HttpAddressBinding : ServiceDescriptionFormatExtension { #region Fields string location; #endregion // Fields #region Constructors public HttpAddressBinding () { location = String.Empty; } #endregion // Constructors #region Properties [XmlAttribute ("location")] public string Location { get { return location; } set { location = value; } } #endregion // Properties } }
{ "content_hash": "d499acd6f52a969e85274f2b7a28f528", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 89, "avg_line_length": 20.205882352941178, "alnum_prop": 0.6724890829694323, "repo_name": "jjenki11/blaze-chem-rendering", "id": "bf120fb04c01d73b010c8b4ecab79a138aa3c24e", "size": "1933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qca_designer/lib/ml-pnet-0.8.1/mcs-sources/class/System.Web.Services/System.Web.Services.Description/HttpAddressBinding.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "2476" } ], "symlink_target": "" }
module PrintNode # An error class for HTTP errors # @author Jake Torrance # @author PrintNode class APIError < StandardError attr_reader :object # Initializes an object or message to use in the error. # == Paramters: # object:: # object to show error messages about. def initialize(object) @object = object end end end
{ "content_hash": "b31dc53773a40a72da454a08ca448591", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 59, "avg_line_length": 22.75, "alnum_prop": 0.6675824175824175, "repo_name": "PrintNode/PrintNode-Ruby", "id": "8cef634bde8e736c7eeaaa620bd5e03e388412ae", "size": "364", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/printnode/api_exception.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "28323" }, { "name": "Shell", "bytes": "233" } ], "symlink_target": "" }
// This file is automatically generated. package adila.db; /* * ZTE * * DEVICE: roundtop * MODEL: ZTE V9800 */ final class roundtop_zte20v9800 { public static final String DATA = "ZTE||"; }
{ "content_hash": "98a0ba96a7cb5e45a95784ae90479c4d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 46, "avg_line_length": 15.538461538461538, "alnum_prop": 0.6633663366336634, "repo_name": "karim/adila", "id": "9ed3b556ae13d7ad52f67829d259857689173978", "size": "202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/src/main/java/adila/db/roundtop_zte20v9800.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2903103" }, { "name": "Prolog", "bytes": "489" }, { "name": "Python", "bytes": "3280" } ], "symlink_target": "" }
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cv_server_provision version_added: "2.4" author: "EOS+ CS (ansible-dev@arista.com) (@mharista)" short_description: Provision server port by applying or removing template configuration to an Arista CloudVision Portal configlet that is applied to a switch. description: - This module allows a server team to provision server network ports for new servers without having to access Arista CVP or asking the network team to do it for them. Provide the information for connecting to CVP, switch rack, port the new server is connected to, optional vlan, and an action and the module will apply the configuration to the switch port via CVP. Actions are add (applies template config to port), remove (defaults the interface config) and show (returns the current port config). options: host: description: - The hostname or IP address of the CVP node being connected to. required: true port: description: - The port number to use when making API calls to the CVP node. This will default to the default port for the specified protocol. Port 80 for http and port 443 for https. protocol: description: - The protocol to use when making API calls to CVP. CVP defaults to https and newer versions of CVP no longer support http. default: https choices: [https, http] username: description: - The user that will be used to connect to CVP for making API calls. required: true password: description: - The password of the user that will be used to connect to CVP for API calls. required: true server_name: description: - The hostname or identifier for the server that is having it's switch port provisioned. required: true switch_name: description: - The hostname of the switch is being configured for the server being provisioned. required: true switch_port: description: - The physical port number on the switch that the new server is connected to. required: true port_vlan: description: - The vlan that should be applied to the port for this server. This parameter is dependent on a proper template that supports single vlan provisioning with it. If a port vlan is specified by the template specified does not support this the module will exit out with no changes. If a template is specified that requires a port vlan but no port vlan is specified the module will exit out with no changes. template: description: - A path to a Jinja formatted template file that contains the configuration block that will be applied to the specified switch port. This template will have variable fields replaced by the module before being applied to the switch configuration. required: true action: description: - The action for the module to take. The actions are add, which applies the specified template config to port, remove, which defaults the specified interface configuration, and show, which will return the current port configuration with no changes. default: show choices: [show, add, remove] auto_run: description: - Flag that determines whether or not the module will execute the CVP task spawned as a result of changes to a switch configlet. When an add or remove action is taken which results in a change to a switch configlet, CVP will spawn a task that needs to be executed for the configuration to be applied to the switch. If this option is True then the module will determined the task number created by the configuration change, execute it and wait for the task to complete. If the option is False then the task will remain in the Pending state in CVP for a network administrator to review and execute. type: bool default: 'no' requirements: [Jinja2, cvprac >= 0.7.0] ''' EXAMPLES = ''' - name: Get current configuration for interface Ethernet2 cv_server_provision: host: cvp_node username: cvp_user password: cvp_pass protocol: https server_name: new_server switch_name: eos_switch_1 switch_port: 2 template: template_file.j2 action: show - name: Remove existing configuration from interface Ethernet2. Run task. cv_server_provision: host: cvp_node username: cvp_user password: cvp_pass protocol: https server_name: new_server switch_name: eos_switch_1 switch_port: 2 template: template_file.j2 action: remove auto_run: True - name: Add template configuration to interface Ethernet2. No VLAN. Run task. cv_server_provision: host: cvp_node username: cvp_user password: cvp_pass protocol: https server_name: new_server switch_name: eos_switch_1 switch_port: 2 template: single_attached_trunk.j2 action: add auto_run: True - name: Add template with VLAN configuration to interface Ethernet2. Run task. cv_server_provision: host: cvp_node username: cvp_user password: cvp_pass protocol: https server_name: new_server switch_name: eos_switch_1 switch_port: 2 port_vlan: 22 template: single_attached_vlan.j2 action: add auto_run: True ''' RETURN = ''' changed: description: Signifies if a change was made to the configlet returned: success type: bool sample: true currentConfigBlock: description: The current config block for the user specified interface returned: when action = show type: str sample: | interface Ethernet4 ! newConfigBlock: description: The new config block for the user specified interface returned: when action = add or remove type: str sample: | interface Ethernet3 description example no switchport ! oldConfigBlock: description: The current config block for the user specified interface before any changes are made returned: when action = add or remove type: str sample: | interface Ethernet3 ! fullConfig: description: The full config of the configlet after being updated returned: when action = add or remove type: str sample: | ! interface Ethernet3 ! interface Ethernet4 ! updateConfigletResponse: description: Response returned from CVP when configlet update is triggered returned: when action = add or remove and configuration changes type: str sample: "Configlet veos1-server successfully updated and task initiated." portConfigurable: description: Signifies if the user specified port has an entry in the configlet that Ansible has access to returned: success type: bool sample: true switchConfigurable: description: Signifies if the user specified switch has a configlet applied to it that CVP is allowed to edit returned: success type: bool sample: true switchInfo: description: Information from CVP describing the switch being configured returned: success type: dict sample: {"architecture": "i386", "bootupTimeStamp": 1491264298.21, "complianceCode": "0000", "complianceIndication": "NONE", "deviceInfo": "Registered", "deviceStatus": "Registered", "fqdn": "veos1", "hardwareRevision": "", "internalBuildId": "12-12", "internalVersion": "4.17.1F-11111.4171F", "ipAddress": "192.168.1.20", "isDANZEnabled": "no", "isMLAGEnabled": "no", "key": "00:50:56:5d:e5:e0", "lastSyncUp": 1496432895799, "memFree": 472976, "memTotal": 1893460, "modelName": "vEOS", "parentContainerId": "container_13_5776759195930", "serialNumber": "", "systemMacAddress": "00:50:56:5d:e5:e0", "taskIdList": [], "tempAction": null, "type": "netelement", "unAuthorized": false, "version": "4.17.1F", "ztpMode": "false"} taskCompleted: description: Signifies if the task created and executed has completed successfully returned: when action = add or remove, and auto_run = true, and configuration changes type: bool sample: true taskCreated: description: Signifies if a task was created due to configlet changes returned: when action = add or remove, and auto_run = true or false, and configuration changes type: bool sample: true taskExecuted: description: Signifies if the automation executed the spawned task returned: when action = add or remove, and auto_run = true, and configuration changes type: bool sample: true taskId: description: The task ID created by CVP because of changes to configlet returned: when action = add or remove, and auto_run = true or false, and configuration changes type: str sample: "500" ''' import re import time from ansible.module_utils.basic import AnsibleModule try: import jinja2 from jinja2 import meta HAS_JINJA2 = True except ImportError: HAS_JINJA2 = False try: from cvprac.cvp_client import CvpClient from cvprac.cvp_client_errors import CvpLoginError, CvpApiError HAS_CVPRAC = True except ImportError: HAS_CVPRAC = False def connect(module): ''' Connects to CVP device using user provided credentials from playbook. :param module: Ansible module with parameters and client connection. :return: CvpClient object with connection instantiated. ''' client = CvpClient() try: client.connect([module.params['host']], module.params['username'], module.params['password'], protocol=module.params['protocol'], port=module.params['port']) except CvpLoginError as e: module.fail_json(msg=str(e)) return client def switch_info(module): ''' Get dictionary of switch info from CVP. :param module: Ansible module with parameters and client connection. :return: Dict of switch info from CVP or exit with failure if no info for device is found. ''' switch_name = module.params['switch_name'] switch_info = module.client.api.get_device_by_name(switch_name) if not switch_info: module.fail_json(msg=str("Device with name '%s' does not exist." % switch_name)) return switch_info def switch_in_compliance(module, sw_info): ''' Check if switch is currently in compliance. :param module: Ansible module with parameters and client connection. :param sw_info: Dict of switch info. :return: Nothing or exit with failure if device is not in compliance. ''' compliance = module.client.api.check_compliance(sw_info['key'], sw_info['type']) if compliance['complianceCode'] != '0000': module.fail_json(msg=str('Switch %s is not in compliance. Returned' ' compliance code %s.' % (sw_info['fqdn'], compliance['complianceCode']))) def server_configurable_configlet(module, sw_info): ''' Check CVP that the user specified switch has a configlet assigned to it that Ansible is allowed to edit. :param module: Ansible module with parameters and client connection. :param sw_info: Dict of switch info. :return: Dict of configlet information or None. ''' configurable_configlet = None configlet_name = module.params['switch_name'] + '-server' switch_configlets = module.client.api.get_configlets_by_device_id( sw_info['key']) for configlet in switch_configlets: if configlet['name'] == configlet_name: configurable_configlet = configlet return configurable_configlet def port_configurable(module, configlet): ''' Check configlet if the user specified port has a configuration entry in the configlet to determine if Ansible is allowed to configure the port on this switch. :param module: Ansible module with parameters and client connection. :param configlet: Dict of configlet info. :return: True or False. ''' configurable = False regex = r'^interface Ethernet%s' % module.params['switch_port'] for config_line in configlet['config'].split('\n'): if re.match(regex, config_line): configurable = True return configurable def configlet_action(module, configlet): ''' Take appropriate action based on current state of device and user requested action. Return current config block for specified port if action is show. If action is add or remove make the appropriate changes to the configlet and return the associated information. :param module: Ansible module with parameters and client connection. :param configlet: Dict of configlet info. :return: Dict of information to updated results with. ''' result = dict() existing_config = current_config(module, configlet['config']) if module.params['action'] == 'show': result['currentConfigBlock'] = existing_config return result elif module.params['action'] == 'add': result['newConfigBlock'] = config_from_template(module) elif module.params['action'] == 'remove': result['newConfigBlock'] = ('interface Ethernet%s\n!' % module.params['switch_port']) result['oldConfigBlock'] = existing_config result['fullConfig'] = updated_configlet_content(module, configlet['config'], result['newConfigBlock']) resp = module.client.api.update_configlet(result['fullConfig'], configlet['key'], configlet['name']) if 'data' in resp: result['updateConfigletResponse'] = resp['data'] if 'task' in resp['data']: result['changed'] = True result['taskCreated'] = True return result def current_config(module, config): ''' Parse the full port configuration for the user specified port out of the full configlet configuration and return as a string. :param module: Ansible module with parameters and client connection. :param config: Full config to parse specific port config from. :return: String of current config block for user specified port. ''' regex = r'^interface Ethernet%s' % module.params['switch_port'] match = re.search(regex, config, re.M) if not match: module.fail_json(msg=str('interface section not found - %s' % config)) block_start, line_end = match.regs[0] match = re.search(r'!', config[line_end:], re.M) if not match: return config[block_start:] _, block_end = match.regs[0] block_end = line_end + block_end return config[block_start:block_end] def valid_template(port, template): ''' Test if the user provided Jinja template is valid. :param port: User specified port. :param template: Contents of Jinja template. :return: True or False ''' valid = True regex = r'^interface Ethernet%s' % port match = re.match(regex, template, re.M) if not match: valid = False return valid def config_from_template(module): ''' Load the Jinja template and apply user provided parameters in necessary places. Fail if template is not found. Fail if rendered template does not reference the correct port. Fail if the template requires a VLAN but the user did not provide one with the port_vlan parameter. :param module: Ansible module with parameters and client connection. :return: String of Jinja template rendered with parameters or exit with failure. ''' template_loader = jinja2.FileSystemLoader('./templates') env = jinja2.Environment(loader=template_loader, undefined=jinja2.DebugUndefined) template = env.get_template(module.params['template']) if not template: module.fail_json(msg=str('Could not find template - %s' % module.params['template'])) data = {'switch_port': module.params['switch_port'], 'server_name': module.params['server_name']} temp_source = env.loader.get_source(env, module.params['template'])[0] parsed_content = env.parse(temp_source) temp_vars = list(meta.find_undeclared_variables(parsed_content)) if 'port_vlan' in temp_vars: if module.params['port_vlan']: data['port_vlan'] = module.params['port_vlan'] else: module.fail_json(msg=str('Template %s requires a vlan. Please' ' re-run with vlan number provided.' % module.params['template'])) template = template.render(data) if not valid_template(module.params['switch_port'], template): module.fail_json(msg=str('Template content does not configure proper' ' interface - %s' % template)) return template def updated_configlet_content(module, existing_config, new_config): ''' Update the configlet configuration with the new section for the port specified by the user. :param module: Ansible module with parameters and client connection. :param existing_config: String of current configlet configuration. :param new_config: String of configuration for user specified port to replace in the existing config. :return: String of the full updated configuration. ''' regex = r'^interface Ethernet%s' % module.params['switch_port'] match = re.search(regex, existing_config, re.M) if not match: module.fail_json(msg=str('interface section not found - %s' % existing_config)) block_start, line_end = match.regs[0] updated_config = existing_config[:block_start] + new_config match = re.search(r'!\n', existing_config[line_end:], re.M) if match: _, block_end = match.regs[0] block_end = line_end + block_end updated_config += '\n%s' % existing_config[block_end:] return updated_config def configlet_update_task(module): ''' Poll device info of switch from CVP up to three times to see if the configlet updates have spawned a task. It sometimes takes a second for the task to be spawned after configlet updates. If a task is found return the task ID. Otherwise return None. :param module: Ansible module with parameters and client connection. :return: Task ID or None. ''' for num in range(3): device_info = switch_info(module) if (('taskIdList' in device_info) and (len(device_info['taskIdList']) > 0)): for task in device_info['taskIdList']: if ('Configlet Assign' in task['description'] and task['data']['WORKFLOW_ACTION'] == 'Configlet Push'): return task['workOrderId'] time.sleep(1) return None def wait_for_task_completion(module, task): ''' Poll CVP for the executed task to complete. There is currently no timeout. Exits with failure if task status is Failed or Cancelled. :param module: Ansible module with parameters and client connection. :param task: Task ID to poll for completion. :return: True or exit with failure if task is cancelled or fails. ''' task_complete = False while not task_complete: task_info = module.client.api.get_task_by_id(task) task_status = task_info['workOrderUserDefinedStatus'] if task_status == 'Completed': return True elif task_status in ['Failed', 'Cancelled']: module.fail_json(msg=str('Task %s has reported status %s. Please' ' consult the CVP admins for more' ' information.' % (task, task_status))) time.sleep(2) def main(): """ main entry point for module execution """ argument_spec = dict( host=dict(required=True), port=dict(required=False, default=None), protocol=dict(default='https', choices=['http', 'https']), username=dict(required=True), password=dict(required=True, no_log=True), server_name=dict(required=True), switch_name=dict(required=True), switch_port=dict(required=True), port_vlan=dict(required=False, default=None), template=dict(require=True), action=dict(default='show', choices=['show', 'add', 'remove']), auto_run=dict(type='bool', default=False)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_JINJA2: module.fail_json(msg='The Jinja2 python module is required.') if not HAS_CVPRAC: module.fail_json(msg='The cvprac python module is required.') result = dict(changed=False) module.client = connect(module) try: result['switchInfo'] = switch_info(module) if module.params['action'] in ['add', 'remove']: switch_in_compliance(module, result['switchInfo']) switch_configlet = server_configurable_configlet(module, result['switchInfo']) if not switch_configlet: module.fail_json(msg=str('Switch %s has no configurable server' ' ports.' % module.params['switch_name'])) result['switchConfigurable'] = True if not port_configurable(module, switch_configlet): module.fail_json(msg=str('Port %s is not configurable as a server' ' port on switch %s.' % (module.params['switch_port'], module.params['switch_name']))) result['portConfigurable'] = True result['taskCreated'] = False result['taskExecuted'] = False result['taskCompleted'] = False result.update(configlet_action(module, switch_configlet)) if module.params['auto_run'] and module.params['action'] != 'show': task_id = configlet_update_task(module) if task_id: result['taskId'] = task_id note = ('Update config on %s with %s action from Ansible.' % (module.params['switch_name'], module.params['action'])) module.client.api.add_note_to_task(task_id, note) module.client.api.execute_task(task_id) result['taskExecuted'] = True task_completed = wait_for_task_completion(module, task_id) if task_completed: result['taskCompleted'] = True else: result['taskCreated'] = False except CvpApiError as e: module.fail_json(msg=str(e)) module.exit_json(**result) if __name__ == '__main__': main()
{ "content_hash": "cf80f6045e87246cb5fc174a6da1dd48", "timestamp": "", "source": "github", "line_count": 626, "max_line_length": 84, "avg_line_length": 37.801916932907346, "alnum_prop": 0.6374661933739013, "repo_name": "SergeyCherepanov/ansible", "id": "925ebba35fb314aa26f2b282078add355626a408", "size": "24337", "binary": false, "copies": "51", "ref": "refs/heads/master", "path": "ansible/ansible/modules/network/cloudvision/cv_server_provision.py", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "824" } ], "symlink_target": "" }
<div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h2 style="margin-top: 0;">Details</h2> <h4>Here you can see details for <b>{{friend?.firstName}} {{friend?.lastName}}</b></h4> <img id="avatar" style="height: 10%; width: 10%;display:block; margin-top: 15px; margin-bottom: 15px;" [src]="friend?.character?.picture" > </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <div class="panel panel-default"> <div class="panel-heading"> <h2 style="margin-top: 0;">Achievements</h2> <h4>Here you can see achievements for <b>{{friend?.firstName}} {{friend?.lastName}}</b></h4> </div> <br> <br> <div class="panel-body"> <div class="row"> <div class="col-md-3" *ngFor="let achievement of achievements"> <div class="panel panel-default" style="text-align: center"> <div class="panel-heading"> <img [id]="'image'" [name]="'image'" [src]="achievement.picture" class="img-responsive"> </div> <div class="panel-body" style="margin-top: 10px;"> <b>{{achievement.name}}</b> <div><small>{{achievement.description}}</small></div> </div> </div> </div> </div> </div> </div> </div> </div> <style> #image{ display: block; margin-left: auto; margin-right: auto; border-radius: 15px; width: 200px; height: 130px; } </style>
{ "content_hash": "302929b9af3a673295a876dd26c87f1c", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 155, "avg_line_length": 35.67307692307692, "alnum_prop": 0.45498652291105124, "repo_name": "cristirosu/rpg-scheduler-front", "id": "235d05ff5f923ebbac2cdd05cf465b0bd3953d50", "size": "1855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/pages/friends-details/friend.details.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "120636" }, { "name": "HTML", "bytes": "98007" }, { "name": "JavaScript", "bytes": "35594" }, { "name": "Shell", "bytes": "153" }, { "name": "TypeScript", "bytes": "258721" } ], "symlink_target": "" }
Sass is a ‘pre-processing’ language. This means that the Sass documents cannot consumed by the browser, but need to be processed into another language that can. Sass is processed into CSS, similar to the way that CoffeeScript is processed into JavaScript. The following SCSS files form the styling workflow: ``` style.css: ``` Do not worry about this file, it's required by WordPress. All styling are handled in the Sass files described below. ``` assets/scss/foundation.scss: ``` Imports for Foundation components and your custom styles. ``` assets/scss/config/_settings.scss: ``` Original Foundation 5 base settings. ``` assets/scss/config/_custom-settings.scss: ``` Copy the settings you will modify to this file. Make it your own. ``` assets/scss/site/*.scss: ``` Unleash your creativity. Create the files you need (and remember to make import statements for all your files in assets/scss/foundation.scss)
{ "content_hash": "ad597e8af6667a647eea2ac247059900", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 255, "avg_line_length": 27.87878787878788, "alnum_prop": 0.7630434782608696, "repo_name": "msuexponent/msuexponent.github.io", "id": "7d67fc874587b914855509124914ecf71141e5ba", "size": "934", "binary": false, "copies": "1", "ref": "refs/heads/source", "path": "docs/04_Theme/04_SASS.md", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "137" }, { "name": "CSS", "bytes": "92757" }, { "name": "HTML", "bytes": "249096" }, { "name": "JavaScript", "bytes": "26710" }, { "name": "PHP", "bytes": "179572" }, { "name": "Shell", "bytes": "51" } ], "symlink_target": "" }
package org.apache.spark.kafka010 import java.{util => ju} import javax.security.auth.login.{AppConfigurationEntry, Configuration} import org.apache.hadoop.io.Text import org.apache.hadoop.security.{Credentials, UserGroupInformation} import org.apache.hadoop.security.token.Token import org.mockito.Mockito.mock import org.scalatest.BeforeAndAfterEach import org.apache.spark.{SparkConf, SparkEnv, SparkFunSuite} import org.apache.spark.kafka010.KafkaTokenUtil.KafkaDelegationTokenIdentifier /** * This is a trait which provides functionalities for Kafka delegation token related test suites. */ trait KafkaDelegationTokenTest extends BeforeAndAfterEach { self: SparkFunSuite => private def doReturn(value: Any) = org.mockito.Mockito.doReturn(value, Seq.empty: _*) protected val tokenId = "tokenId" + ju.UUID.randomUUID().toString protected val tokenPassword = "tokenPassword" + ju.UUID.randomUUID().toString private class KafkaJaasConfiguration extends Configuration { val entry = new AppConfigurationEntry( "DummyModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, ju.Collections.emptyMap[String, Object]() ) override def getAppConfigurationEntry(name: String): Array[AppConfigurationEntry] = { if (name.equals("KafkaClient")) { Array(entry) } else { null } } } override def afterEach(): Unit = { try { Configuration.setConfiguration(null) UserGroupInformation.setLoginUser(null) SparkEnv.set(null) } finally { super.afterEach() } } protected def setGlobalKafkaClientConfig(): Unit = { Configuration.setConfiguration(new KafkaJaasConfiguration) } protected def addTokenToUGI(tokenService: Text): Unit = { val token = new Token[KafkaDelegationTokenIdentifier]( tokenId.getBytes, tokenPassword.getBytes, KafkaTokenUtil.TOKEN_KIND, tokenService ) val creds = new Credentials() creds.addToken(token.getService, token) UserGroupInformation.getCurrentUser.addCredentials(creds) } protected def setSparkEnv(settings: Iterable[(String, String)]): Unit = { val conf = new SparkConf().setAll(settings) val env = mock(classOf[SparkEnv]) doReturn(conf).when(env).conf SparkEnv.set(env) } }
{ "content_hash": "bcda56873a8742435831a644a1ff7e37", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 97, "avg_line_length": 30.103896103896105, "alnum_prop": 0.727351164797239, "repo_name": "LantaoJin/spark", "id": "2675085bb2cbc464b1f4fb56b77214bbd4059e82", "size": "3118", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "external/kafka-0-10-token-provider/src/test/scala/org/apache/spark/kafka010/KafkaDelegationTokenTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "42949" }, { "name": "Batchfile", "bytes": "31085" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "26884" }, { "name": "Dockerfile", "bytes": "8823" }, { "name": "HTML", "bytes": "70460" }, { "name": "HiveQL", "bytes": "1823426" }, { "name": "Java", "bytes": "3989445" }, { "name": "JavaScript", "bytes": "199308" }, { "name": "Makefile", "bytes": "9397" }, { "name": "PLpgSQL", "bytes": "192725" }, { "name": "PowerShell", "bytes": "3867" }, { "name": "Python", "bytes": "2901816" }, { "name": "R", "bytes": "1184970" }, { "name": "Roff", "bytes": "15662" }, { "name": "SQLPL", "bytes": "3603" }, { "name": "Scala", "bytes": "29164087" }, { "name": "Shell", "bytes": "201183" }, { "name": "Thrift", "bytes": "65194" }, { "name": "q", "bytes": "146878" } ], "symlink_target": "" }
.class public Lcom/htc/painting/penmenu15/transition/AnimationTransitioner; .super Ljava/lang/Object; .source "AnimationTransitioner.java" # interfaces .implements Lcom/htc/painting/penmenu15/transition/ViewTransitioner; # instance fields .field private mInAnimation:Landroid/view/animation/Animation; .field private mOutAnimation:Landroid/view/animation/Animation; .field private mTargetView:Landroid/view/View; # direct methods .method public constructor <init>(Landroid/view/View;Landroid/view/animation/Animation;Landroid/view/animation/Animation;)V .locals 1 .parameter "target" .parameter "in" .parameter "out" .prologue .line 18 invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V .line 16 const/4 v0, 0x0 iput-object v0, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mTargetView:Landroid/view/View; .line 19 iput-object p2, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mInAnimation:Landroid/view/animation/Animation; .line 20 iput-object p3, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mOutAnimation:Landroid/view/animation/Animation; .line 21 iput-object p1, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mTargetView:Landroid/view/View; .line 22 return-void .end method # virtual methods .method public startTransition(I)V .locals 2 .parameter "type" .prologue .line 32 const/4 v0, 0x0 .line 33 .local v0, animation:Landroid/view/animation/Animation; const/16 v1, 0x258 if-ne p1, v1, :cond_2 .line 34 iget-object v0, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mInAnimation:Landroid/view/animation/Animation; .line 39 :cond_0 :goto_0 if-eqz v0, :cond_1 .line 40 iget-object v1, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mTargetView:Landroid/view/View; invoke-virtual {v1, v0}, Landroid/view/View;->setAnimation(Landroid/view/animation/Animation;)V .line 41 invoke-virtual {v0}, Landroid/view/animation/Animation;->reset()V .line 42 invoke-virtual {v0}, Landroid/view/animation/Animation;->start()V .line 44 :cond_1 return-void .line 35 :cond_2 const/16 v1, 0x259 if-ne p1, v1, :cond_0 .line 36 iget-object v0, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mOutAnimation:Landroid/view/animation/Animation; goto :goto_0 .end method .method public stopTransition(I)V .locals 2 .parameter "type" .prologue .line 52 const/4 v0, 0x0 .line 53 .local v0, animation:Landroid/view/animation/Animation; const/16 v1, 0x258 if-ne p1, v1, :cond_2 .line 54 iget-object v0, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mInAnimation:Landroid/view/animation/Animation; .line 59 :cond_0 :goto_0 if-eqz v0, :cond_1 .line 60 iget-object v1, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mTargetView:Landroid/view/View; invoke-virtual {v1, v0}, Landroid/view/View;->setAnimation(Landroid/view/animation/Animation;)V .line 61 invoke-virtual {v0}, Landroid/view/animation/Animation;->cancel()V .line 62 invoke-virtual {v0}, Landroid/view/animation/Animation;->reset()V .line 66 :cond_1 return-void .line 55 :cond_2 const/16 v1, 0x259 if-ne p1, v1, :cond_0 .line 56 iget-object v0, p0, Lcom/htc/painting/penmenu15/transition/AnimationTransitioner;->mOutAnimation:Landroid/view/animation/Animation; goto :goto_0 .end method
{ "content_hash": "4fad2a5049a9f02af330d972ad8cb25b", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 135, "avg_line_length": 25.618055555555557, "alnum_prop": 0.7115749525616698, "repo_name": "baidurom/devices-onex", "id": "63cc507d77c417a62b87064013791c1f5344c54d", "size": "3689", "binary": false, "copies": "1", "ref": "refs/heads/coron-4.0", "path": "HTCExtension.jar.out/smali/com/htc/painting/penmenu15/transition/AnimationTransitioner.smali", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use strict'; const BaseElement = require('./baseElement'); const delay = require('delay'); module.exports = Dice; function Dice() { BaseElement.call(this, 'dice_v1'); let value = 6; let canBeRolledByPlayerIndexes = []; this.onAfterRoll = null; this.roll = async function() { value = Math.floor(Math.random() * 6) + 1; this.sendEvent('dice.rolled', {value: value}); this.GameBase.Elements.clearPermissions(); await delay(2000); return value; }; this.toArray = function() { return { value: value, canBeRolledBy: canBeRolledByPlayerIndexes }; }; this.canBeRolledBy = function(playerIndexes) { if (typeof playerIndexes === 'number') { playerIndexes = [playerIndexes]; } canBeRolledByPlayerIndexes = playerIndexes; this.sendEvent('dice.permissionChanged', {canBeRolledBy: canBeRolledByPlayerIndexes}); }; this.clearPermissions = function() { if (canBeRolledByPlayerIndexes.length) { this.canBeRolledBy([]); } }; this.getValue = function() { return value; }; this.on('dice.roll', async slotIndex => { let value = this.roll(); if (typeof this.onAfterRoll === 'function') { await this.onAfterRoll.call(this, slotIndex, value); } }); } Dice.prototype = Object.create(BaseElement.prototype); Dice.prototype.constructor = Dice;
{ "content_hash": "2de9bf5b382cf92b3b3c6201e671b5af", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 94, "avg_line_length": 23.714285714285715, "alnum_prop": 0.5983935742971888, "repo_name": "byWulf/gcs-game-base-nodejs", "id": "92807391d749e331bb80c955e9f975abab8df3ac", "size": "1494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/elements/dice.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "43163" } ], "symlink_target": "" }
// <copyright file="ClickAndHoldAction.cs" company="WebDriver Committers"> // Copyright 2007-2011 WebDriver committers // Copyright 2007-2011 Google Inc. // Portions copyright 2011 Software Freedom Conservancy // // 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. // </copyright> using System; using System.Collections.Generic; using System.Text; using OpenQA.Selenium.Interactions.Internal; namespace OpenQA.Selenium.Interactions { /// <summary> /// Defines an action for clicking and holding the mouse button on an element. /// </summary> internal class ClickAndHoldAction : MouseAction, IAction { /// <summary> /// Initializes a new instance of the <see cref="ClickAndHoldAction"/> class. /// </summary> /// <param name="mouse">The <see cref="IMouse"/> with which the action will be performed.</param> /// <param name="actionTarget">An <see cref="ILocatable"/> describing an element at which to perform the action.</param> public ClickAndHoldAction(IMouse mouse, ILocatable actionTarget) : base(mouse, actionTarget) { } #region IAction Members /// <summary> /// Performs this action. /// </summary> public void Perform() { this.MoveToLocation(); this.Mouse.MouseDown(this.ActionLocation); } #endregion } }
{ "content_hash": "bc97744d74ce1c987bd617205cbc464d", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 128, "avg_line_length": 36.9622641509434, "alnum_prop": 0.6559469116896376, "repo_name": "jmt4/Selenium2", "id": "3a2ec1af701ca011c933b41b0dbaf2886554da09", "size": "1961", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "dotnet/src/WebDriver/Interactions/ClickAndHoldAction.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "2614" }, { "name": "Batchfile", "bytes": "148" }, { "name": "C", "bytes": "53732" }, { "name": "C#", "bytes": "2203951" }, { "name": "C++", "bytes": "1475325" }, { "name": "CSS", "bytes": "23536" }, { "name": "HTML", "bytes": "1968975" }, { "name": "Java", "bytes": "7955540" }, { "name": "JavaScript", "bytes": "4031532" }, { "name": "Makefile", "bytes": "4655" }, { "name": "Objective-C", "bytes": "320336" }, { "name": "Objective-C++", "bytes": "21844" }, { "name": "Python", "bytes": "629542" }, { "name": "Ragel in Ruby Host", "bytes": "3086" }, { "name": "Ruby", "bytes": "768787" }, { "name": "Shell", "bytes": "6395" }, { "name": "XSLT", "bytes": "1083" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.4.5 / contrib:smc dev</a></li> <li class="active"><a href="">2015-01-07 21:12:13</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:smc <small> dev <span class="label label-info">Not compatible with this Coq</span> </small> </h1> <p><em><script>document.write(moment("2015-01-07 21:12:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-01-07 21:12:13 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:smc/coq:contrib:smc.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>The package is valid. </pre></dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:smc.dev coq.8.4.5</code></dd> <dt>Return code</dt> <dd>768</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.4.5). The following dependencies couldn&#39;t be met: - coq:contrib:smc -&gt; coq &gt;= dev Your request can&#39;t be satisfied: - Conflicting version constraints for coq No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --dry-run coq:contrib:smc.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>4 s</dd> <dt>Output</dt> <dd><pre>The following actions will be performed: - remove coq.8.4.5 === 1 to remove === =-=- Removing Packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Removing coq.8.4.5. [WARNING] Directory /home/bench/.opam/system/lib/coq is not empty, not removing [WARNING] Directory /home/bench/.opam/system/share/coq is not empty, not removing The following actions will be performed: - install coq.hott [required by coq:contrib:smc] - install coq:contrib:smc.dev === 2 to install === =-=- Synchronizing package archives -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= =-=- Installing packages =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Building coq.hott: ./configure -configdir /home/bench/.opam/system/lib/coq/config -mandir /home/bench/.opam/system/man -docdir /home/bench/.opam/system/doc -prefix /home/bench/.opam/system -usecamlp5 -camlp5dir /home/bench/.opam/system/lib/camlp5 -coqide no make -j4 make install Installing coq.hott. Building coq:contrib:smc.dev: coq_makefile -f Make -o Makefile make -j4 make install Installing coq:contrib:smc.dev. </pre></dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "46e29627cbbfadc628390b00ee4c36ef", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 240, "avg_line_length": 40.56804733727811, "alnum_prop": 0.5023337222870479, "repo_name": "coq-bench/coq-bench.github.io-old", "id": "3ef4d50fa6f3f074d86c0af60effab8bf450a0f8", "size": "6858", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.02.1-1.2.0/unstable/8.4.5/contrib:smc/dev/2015-01-07_21-12-13.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#ifndef MICROPY_INCLUDED_PY_DYNRUNTIME_H #define MICROPY_INCLUDED_PY_DYNRUNTIME_H // This header file contains definitions to dynamically implement the static // MicroPython runtime API defined in py/obj.h and py/runtime.h. #include "py/nativeglue.h" #include "py/objstr.h" #undef MP_ROM_QSTR #undef MP_OBJ_QSTR_VALUE #undef MP_OBJ_NEW_QSTR #undef mp_const_none #undef mp_const_false #undef mp_const_true #undef mp_const_empty_tuple #undef nlr_raise /******************************************************************************/ // Memory allocation #define m_malloc(n) (m_malloc_dyn((n))) #define m_free(ptr) (m_free_dyn((ptr))) #define m_realloc(ptr, new_num_bytes) (m_realloc_dyn((ptr), (new_num_bytes))) static inline void *m_malloc_dyn(size_t n) { // TODO won't raise on OOM return mp_fun_table.realloc_(NULL, n, false); } static inline void m_free_dyn(void *ptr) { mp_fun_table.realloc_(ptr, 0, false); } static inline void *m_realloc_dyn(void *ptr, size_t new_num_bytes) { // TODO won't raise on OOM return mp_fun_table.realloc_(ptr, new_num_bytes, true); } /******************************************************************************/ // Printing #define mp_plat_print (*mp_fun_table.plat_print) #define mp_printf(p, ...) (mp_fun_table.printf_((p), __VA_ARGS__)) #define mp_vprintf(p, fmt, args) (mp_fun_table.vprintf_((p), (fmt), (args))) /******************************************************************************/ // Types and objects #define MP_OBJ_NEW_QSTR(x) MP_OBJ_NEW_QSTR_ ## x #define mp_type_type (*mp_fun_table.type_type) #define mp_type_str (*mp_fun_table.type_str) #define mp_type_list (*mp_fun_table.type_list) #define mp_type_EOFError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_EOFError))) #define mp_type_IndexError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_IndexError))) #define mp_type_KeyError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_KeyError))) #define mp_type_NotImplementedError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_NotImplementedError))) #define mp_type_RuntimeError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_RuntimeError))) #define mp_type_TypeError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_TypeError))) #define mp_type_ValueError (*(mp_obj_type_t*)(mp_load_global(MP_QSTR_ValueError))) #define mp_stream_read_obj (*mp_fun_table.stream_read_obj) #define mp_stream_readinto_obj (*mp_fun_table.stream_readinto_obj) #define mp_stream_unbuffered_readline_obj (*mp_fun_table.stream_unbuffered_readline_obj) #define mp_stream_write_obj (*mp_fun_table.stream_write_obj) #define mp_const_none ((mp_obj_t)mp_fun_table.const_none) #define mp_const_false ((mp_obj_t)mp_fun_table.const_false) #define mp_const_true ((mp_obj_t)mp_fun_table.const_true) #define mp_const_empty_tuple (mp_fun_table.new_tuple(0, NULL)) #define mp_obj_new_bool(b) ((b) ? (mp_obj_t)mp_fun_table.const_true : (mp_obj_t)mp_fun_table.const_false) #define mp_obj_new_int(i) (mp_fun_table.native_to_obj(i, MP_NATIVE_TYPE_INT)) #define mp_obj_new_int_from_uint(i) (mp_fun_table.native_to_obj(i, MP_NATIVE_TYPE_UINT)) #define mp_obj_new_str(data, len) (mp_fun_table.obj_new_str((data), (len))) #define mp_obj_new_str_of_type(t, d, l) (mp_obj_new_str_of_type_dyn((t), (d), (l))) #define mp_obj_new_bytes(data, len) (mp_fun_table.obj_new_bytes((data), (len))) #define mp_obj_new_bytearray_by_ref(n, i) (mp_fun_table.obj_new_bytearray_by_ref((n), (i))) #define mp_obj_new_tuple(n, items) (mp_fun_table.new_tuple((n), (items))) #define mp_obj_new_list(n, items) (mp_fun_table.new_list((n), (items))) #define mp_obj_get_type(o) (mp_fun_table.obj_get_type((o))) #define mp_obj_get_int(o) (mp_fun_table.native_from_obj(o, MP_NATIVE_TYPE_INT)) #define mp_obj_get_int_truncated(o) (mp_fun_table.native_from_obj(o, MP_NATIVE_TYPE_UINT)) #define mp_obj_str_get_str(s) ((void*)mp_fun_table.native_from_obj(s, MP_NATIVE_TYPE_PTR)) #define mp_obj_str_get_data(o, len) (mp_obj_str_get_data_dyn((o), (len))) #define mp_get_buffer_raise(o, bufinfo, fl) (mp_fun_table.get_buffer_raise((o), (bufinfo), (fl))) #define mp_get_stream_raise(s, flags) (mp_fun_table.get_stream_raise((s), (flags))) #define mp_obj_len(o) (mp_obj_len_dyn(o)) #define mp_obj_subscr(base, index, val) (mp_fun_table.obj_subscr((base), (index), (val))) #define mp_obj_list_append(list, item) (mp_fun_table.list_append((list), (item))) static inline mp_obj_t mp_obj_new_str_of_type_dyn(const mp_obj_type_t *type, const byte* data, size_t len) { if (type == &mp_type_str) { return mp_obj_new_str((const char*)data, len); } else { return mp_obj_new_bytes(data, len); } } static inline void *mp_obj_str_get_data_dyn(mp_obj_t o, size_t *l) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(o, &bufinfo, MP_BUFFER_READ); *l = bufinfo.len; return bufinfo.buf; } static inline mp_obj_t mp_obj_len_dyn(mp_obj_t o) { // If bytes implemented MP_UNARY_OP_LEN could use: mp_unary_op(MP_UNARY_OP_LEN, o) return mp_fun_table.call_function_n_kw(mp_fun_table.load_name(MP_QSTR_len), 1, &o); } /******************************************************************************/ // General runtime functions #define mp_load_name(qst) (mp_fun_table.load_name(qst)) #define mp_load_global(qst) (mp_fun_table.load_global(qst)) #define mp_store_global(qst, obj) (mp_fun_table.store_global((qst), (obj))) #define mp_unary_op(op, obj) (mp_fun_table.unary_op((op), (obj))) #define mp_binary_op(op, lhs, rhs) (mp_fun_table.binary_op((op), (lhs), (rhs))) #define mp_make_function_from_raw_code(rc, def_args, def_kw_args) \ (mp_fun_table.make_function_from_raw_code((rc), (def_args), (def_kw_args))) #define mp_call_function_n_kw(fun, n_args, n_kw, args) \ (mp_fun_table.call_function_n_kw((fun), (n_args) | ((n_kw) << 8), args)) #define mp_arg_check_num(n_args, n_kw, n_args_min, n_args_max, takes_kw) \ (mp_fun_table.arg_check_num_sig((n_args), (n_kw), MP_OBJ_FUN_MAKE_SIG((n_args_min), (n_args_max), (takes_kw)))) #define MP_DYNRUNTIME_INIT_ENTRY \ mp_obj_t old_globals = mp_fun_table.swap_globals(self->globals); \ mp_raw_code_t rc; \ rc.kind = MP_CODE_NATIVE_VIPER; \ rc.scope_flags = 0; \ rc.const_table = (void*)self->const_table; \ (void)rc; #define MP_DYNRUNTIME_INIT_EXIT \ mp_fun_table.swap_globals(old_globals); \ return mp_const_none; #define MP_DYNRUNTIME_MAKE_FUNCTION(f) \ (mp_make_function_from_raw_code((rc.fun_data = (f), &rc), MP_OBJ_NULL, MP_OBJ_NULL)) /******************************************************************************/ // Exceptions #define mp_obj_new_exception(o) ((mp_obj_t)(o)) // Assumes returned object will be raised, will create instance then #define mp_obj_new_exception_arg1(e_type, arg) (mp_obj_new_exception_arg1_dyn((e_type), (arg))) #define nlr_raise(o) (mp_raise_dyn(o)) #define mp_raise_msg(type, msg) (mp_fun_table.raise_msg((type), (msg))) #define mp_raise_OSError(er) (mp_raise_OSError_dyn(er)) #define mp_raise_NotImplementedError(msg) (mp_raise_msg(&mp_type_NotImplementedError, (msg))) #define mp_raise_TypeError(msg) (mp_raise_msg(&mp_type_TypeError, (msg))) #define mp_raise_ValueError(msg) (mp_raise_msg(&mp_type_ValueError, (msg))) static inline mp_obj_t mp_obj_new_exception_arg1_dyn(const mp_obj_type_t *exc_type, mp_obj_t arg) { mp_obj_t args[1] = { arg }; return mp_call_function_n_kw(MP_OBJ_FROM_PTR(exc_type), 1, 0, &args[0]); } static NORETURN inline void mp_raise_dyn(mp_obj_t o) { mp_fun_table.raise(o); for (;;) { } } static inline void mp_raise_OSError_dyn(int er) { mp_obj_t args[1] = { MP_OBJ_NEW_SMALL_INT(er) }; nlr_raise(mp_call_function_n_kw(mp_load_global(MP_QSTR_OSError), 1, 0, &args[0])); } /******************************************************************************/ // Floating point #define mp_obj_new_float_from_f(f) (mp_fun_table.obj_new_float_from_f((f))) #define mp_obj_new_float_from_d(d) (mp_fun_table.obj_new_float_from_d((d))) #define mp_obj_get_float_to_f(o) (mp_fun_table.obj_get_float_to_f((o))) #define mp_obj_get_float_to_d(o) (mp_fun_table.obj_get_float_to_d((o))) #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT #define mp_obj_new_float(f) (mp_obj_new_float_from_f((f))) #define mp_obj_get_float(o) (mp_obj_get_float_to_f((o))) #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE #define mp_obj_new_float(f) (mp_obj_new_float_from_d((f))) #define mp_obj_get_float(o) (mp_obj_get_float_to_d((o))) #endif #endif // MICROPY_INCLUDED_PY_DYNRUNTIME_H
{ "content_hash": "4e3bc99829793357e3a88e2e2558c3ca", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 132, "avg_line_length": 47.52577319587629, "alnum_prop": 0.5893709327548807, "repo_name": "trezor/micropython", "id": "7092a5dd888ccfd2b985be61c85a6659c3cf6b9e", "size": "10444", "binary": false, "copies": "1", "ref": "refs/heads/trezor-v1.12", "path": "py/dynruntime.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "106243" }, { "name": "C", "bytes": "12090846" }, { "name": "C++", "bytes": "570652" }, { "name": "CMake", "bytes": "800" }, { "name": "HTML", "bytes": "84456" }, { "name": "Makefile", "bytes": "105968" }, { "name": "Objective-C", "bytes": "7450" }, { "name": "Python", "bytes": "841669" }, { "name": "Shell", "bytes": "13882" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe "bonds/show", :type => :view do before(:each) do @bond = assign(:bond, Bond.create!( :name => "Name" )) end it "renders attributes in <p>" do render expect(rendered).to match(/Name/) end end
{ "content_hash": "cdb82f58d1268eb754cbe0f29089e839", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 46, "avg_line_length": 18.642857142857142, "alnum_prop": 0.6053639846743295, "repo_name": "overallduka/bullkap", "id": "c39323c57ab73834c6f0cbf7dcc3a721650df13b", "size": "261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/views/bonds/show.html.erb_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4255" }, { "name": "CoffeeScript", "bytes": "1370" }, { "name": "HTML", "bytes": "46404" }, { "name": "JavaScript", "bytes": "977" }, { "name": "Ruby", "bytes": "103266" }, { "name": "Shell", "bytes": "2520" } ], "symlink_target": "" }
package test.thread; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.xml.XmlSuite; import test.BaseTest; import java.util.HashMap; import java.util.Map; public class SequentialTest extends BaseTest { @Test public void verifySequential1() { verifySequential(1); } @Test public void verifySequential2() { verifySequential(2); } @Test public void verifySequential3() { verifySequential(3); } @Test public void verifySingleThreaded1() { verifySingleThreaded(1); } @Test public void verifySingleThreaded2() { verifySingleThreaded(2); } @Test public void verifySingleThreaded3() { verifySingleThreaded(3); } public void verifySequential(int threadCount) { runTest(threadCount, SequentialSampleTest.class.getName(), SequentialSample2Test.class.getName(), SequentialSample3Test.class.getName()); } public void verifySingleThreaded(int threadCount) { runTest(threadCount, SingleThreadedSampleTest.class.getName(), SingleThreadedSample2Test.class.getName(), SingleThreadedSample3Test.class.getName()); } private void runTest(int threadCount, String... classes) { Helper.reset(); for (String c : classes) { addClass(c); } setParallel(XmlSuite.PARALLEL_METHODS); setThreadCount(threadCount); run(); Map<Long, Long>[] maps = new Map[] { Helper.getMap(classes[0]), Helper.getMap(classes[1]), Helper.getMap(classes[2]), }; for(Map m : maps) { Assert.assertEquals(m.size(), 1); } long[] ids = new long[] { maps[0].keySet().iterator().next().longValue(), maps[1].keySet().iterator().next().longValue(), maps[2].keySet().iterator().next().longValue(), }; Map<Long, Long> verifyMap = new HashMap<Long, Long>(); for (long id : ids) { verifyMap.put(id, id); } Assert.assertEquals(verifyMap.size(), threadCount); ppp("COUNT:" + threadCount + " THREAD ID'S:" + ids[0] + " " + ids[1] + " " + ids[2]); } private static void ppp(String s) { if (false) { System.out.println("[SequentialTest] " + s); } } }
{ "content_hash": "74cf7d3799e5d1dd807d8a977affde01", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 90, "avg_line_length": 22.93069306930693, "alnum_prop": 0.6101036269430051, "repo_name": "tremes/testng", "id": "68b41d5da023dbc116823cd12944c17051d70608", "size": "2316", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/test/java/test/thread/SequentialTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "6065" }, { "name": "HTML", "bytes": "11861" }, { "name": "Java", "bytes": "2188634" }, { "name": "JavaScript", "bytes": "3555" }, { "name": "PHP", "bytes": "1594" }, { "name": "Shell", "bytes": "4388" }, { "name": "XSLT", "bytes": "7117" } ], "symlink_target": "" }
/** \file * * Input classes for the Velodyne HDL-64E 3D LIDAR: * * Input -- base class used to access the data independently of * its source * * InputSocket -- derived class reads live data from the device * via a UDP socket * * InputPCAP -- derived class provides a similar interface from a * PCAP dump */ #include <unistd.h> #include <string> #include <sstream> #include <sys/socket.h> #include <arpa/inet.h> #include <poll.h> #include <errno.h> #include <fcntl.h> #include <sys/file.h> #include <velodyne_driver/input.h> namespace velodyne_driver { static const size_t packet_size = sizeof(velodyne_msgs::VelodynePacket().data); //////////////////////////////////////////////////////////////////////// // Input base class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number. */ Input::Input(ros::NodeHandle private_nh, uint16_t port): private_nh_(private_nh), port_(port) { private_nh.param("device_ip", devip_str_, std::string("")); if (!devip_str_.empty()) ROS_INFO_STREAM("Only accepting packets from IP address: " << devip_str_); } //////////////////////////////////////////////////////////////////////// // InputSocket class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number */ InputSocket::InputSocket(ros::NodeHandle private_nh, uint16_t port): Input(private_nh, port) { sockfd_ = -1; if (!devip_str_.empty()) { inet_aton(devip_str_.c_str(),&devip_); } // connect to Velodyne UDP port ROS_INFO_STREAM("Opening UDP socket: port " << port); sockfd_ = socket(PF_INET, SOCK_DGRAM, 0); if (sockfd_ == -1) { perror("socket"); // TODO: ROS_ERROR errno return; } sockaddr_in my_addr; // my address information memset(&my_addr, 0, sizeof(my_addr)); // initialize to zeros my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(port); // port in network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill in my IP if (bind(sockfd_, (sockaddr *)&my_addr, sizeof(sockaddr)) == -1) { perror("bind"); // TODO: ROS_ERROR errno return; } if (fcntl(sockfd_,F_SETFL, O_NONBLOCK|FASYNC) < 0) { perror("non-block"); return; } ROS_DEBUG("Velodyne socket fd is %d\n", sockfd_); } /** @brief destructor */ InputSocket::~InputSocket(void) { (void) close(sockfd_); } /** @brief Get one velodyne packet. */ int InputSocket::getPacket(velodyne_msgs::VelodynePacket *pkt, const double time_offset) { double time1 = ros::Time::now().toSec(); struct pollfd fds[1]; fds[0].fd = sockfd_; fds[0].events = POLLIN; static const int POLL_TIMEOUT = 1000; // one second (in msec) sockaddr_in sender_address; socklen_t sender_address_len = sizeof(sender_address); while (true) { // Unfortunately, the Linux kernel recvfrom() implementation // uses a non-interruptible sleep() when waiting for data, // which would cause this method to hang if the device is not // providing data. We poll() the device first to make sure // the recvfrom() will not block. // // Note, however, that there is a known Linux kernel bug: // // Under Linux, select() may report a socket file descriptor // as "ready for reading", while nevertheless a subsequent // read blocks. This could for example happen when data has // arrived but upon examination has wrong checksum and is // discarded. There may be other circumstances in which a // file descriptor is spuriously reported as ready. Thus it // may be safer to use O_NONBLOCK on sockets that should not // block. // poll() until input available do { int retval = poll(fds, 1, POLL_TIMEOUT); if (retval < 0) // poll() error? { if (errno != EINTR) ROS_ERROR("poll() error: %s", strerror(errno)); return 1; } if (retval == 0) // poll() timeout? { ROS_WARN("Velodyne poll() timeout"); return 1; } if ((fds[0].revents & POLLERR) || (fds[0].revents & POLLHUP) || (fds[0].revents & POLLNVAL)) // device error? { ROS_ERROR("poll() reports Velodyne error"); return 1; } } while ((fds[0].revents & POLLIN) == 0); // Receive packets that should now be available from the // socket using a blocking read. ssize_t nbytes = recvfrom(sockfd_, &pkt->data[0], packet_size, 0, (sockaddr*) &sender_address, &sender_address_len); if (nbytes < 0) { if (errno != EWOULDBLOCK) { perror("recvfail"); ROS_INFO("recvfail"); return 1; } } else if ((size_t) nbytes == packet_size) { // read successful, // if packet is not from the lidar scanner we selected by IP, // continue otherwise we are done if(devip_str_ != "" && sender_address.sin_addr.s_addr != devip_.s_addr) continue; else break; //done } ROS_DEBUG_STREAM("incomplete Velodyne packet read: " << nbytes << " bytes"); } // Average the times at which we begin and end reading. Use that to // estimate when the scan occurred. Add the time offset. double time2 = ros::Time::now().toSec(); pkt->stamp = ros::Time((time2 + time1) / 2.0 + time_offset); return 0; } //////////////////////////////////////////////////////////////////////// // InputPCAP class implementation //////////////////////////////////////////////////////////////////////// /** @brief constructor * * @param private_nh ROS private handle for calling node. * @param port UDP port number * @param packet_rate expected device packet frequency (Hz) * @param filename PCAP dump file name */ InputPCAP::InputPCAP(ros::NodeHandle private_nh, uint16_t port, double packet_rate, std::string filename, bool read_once, bool read_fast, double repeat_delay): Input(private_nh, port), packet_rate_(packet_rate), filename_(filename) { pcap_ = NULL; empty_ = true; // get parameters using private node handle private_nh.param("read_once", read_once_, false); private_nh.param("read_fast", read_fast_, false); private_nh.param("repeat_delay", repeat_delay_, 0.0); if (read_once_) ROS_INFO("Read input file only once."); if (read_fast_) ROS_INFO("Read input file as quickly as possible."); if (repeat_delay_ > 0.0) ROS_INFO("Delay %.3f seconds before repeating input file.", repeat_delay_); // Open the PCAP dump file ROS_INFO("Opening PCAP file \"%s\"", filename_.c_str()); if ((pcap_ = pcap_open_offline(filename_.c_str(), errbuf_) ) == NULL) { ROS_FATAL("Error opening Velodyne socket dump file."); return; } std::stringstream filter; if( devip_str_ != "" ) // using specific IP? { filter << "src host " << devip_str_ << " && "; } filter << "udp dst port " << port; pcap_compile(pcap_, &pcap_packet_filter_, filter.str().c_str(), 1, PCAP_NETMASK_UNKNOWN); } /** destructor */ InputPCAP::~InputPCAP(void) { pcap_close(pcap_); } /** @brief Get one velodyne packet. */ int InputPCAP::getPacket(velodyne_msgs::VelodynePacket *pkt, const double time_offset) { struct pcap_pkthdr *header; const u_char *pkt_data; while (true) { int res; if ((res = pcap_next_ex(pcap_, &header, &pkt_data)) >= 0) { // Skip packets not for the correct port and from the // selected IP address. if (!devip_str_.empty() && (0 == pcap_offline_filter(&pcap_packet_filter_, header, pkt_data))) continue; // Keep the reader from blowing through the file. if (read_fast_ == false) packet_rate_.sleep(); memcpy(&pkt->data[0], pkt_data+42, packet_size); pkt->stamp = ros::Time::now(); // time_offset not considered here, as no synchronization required empty_ = false; return 0; // success } if (empty_) // no data in file? { ROS_WARN("Error %d reading Velodyne packet: %s", res, pcap_geterr(pcap_)); return -1; } if (read_once_) { ROS_INFO("end of file reached -- done reading."); return -1; } if (repeat_delay_ > 0.0) { ROS_INFO("end of file reached -- delaying %.3f seconds.", repeat_delay_); usleep(rint(repeat_delay_ * 1000000.0)); } ROS_DEBUG("replaying Velodyne dump file"); // I can't figure out how to rewind the file, because it // starts with some kind of header. So, close the file // and reopen it with pcap. pcap_close(pcap_); pcap_ = pcap_open_offline(filename_.c_str(), errbuf_); empty_ = true; // maybe the file disappeared? } // loop back and try again } } // velodyne_driver namespace
{ "content_hash": "fe210bdb8971c559e05ae4dd326e2389", "timestamp": "", "source": "github", "line_count": 319, "max_line_length": 109, "avg_line_length": 32.57993730407524, "alnum_prop": 0.5121716539978832, "repo_name": "startcode/apollo", "id": "ad682bb90a4f67ab6c09124e711e5c08238e4146", "size": "10632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/drivers/velodyne_vls/velodyne_driver/src/lib/input.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "45614" }, { "name": "C++", "bytes": "9361050" }, { "name": "CMake", "bytes": "41261" }, { "name": "CSS", "bytes": "35714" }, { "name": "Cuda", "bytes": "51223" }, { "name": "Dockerfile", "bytes": "1843" }, { "name": "HTML", "bytes": "20313" }, { "name": "JavaScript", "bytes": "304933" }, { "name": "Python", "bytes": "1203616" }, { "name": "Shell", "bytes": "281488" }, { "name": "Smarty", "bytes": "43786" } ], "symlink_target": "" }
package com.jpattern.gwt.history; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.user.client.ui.HasVisibility; import com.google.gwt.user.client.ui.HasWidgets; import com.jpattern.gwt.client.AApplication; import com.jpattern.gwt.client.BaseTest; import com.jpattern.gwt.client.IApplicationProvider; import com.jpattern.gwt.client.history.HistoryService; import com.jpattern.gwt.client.history.IHistoryManagerObserver; import com.jpattern.gwt.client.history.DirectHistoryEngine; import com.jpattern.gwt.client.logger.SysoutLoggerService; import com.jpattern.gwt.client.navigationevent.ANavigationEvent; import com.jpattern.gwt.client.navigationevent.NullNavigationEventCallback; import com.jpattern.gwt.client.navigationevent.RootNavigationEvent; import com.jpattern.gwt.client.presenter.APresenter; import com.jpattern.gwt.client.presenter.IPresenter; import com.jpattern.gwt.client.presenter.IPresenterDefinition; import com.jpattern.gwt.client.presenter.NullPresenter; import com.jpattern.gwt.client.view.INotificationArea; import com.jpattern.gwt.client.view.IShowViewStrategy; import com.jpattern.gwt.client.view.IView; import com.jpattern.gwt.client.view.NullNotificationArea; import com.jpattern.gwt.client.view.NullHasWidgets; import com.jpattern.gwt.client.view.NullShowViewStrategy; import com.jpattern.gwt.client.view.NullView; /** * * @author Francesco Cina' * * 08/ago/2011 */ public class FixedSizeHistoryManager4Test extends BaseTest { public static List<IPresenter> createdPresenterList = new ArrayList<IPresenter>(); private AApplication applicationProvider; private HistoryManagerObserver historyManagerObserver = new HistoryManagerObserver(); @Override protected void setUp() throws Exception { applicationProvider = new AApplication() { public void stopSystem() {} public void startSystem() { setLoggerService(new SysoutLoggerService()); setHistoryService(new HistoryService(new DirectHistoryEngine(getLoggerService()), historyManagerObserver,getLoggerService())); } }; applicationProvider.startSystem(); } @Override protected void tearDown() throws Exception { } public void testHistoryManager() throws Exception { MockMainNavigationEvent mainNavigationEvent = new MockMainNavigationEvent(""); mainNavigationEvent.registerNavigationEvent(new NavEvent("event1"), new NullHasWidgets(), new NullNavigationEventCallback()); mainNavigationEvent.registerNavigationEvent(new NavEvent("event2"), new NullHasWidgets(), new NullNavigationEventCallback()); mainNavigationEvent.registerNavigationEvent(new NavEvent("event3"), new NullHasWidgets(), new NullNavigationEventCallback()); mainNavigationEvent.registerNavigationEvent(new NavEvent("event4"), new NullHasWidgets(), new NullNavigationEventCallback()); // rootNavigationEvent.addInitialNavigationEvent("event1"); RootNavigationEvent rootNavigationEvent = new RootNavigationEvent( mainNavigationEvent, new NullHasWidgets(),applicationProvider); rootNavigationEvent.startApplication(); System.out.println("App started"); IPresenter rootPresenter = mainNavigationEvent.launch(new NullPresenter(applicationProvider), new HashMap<String, String>(), new String[0]); rootPresenter.launchNavigationEvent("event1", true); assertEquals( "_event1" , historyManagerObserver.eventName ); assertEquals( 1 , createdPresenterList.size() ); assertEquals( "event1", createdPresenterList.get(0).getNavigationEvent().getName()); } class HistoryManagerObserver implements IHistoryManagerObserver { String eventName = ""; @Override public void onRegisterHistory(String currentToken, List<String> presenterHierarchy) { System.out.println("-----------------------------------------------------------"); System.out.println("current token: [" + currentToken + "]"); System.out.println("-----------------------------------------------------------"); } @Override public void onEvent(String eventName) { this.eventName = eventName; System.out.println("-----------------------------------------------------------"); System.out.println("history event: [" + eventName + "]"); System.out.println("-----------------------------------------------------------"); } } class NavEvent extends ANavigationEvent { public NavEvent(String eventName) { super(eventName); } @Override public IPresenter exec(Map<String, String> queryStringMap) { System.out.println("Event exec() on " + getName()); return new SimplePresenter(new NullShowViewStrategy<IView>(new NullView()), getPresenterDefinition()); } } static class SimplePresenter extends APresenter<IView> { public static int ID_COUNT = 0; public int id; public SimplePresenter(IShowViewStrategy<IView> showViewStrategy, IPresenterDefinition navigationEvent) { super(showViewStrategy, navigationEvent); createdPresenterList.add(this); id = ID_COUNT++; System.out.println("SimplePresenter " + id + " created"); } @Override public void preRender() { System.out.println("SimplePresenter " + id + " preDisplay"); } @Override public void init() { System.out.println("SimplePresenter " + id + " postDisplay"); } @Override public void onGlobalEvent(String status) { } @Override protected void onUnloadPresenter() { } } class SimpleView implements IView { private IPresenter presenter; @Override public void visit(IPresenter presenter) { this.presenter = presenter; } @Override public IPresenter getPresenter() { return presenter; } @Override public void render(HasWidgets container) { } @Override public INotificationArea getNotificationArea() { return new NullNotificationArea(); } @Override public void onNavigationEvent(String eventName) { } @Override public void hideIfUserNotInRole(HasVisibility widget, String[] allowedRoles) { } @Override public void hideIfUserIsNotValid(HasVisibility widget) { } @Override public void setApplicationProvider(IApplicationProvider provider) { } @Override public void hideIfUserHasNoRightsForNavigationEvent( HasVisibility widget, String navigationEventName) { // TODO Auto-generated method stub } @Override public void init() { // TODO Auto-generated method stub } } }
{ "content_hash": "d4acba438ef492e8657984bffc027eb7", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 142, "avg_line_length": 31.48768472906404, "alnum_prop": 0.7377972465581978, "repo_name": "ufoscout/jpattern", "id": "cbf9d4d29fa933233bcb3216b641100350a7c302", "size": "6392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gwt/src/test/java/com/jpattern/gwt/history/FixedSizeHistoryManager4Test.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "33062" }, { "name": "Java", "bytes": "1384577" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <titles> <title> <KEXPRelease>844eb096-2b84-4c8f-9922-7f287126b39e</KEXPRelease> <KEXPMediumNumber>1</KEXPMediumNumber> <KEXPTotalMediums>1</KEXPTotalMediums> <KEXPReleaseArtistSortName>Anderson .Paak</KEXPReleaseArtistSortName> <KEXPTrackMBID>9c499eb3-5598-4541-92b5-bf9695feb7c2</KEXPTrackMBID> <ItemCode>9c499eb3-5598-4541-92b5-bf9695feb7c2</ItemCode> <Key1>9c499eb3-5598-4541-92b5-bf9695feb7c2</Key1> <KEXPRecordingMBID>f9b300d0-af27-4b3e-a873-a21b6cc5b960</KEXPRecordingMBID> <Title>Lite Weight</Title> <KEXPTrackNumber>9</KEXPTrackNumber> <KEXPTotalTracks>16</KEXPTotalTracks> <KEXPPrimaryGenre></KEXPPrimaryGenre> <KEXPFCCObscenityRating>RED DOT</KEXPFCCObscenityRating> <KEXPArtist>d02dd67e-f655-4600-bc47-f789f59e7367</KEXPArtist> <KEXPArtist>34ee9f44-6ffd-4ac0-b86b-eed77a40fdca</KEXPArtist> <KEXPArtistCredit>Anderson .Paak feat. The Free Nationals United Fellowship Choir</KEXPArtistCredit> <secondary_category>CATEGORIES/ROTATION-STAGING/Heavy/Anderson .Paak - Malibu</secondary_category> <KEXPReleaseArtistDistributionRule>A</KEXPReleaseArtistDistributionRule> <KEXPVariousArtistReleaseTitleDistributionRule>M</KEXPVariousArtistReleaseTitleDistributionRule> <KEXPContentType>music library track</KEXPContentType> <KEXPSource>CD Library</KEXPSource> </title> </titles>
{ "content_hash": "7a97c849a63dccb60f7f92c338dc1293", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 104, "avg_line_length": 54.15384615384615, "alnum_prop": 0.7883522727272727, "repo_name": "hidat/audio_pipeline", "id": "6a03ee2e14f31558a19bf58a28759309c96018ac", "size": "1408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "audio_pipeline/test/results/correct_dalet_xmls/track_meta/9c499eb3-5598-4541-92b5-bf9695feb7c2.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "343203" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <config xmlns="http://www.knime.org/2008/09/XMLConfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.knime.org/2008/09/XMLConfig http://www.knime.org/XMLConfig_2008_09.xsd" key="spec.xml"> <entry key="spec_name" type="xstring" value="default"/> <entry key="number_columns" type="xint" value="1"/> <config key="column_spec_0"> <entry key="column_name" type="xstring" value="uniprot_id"/> <config key="element_names"> <entry key="array-size" type="xint" value="0"/> </config> <config key="column_type"> <entry key="cell_class" type="xstring" value="org.knime.core.data.def.StringCell"/> </config> <config key="column_domain"> <config key="possible_values"> <entry key="array-size" type="xint" value="1"/> <config key="0"> <entry key="datacell" type="xstring" value="org.knime.core.data.def.StringCell"/> <config key="org.knime.core.data.def.StringCell"> <entry key="StringCell" type="xstring" value="oprk_human"/> </config> </config> </config> </config> <config key="column_properties"/> </config> </config>
{ "content_hash": "55771d14e86c628894bdc6c7142c0d49", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 227, "avg_line_length": 41.69230769230769, "alnum_prop": 0.7066420664206642, "repo_name": "3D-e-Chem/knime-gpcrdb", "id": "72c2a1b5e037ac50f67f5abaf870a7af31f60499", "size": "1084", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/src/knime/residues-test/Table Creator (#3)/port_1/spec.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "591195" } ], "symlink_target": "" }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.base.task; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import android.support.test.filters.SmallTest; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.task.SchedulerTestHelpers; import java.util.ArrayList; import java.util.List; /** * Test class for {@link SequencedTaskRunnerImpl}. * * Note due to layering concerns we can't test post native functionality in a * base javatest. Instead see: * content/public/android/javatests/src/org/chromium/content/browser/scheduler/ * NativePostTaskTest.java */ @RunWith(BaseJUnit4ClassRunner.class) public class SequencedTaskRunnerImplTest { @Test @SmallTest public void testPreNativeTasksRunInOrder() { TaskRunner taskQueue = new SequencedTaskRunnerImpl(TaskTraits.USER_BLOCKING); List<Integer> orderList = new ArrayList<>(); SchedulerTestHelpers.postRecordOrderTask(taskQueue, orderList, 1); SchedulerTestHelpers.postRecordOrderTask(taskQueue, orderList, 2); SchedulerTestHelpers.postRecordOrderTask(taskQueue, orderList, 3); SchedulerTestHelpers.postTaskAndBlockUntilRun(taskQueue); assertThat(orderList, contains(1, 2, 3)); } }
{ "content_hash": "f4f181c6d770e8b1e5dda3eeaebf8e4b", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 85, "avg_line_length": 36.142857142857146, "alnum_prop": 0.7733860342555995, "repo_name": "endlessm/chromium-browser", "id": "4fd607581a75bb3635e5f5e5d82f08018da3fb35", "size": "1518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "base/android/javatests/src/org/chromium/base/task/SequencedTaskRunnerImplTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#ifndef itkNeighborhoodAllocator_h #define itkNeighborhoodAllocator_h #include <algorithm> #include <iostream> #include <memory> #include "itkMacro.h" namespace itk { /** \class NeighborhoodAllocator * \brief A memory allocator for use as the default allocator type in * Neighborhood. * * This is a memory allocator for use as the default allocator type in * Neighborhood. The API is designed to mimic that of vnl_vector so that * vnl_vector can also be used as an allocator for Neighborhood. * * The decision to create this allocator with the vnl_vector api (versus * using an STL allocator and wrapping the vnl_vector API) was made because * the STL allocator API is not guaranteed stable at this time. * * \ingroup Operators * \ingroup ITKCommon */ template <typename TPixel> class NeighborhoodAllocator { public: /** Standard class type aliases. */ using Self = NeighborhoodAllocator; /** Iterator support. Note that the naming of the type alias is on purpose. * itk::Neighborhood makes reference to the allocator, which because it may * be vnl or other type, uses the lower case/underscore forms iterator and * const_iterator. */ using iterator = TPixel *; using const_iterator = const TPixel *; /** Default constructor */ NeighborhoodAllocator() = default; /** Defaulted destructor */ ~NeighborhoodAllocator() = default; /** Allocates memory using new() */ void Allocate(unsigned int n) { m_Data.reset(new TPixel[n]); m_ElementCount = n; } /** Deallocates memory using delete[](). */ void Deallocate() { m_Data.reset(); m_ElementCount = 0; } /** Copy constructor. */ NeighborhoodAllocator(const Self & other) : m_ElementCount(other.m_ElementCount) , m_Data(new TPixel[other.m_ElementCount]) { std::copy_n(other.m_Data.get(), m_ElementCount, m_Data.get()); } /** Move-constructor. */ NeighborhoodAllocator(Self && other) noexcept : m_ElementCount{ other.m_ElementCount } , m_Data{ std::move(other.m_Data) } { other.m_ElementCount = 0; } /** Assignment operator. */ Self & operator=(const Self & other) { if (this != &other) { this->set_size(other.m_ElementCount); std::copy_n(other.m_Data.get(), m_ElementCount, m_Data.get()); } return *this; } /** Move-assignment. */ Self & operator=(Self && other) noexcept { if (this != &other) { m_ElementCount = other.m_ElementCount; m_Data = std::move(other.m_Data); other.m_ElementCount = 0; } return *this; } /** STL-style iterator support for the memory buffer. */ iterator begin() { return m_Data.get(); } const_iterator begin() const { return m_Data.get(); } iterator end() { return (m_Data.get() + m_ElementCount); } const_iterator end() const { return (m_Data.get() + m_ElementCount); } unsigned int size() const { return m_ElementCount; } /** Data access methods */ const TPixel & operator[](unsigned int i) const { return m_Data[i]; } TPixel & operator[](unsigned int i) { return m_Data[i]; } /** Allocates a buffer of size n */ void set_size(unsigned int n) { if (n != m_ElementCount) { *this = NeighborhoodAllocator(); m_Data.reset(new TPixel[n]); m_ElementCount = n; } } TPixel * data() noexcept { return m_Data.get(); } const TPixel * data() const noexcept { return m_Data.get(); } private: unsigned int m_ElementCount{ 0 }; std::unique_ptr<TPixel[]> m_Data; }; template <typename TPixel> inline std::ostream & operator<<(std::ostream & o, const NeighborhoodAllocator<TPixel> & a) { o << "NeighborhoodAllocator { this = " << &a << ", begin = " << static_cast<const void *>(a.begin()) << ", size=" << a.size() << " }"; return o; } // Equality operator. template <typename TPixel> inline bool operator==(const NeighborhoodAllocator<TPixel> & lhs, const NeighborhoodAllocator<TPixel> & rhs) { const unsigned int size = lhs.size(); return (size == rhs.size()) && ((size == 0) || std::equal(lhs.begin(), lhs.end(), rhs.begin())); } // Inequality operator. template <typename TPixel> inline bool operator!=(const NeighborhoodAllocator<TPixel> & lhs, const NeighborhoodAllocator<TPixel> & rhs) { return !(lhs == rhs); } } // end namespace itk #endif
{ "content_hash": "9cd6d3e2d758cd17b66d6f39803b5b10", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 102, "avg_line_length": 22.701030927835053, "alnum_prop": 0.6428247048138056, "repo_name": "BRAINSia/ITK", "id": "25c9a833165a8b231718ed692b96562bd9ddaa71", "size": "5161", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Modules/Core/Common/include/itkNeighborhoodAllocator.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "460926" }, { "name": "C++", "bytes": "35348259" }, { "name": "CMake", "bytes": "1650670" }, { "name": "CSS", "bytes": "17428" }, { "name": "HTML", "bytes": "8373" }, { "name": "JavaScript", "bytes": "1522" }, { "name": "Objective-C++", "bytes": "5647" }, { "name": "Perl", "bytes": "6197" }, { "name": "Python", "bytes": "678443" }, { "name": "SWIG", "bytes": "53991" }, { "name": "Shell", "bytes": "194950" }, { "name": "Tcl", "bytes": "7953" }, { "name": "XSLT", "bytes": "8640" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-fingroup: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.11.dev / mathcomp-fingroup - 1.6.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-fingroup <small> 1.6.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-07-16 03:01:33 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-16 03:01:33 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-mathcomp-fingroup&quot; version: &quot;1.6.1&quot; maintainer: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; homepage: &quot;http://ssr.msr-inria.inria.fr/&quot; bug-reports: &quot;Mathematical Components &lt;mathcomp-dev@sympa.inria.fr&gt;&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-C&quot; &quot;mathcomp/fingroup&quot; &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;-C&quot; &quot;mathcomp/fingroup&quot; &quot;install&quot; ] remove: [ &quot;sh&quot; &quot;-c&quot; &quot;rm -rf &#39;%{lib}%/coq/user-contrib/mathcomp/fingroup&#39;&quot; ] depends: [ &quot;ocaml&quot; &quot;coq-mathcomp-ssreflect&quot; {= &quot;1.6.1&quot;} ] tags: [ &quot;keyword:finite groups&quot; &quot;keyword:small scale reflection&quot; &quot;keyword:mathematical components&quot; &quot;keyword:odd order theorem&quot; ] authors: [ &quot;Jeremy Avigad &lt;&gt;&quot; &quot;Andrea Asperti &lt;&gt;&quot; &quot;Stephane Le Roux &lt;&gt;&quot; &quot;Yves Bertot &lt;&gt;&quot; &quot;Laurence Rideau &lt;&gt;&quot; &quot;Enrico Tassi &lt;&gt;&quot; &quot;Ioana Pasca &lt;&gt;&quot; &quot;Georges Gonthier &lt;&gt;&quot; &quot;Sidi Ould Biha &lt;&gt;&quot; &quot;Cyril Cohen &lt;&gt;&quot; &quot;Francois Garillot &lt;&gt;&quot; &quot;Alexey Solovyev &lt;&gt;&quot; &quot;Russell O&#39;Connor &lt;&gt;&quot; &quot;Laurent Théry &lt;&gt;&quot; &quot;Assia Mahboubi &lt;&gt;&quot; ] synopsis: &quot;Mathematical Components Library on finite groups&quot; description: &quot;&quot;&quot; This library contains definitions and theorems about finite groups, group quotients, group morphisms, group presentation, group action...&quot;&quot;&quot; url { src: &quot;http://github.com/math-comp/math-comp/archive/mathcomp-1.6.1.tar.gz&quot; checksum: &quot;md5=10d8a17134ddb509b4afa8d3243ee1a0&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-mathcomp-fingroup.1.6.1 coq.8.11.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev). The following dependencies couldn&#39;t be met: - coq-mathcomp-fingroup -&gt; coq-mathcomp-ssreflect = 1.6.1 -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-mathcomp-fingroup.1.6.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "a017cffe8bc52751b20e936051de707a", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 554, "avg_line_length": 46.41818181818182, "alnum_prop": 0.5598642120381251, "repo_name": "coq-bench/coq-bench.github.io", "id": "f6c60c4f4528b3d981ab6ba6530627f747857fdc", "size": "7685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.6/extra-dev/8.11.dev/mathcomp-fingroup/1.6.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
namespace aura { class Window; } namespace gfx { class Point; } namespace ash { // Finds the topmost window at |screen_point| with ignoring |ignore|. If // overview is active when this function is called, the overview window that // contains |screen_point| will be returned. Note this overview window might not // be visibile (e.g., it represents an aura window whose window state is // MINIMIZED). ASH_EXPORT aura::Window* GetTopmostWindowAtPoint( const gfx::Point& screen_point, const std::set<aura::Window*>& ignore); } // namespace ash #endif // ASH_PUBLIC_CPP_WINDOW_FINDER_H_
{ "content_hash": "b38442a78ebe784403dab7a1848521e9", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 80, "avg_line_length": 27.136363636363637, "alnum_prop": 0.7269681742043551, "repo_name": "nwjs/chromium.src", "id": "ee9794a56b8a85d9013dc8b8676569a2a1e42923", "size": "867", "binary": false, "copies": "6", "ref": "refs/heads/nw70", "path": "ash/public/cpp/window_finder.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <sbml xmlns="http://www.sbml.org/sbml/level2/version2" level="2" version="2"> <model metaid="_case00395" id="case00395" name="case00395"> <listOfCompartments> <compartment id="C" name="C" size="1" units="volume"/> </listOfCompartments> <listOfSpecies> <species id="S1" name="S1" compartment="C" initialAmount="1" substanceUnits="substance"/> <species id="S2" name="S2" compartment="C" initialAmount="2" substanceUnits="substance"/> <species id="S3" name="S3" compartment="C" initialAmount="1" substanceUnits="substance"/> </listOfSpecies> <listOfReactions> <reaction id="reaction1" name="reaction1" reversible="false" fast="false"> <listOfReactants> <speciesReference species="S1"/> <speciesReference species="S2"/> </listOfReactants> <listOfProducts> <speciesReference species="S3"/> </listOfProducts> <kineticLaw> <math xmlns="http://www.w3.org/1998/Math/MathML"> <apply> <times/> <ci> C </ci> <ci> k </ci> <ci> S1 </ci> <ci> S2 </ci> </apply> </math> <listOfParameters> <parameter id="k" value="0.75"/> </listOfParameters> </kineticLaw> </reaction> <reaction id="reaction2" name="reaction2" reversible="false" fast="false"> <listOfReactants> <speciesReference species="S3"/> </listOfReactants> <listOfProducts> <speciesReference species="S1"/> <speciesReference species="S2"/> </listOfProducts> <kineticLaw> <math xmlns="http://www.w3.org/1998/Math/MathML"> <apply> <times/> <ci> C </ci> <ci> k </ci> <ci> S3 </ci> </apply> </math> <listOfParameters> <parameter id="k" value="0.25"/> </listOfParameters> </kineticLaw> </reaction> </listOfReactions> <listOfEvents> <event id="event1" name="event1"> <trigger> <math xmlns="http://www.w3.org/1998/Math/MathML"> <apply> <lt/> <ci> S1 </ci> <cn> 0.75 </cn> </apply> </math> </trigger> <listOfEventAssignments> <eventAssignment variable="S2"> <math xmlns="http://www.w3.org/1998/Math/MathML"> <cn> 1.5 </cn> </math> </eventAssignment> <eventAssignment variable="S1"> <math xmlns="http://www.w3.org/1998/Math/MathML"> <cn type="integer"> 1 </cn> </math> </eventAssignment> </listOfEventAssignments> </event> </listOfEvents> </model> </sbml>
{ "content_hash": "e1e20ba0c20c79fe4f5e623528b8c64a", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 95, "avg_line_length": 34, "alnum_prop": 0.5173010380622838, "repo_name": "stanleygu/sbmltest2archive", "id": "1a48bb896f2cd5bcd6e09e067aabd47d5f0f3774", "size": "2890", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sbml-test-cases/cases/semantic/00395/00395-sbml-l2v2.xml", "mode": "33188", "license": "mit", "language": [ { "name": "M", "bytes": "12509" }, { "name": "Mathematica", "bytes": "721776" }, { "name": "Matlab", "bytes": "1729754" }, { "name": "Objective-C", "bytes": "144988" } ], "symlink_target": "" }
package com.codenotfound.ws.client; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.ws.client.core.WebServiceTemplate; @Configuration public class ClientConfig { @Bean Jaxb2Marshaller jaxb2Marshaller() { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setContextPath("org.example.ticketagent"); return jaxb2Marshaller; } @Bean public WebServiceTemplate webServiceTemplate() { WebServiceTemplate webServiceTemplate = new WebServiceTemplate(); webServiceTemplate.setMarshaller(jaxb2Marshaller()); webServiceTemplate.setUnmarshaller(jaxb2Marshaller()); webServiceTemplate.setDefaultUri( "http://localhost:8080/codenotfound/ws/helloworld"); return webServiceTemplate; } }
{ "content_hash": "37bb504375924c6b8dfdc9c303a343f8", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 69, "avg_line_length": 30.896551724137932, "alnum_prop": 0.7935267857142857, "repo_name": "code-not-found/spring-ws", "id": "8769d75fef82072e9c89c402310807f0c3f666ac", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-ws-ticketagent/src/main/java/com/codenotfound/ws/client/ClientConfig.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "223863" }, { "name": "Scala", "bytes": "620" } ], "symlink_target": "" }
package org.springframework.boot.test.autoconfigure.restdocs; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.autoconfigure.properties.PropertyMapping; import org.springframework.context.annotation.Import; /** * Annotation that can be applied to a test class to enable and configure * auto-configuration of Spring REST Docs. Allows configuration of the output directory * and the host, scheme, and port of generated URIs. When further configuration is * required a {@link RestDocsMockMvcConfigurationCustomizer} bean can be used. * * @author Andy Wilkinson * @since 1.4.0 * @see RestDocsAutoConfiguration * @see RestDocsMockMvcConfigurationCustomizer */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @ImportAutoConfiguration @Import(RestDocumentationContextProviderRegistrar.class) @PropertyMapping("spring.test.restdocs") public @interface AutoConfigureRestDocs { /** * The output directory to which generated snippets will be written. A synonym for * {@link #outputDir}. * @return the output directory */ String value() default ""; /** * The output directory to which generated snippets will be written. A synonym for * {@link #value}. * @return the output directory */ String outputDir() default ""; /** * The scheme (typically {@code http} or {@code https}) to be used in documented URIs. * Defaults to {@code http}. * @return the scheme */ String uriScheme() default "http"; /** * The host to be used in documented URIs. Defaults to {@code localhost}. * @return the host */ String uriHost() default "localhost"; /** * The port to be used in documented URIs. Defaults to {@code 8080}. * @return the port */ int uriPort() default 8080; }
{ "content_hash": "fca61a681a2a5537ea34f12237460f74", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 87, "avg_line_length": 29.80597014925373, "alnum_prop": 0.7546319479218828, "repo_name": "philwebb/spring-boot-concourse", "id": "b7f8dcfa3228eb8aa662024f37c420d8d78fb5ee", "size": "2617", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "main/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/restdocs/AutoConfigureRestDocs.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6954" }, { "name": "CSS", "bytes": "5769" }, { "name": "FreeMarker", "bytes": "2138" }, { "name": "Groovy", "bytes": "47595" }, { "name": "HTML", "bytes": "70103" }, { "name": "Java", "bytes": "9545541" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Ruby", "bytes": "1307" }, { "name": "SQLPL", "bytes": "40170" }, { "name": "Shell", "bytes": "20399" }, { "name": "Smarty", "bytes": "3276" }, { "name": "XSLT", "bytes": "34105" } ], "symlink_target": "" }