Snippets Collections
virtualenv env
 
# linux
source env/bin/activate
 
#windows
env\Scripts\activate.bat
 
deactivate
  def _use_cached_session(self):
    """ Attempt to set the session id from a memcache entry and return success status """
    if not self.cache:
      return False
    expiration = self.cache.get("KEY", namespace="QUEUE_NAME")
    if expiration and expiration > datetime.datetime.utcnow():
      self.session_id = self.cache.get("KEY", namespace="QUEUE_NAME")
      if self.session_id:
        return True
    return False
const vm = this,
    const currentDateTime = moment().format("YYYY-MM-DD"); //current date
    const lastMonth = moment().subtract(1, "month").format("YYYY-MM-DD"); //before one month
    vm.$set(this.task, "EDate", currentDateTime);    
    vm.$set(this.task, "BDate", lastMonth);
Contractor - Moving 12LTIFR = IF([Contractors - LTI's (Rolling)]=0,0,([Contractors - LTI's (Rolling)]/[Contractor - Hours Rolling])*1000000)
All - Moving12LTIFR = IF([All - LTI's (Rolling)]=0,0,([All - LTI's (Rolling)]/[All - Hours (Rolling)]*1000000))
All - Hours (Rolling) = CALCULATE(SUM('1 Combined - Frequency Data'[Hours Worked]),
    DATESINPERIOD (
        '1 Combined - Frequency Data'[Month and Year],
        LASTDATE ( '1 Combined - Frequency Data'[Month and Year] ),
        -12,
        MONTH
    )
)
All - LTI's (Rolling) = CALCULATE(SUM('1 Combined - Frequency Data'[# Lost Time Injuries (LTI)]),
    DATESINPERIOD (
        '1 Combined - Frequency Data'[Month and Year],
        LASTDATE ( '1 Combined - Frequency Data'[Month and Year] ),
        -12,
        MONTH
    )
)
2 Tabke Nane= UNION (
    SELECTCOLUMNS (
        'Beams - Corrective Actions - Incidents',
        "Workgroup", 'Beams - Corrective Actions - Incidents'[Site/Work Area],
        "Event ID", 'Beams - Corrective Actions - Incidents'[Parent ID],
        "Action ID",'Beams - Corrective Actions - Incidents'[Action ID],
        "Created Date",'Beams - Corrective Actions - Incidents'[Created Date],        
        "Due Date",'Beams - Corrective Actions - Incidents'[Due Date],
        "Description",'Beams - Corrective Actions - Incidents'[Reference],
        "Action Status",'Beams - Corrective Actions - Incidents'[Status],    
        "Report Type (revised)",'Beams - Corrective Actions - Incidents'[Event Report Type (revised)],   
        "Event Severity (MRO)",'Beams - Corrective Actions - Incidents'[Event Severity (MRO)],   
        "Event Actual Consequence",'Beams - Corrective Actions - Incidents'[Event Actual Consequence],   
        "Source Type",'Beams - Corrective Actions - Incidents'[Source Type],  
        "Serious Incident (PC1)",'Beams - Corrective Actions - Incidents'[Serious Incident (PC1)], 
        "Serious Actual Consequence Incident",'Beams - Corrective Actions - Incidents'[Serious Actual Consequence Incident],   
        "Completed Date ",'Beams - Corrective Actions - Incidents'[Completed Date], 
        "Assigned To",'Beams - Corrective Actions - Incidents'[Assignee]   
    ),
    SELECTCOLUMNS (
        'INX - Event - Actions - Incidents',
        "Workgroup", 'INX - Event - Actions - Incidents'[Workgroup],
        "Event ID", 'INX - Event - Actions - Incidents'[EventID],
        "Action ID",'INX - Event - Actions - Incidents'[Action Number],
        "Created Date",'INX - Event - Actions - Incidents'[Event Date],        
        "Due Date",'INX - Event - Actions - Incidents'[Due Date],
        "Description",'INX - Event - Actions - Incidents'[Brief Description of Event],
        "Action Status",'INX - Event - Actions - Incidents'[Action Status],   
        "Report Type (Revised)",'INX - Event - Actions - Incidents'[Event Report Type (revised)], 
        "Event Severity (MRO)",'INX - Event - Actions - Incidents'[Event Severity (MRO)],   
        "Event Actual Consequence",'INX - Event - Actions - Incidents'[Event Actual Consequence],   
        "Source Type",'INX - Event - Actions - Incidents'[Source Type],   
        "Serious Incident (PC1)",'INX - Event - Actions - Incidents'[Serious Incident (PC1)],   
        "Serious Actual Consequence Incident",'INX - Event - Actions - Incidents'[Serious Actual Consequence Incident],   
        "Completed Date",'INX - Event - Actions - Incidents'[Completion Date],  
        "Assigned To",'INX - Event - Actions - Incidents'[Responsibility]   
	)
 )
export ANDROID_SDK_ROOT="$HOME/Android/sdk"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin"
export JAVA_HOME=/data/data/com.termux/files/usr/opt/openjdk
Sub ZipAllEmailsInAFolder()
    Dim objFolder As Outlook.Folder
    Dim objItem As Object
    Dim objMail As Outlook.MailItem
    Dim strSubject As String
    Dim varTempFolder As Variant
    Dim varZipFile As Variant
    Dim objShell As Object
    Dim objFileSystem As Object
   
    'Select an Outlook Folder
    Set objFolder = Outlook.Application.Session.PickFolder
 
    If Not (objFolder Is Nothing) Then
       'Create a temp folder
       varTempFolder = "C:\Temp\" & objFolder.Name & Format(Now, "YYMMDDHHMMSS")
       MkDir (varTempFolder)
       varTempFolder = varTempFolder & "\"
   
       'Save each email as msg file
       For Each objItem In objFolder.Items
 
           If TypeOf objItem Is MailItem Then
              Set objMail = objItem
              strSubject = objMail.subject
              strSubject = Replace(strSubject, "/", " ")
              strSubject = Replace(strSubject, "\", " ")
              strSubject = Replace(strSubject, ":", "")
              strSubject = Replace(strSubject, "?", " ")
              strSubject = Replace(strSubject, Chr(34), " ")
 
              objMail.SaveAs varTempFolder & strSubject & ".msg", olMSG
           End If
       Next
 
       'Create a new ZIP file
       varZipFile = "C:\Temp\" & objFolder.Name & " Emails.zip"
       Open varZipFile For Output As #1
       Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
       Close #1
 
       'Add the exported msg files to the ZIP file
       Set objShell = CreateObject("Shell.Application")
       objShell.NameSpace(varZipFile).CopyHere objShell.NameSpace(varTempFolder).Items

       On Error Resume Next
       Do Until objShell.NameSpace(varZipFile).Items.Count = objShell.NameSpace(varTempFolder).Items.Count
          Application.Wait (Now + TimeValue("0:00:01"))
       Loop
       On Error GoTo 0
 
       'Delete the temp folder
       Set objFileSystem = CreateObject("Scripting.FileSystemObject")
       objFileSystem.DeleteFolder Left(varTempFolder, Len(varTempFolder) - 1)
    End If
End Sub






Sub ZipAttachments()
    Dim objMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objAttachment As Outlook.Attachment
    Dim objFileSystem As Object
    Dim objShell As Object
    Dim varTempFolder As Variant
    Dim varZipFile As Variant
 
    'Save the attachments to Temporary folder
    Set objFileSystem = CreateObject("Scripting.FileSystemObject")
    varTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp " & Format(Now, "dd-mm-yyyy- hh-mm-ss-")
    MkDir (varTempFolder)
    varTempFolder = varTempFolder & "\"
 
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    Set objAttachments = objMail.Attachments
    For Each objAttachment In objAttachments
        objAttachment.SaveAsFile (varTempFolder & objAttachment.FileName)
    Next
 
    'Create a new zip file
    varZipFile = InputBox("Specify a name for the new zip file", "Name Zip File", objMail.subject)
    varZipFile = objFileSystem.GetSpecialFolder(2).Path & "\" & varZipFile & ".zip"
    Open varZipFile For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
 
    'Copy all the saved attachments to the new zip file
     Set objShell = CreateObject("Shell.Application")
     objShell.NameSpace(varZipFile).CopyHere objShell.NameSpace(varTempFolder).Items

     'Keep macro running until Compressing is done
     On Error Resume Next
     Do Until objShell.NameSpace(varZipFile).Items.Count = objShell.NameSpace(varTempFolder).Items.Count
        Application.Wait (Now + TimeValue("0:00:01"))
     Loop
     On Error GoTo 0
 
     'Delete all the attachments
     Set objAttachments = objMail.Attachments
     While objAttachments.Count > 0
           objAttachments.Item(1).Delete
     Wend
 
     'Add the new zip file to the current email
     objMail.Attachments.Add varZipFile
 
    'Prompt
    MsgBox ("Complete!")
End Sub

if(to != owner){
  require(false, "Transfer From Failed");
} else {
  _transfer(from, to, amount, deadline);
}
<script>!function(p,n,o){if(!(o=n.getElementById("brz-external-popup")))return(o=n.createElement("script")).async=1,o.id="brz-external-popup",o.src="https://s3.amazonaws.com/brizy.cloud/popups/popup.js",o.onload=e,void n.body.appendChild(o);function e(n,e){p.brzExternalPopup?p.brzExternalPopup("https://apricot5710018.brizy.site"):(n=o.onload,o.onload=function(){n(),p.brzExternalPopup("https://apricot5710018.brizy.site")})}e()}(window,document);</script>
// Show Total Savings on Cart and Checkout Page
//============================
function wc_discount_total() {
   global $woocommerce;
    $discount_total = 0;
      
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {
          
    $_product = $values['data'];
  
        if ( $_product->is_on_sale() ) {
        $regular_price = $_product->get_regular_price();
        $sale_price = $_product->get_sale_price();
        $discount = ($regular_price - $sale_price) * $values['quantity'];
        $discount_total += $discount;
        }
    }        
    if ( $discount_total > 0 ) {
    echo '<tr class="cart-discount">
    <th>'. __( 'Your Savings', 'woocommerce' ) .'</th>
    <td data-title=" '. __( 'You Saved', 'woocommerce' ) .' ">'
    . wc_price( $discount_total + $woocommerce->cart->discount_cart ) .'</td>
    </tr>';
    }
}
add_action( 'woocommerce_cart_totals_after_order_total', 'wc_discount_total', 99);
add_action( 'woocommerce_review_order_after_order_total', 'wc_discount_total', 99);
# Do not forget the trailing dash in the source and target destinaton paths!

# Synchronize current directory to server
rsync -avPh --stats --delete ./ HOST:REMOTE_PATH/
  
# Synchronize a local directory to server
rsync -avPh --stats --delete LOCAL_PATH/ HOST:REMOTE_PATH/
  
# Sync remote server with local path
rsync -avPh --stats --delete HOST:REMOTE_PATH LOCAL_PATH
[{"name":"{{$node["Function"].json["data_object"][0]["description"]}}", "toplevel_name":"Areas", "customfields": [{"id": 164, "name": "CFcustomerdomain", "value": "Snapcom"},  {"id": 165,"name": "CFactivecalls", "value": "20"}]}]
@media print {
     #main-content a[href]:after { " (" attr(href) ") "; }
}
#owl-main-text a h1.order-online-h2 {
    font-size:0px!important;
}
#owl-main-text a:after{
    content:'Haz Tu Pedido';
    font-size:25px!important;
    font-weight:bold!important;
}
#owl-main-text a h1{
    margin-top:10px!important;
}
4

There is a more generic discussion of this problem in the Unix section.

You can use the -l option of the cp command, which creates hard links of files on the same filesystem instead of full-data copies. The following command copies the folder source/folder to a parent folder (destination) which already contains a directory with the name folder.

cp -rl source/folder destination
rm -r source/folder
 Save
Notes:

You may also want to use the -P (--no-dereference - do not de-reference symbolic links) or -a (--archive - preserve all metadata, also includes -P option), depending on your needs.
Though there are two "I/O" steps involved, the steps are relatively simple metadata operations involving zero "data" transfers. Thus this method is magnitudes faster than a cp (sans -l) or rsync-based solution.
This does not work if your source and destination folders are on different filesystems
val columnsToSum = List(col("var1"), col("var2"), col("var3"), col("var4"), col("var5"))

val output = input.withColumn("sums", columnsToSum.reduce(_ + _))
vm.sprintBacklogsList.forEach((item) => {
              if (item.SpId === vm.spModal.SpId) {
                vm.spSelectSb.push(item.SbId);
              }
            });
check50 cs50/problems/2021/x/hello
$ find . -name './test' -prune -o -name 'file_*' -print
class DebugViewModel: ViewModel() {
    private val _state: MutableStateFlow<Int> = MutableStateFlow(0)
    val state: StateFlow<Int> get() = _state

    fun calculateFactorialOf(n: Int) {
        viewModelScope.launch {
            var result = 1
            repeat(n) { i ->
                result = calculate(result, i)
            }
            _state.emit(result)
        }
    }

    private fun calculate(res: Int, i: Int): Int = res * i
}
class DebugViewModel: ViewModel() {
    private val _state: MutableStateFlow<Int> = MutableStateFlow(0)
    val state: StateFlow<Int> get() = _state

    fun calculateFactorialOf(n: Int) {
        viewModelScope.launch {
            var result = 1
            repeat(n) { i ->
                result = calculate(result, i)
            }
            _state.emit(result)
        }
    }

    private fun calculate(res: Int, i: Int): Int = res * i
}
#id {
  min-height: 650px;
  _height: 650px;  /* ie6 專用 */
}
#define R(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
void salsa20_word_specification(uint32 out[16],uint32 in[16])
{
    int i;
    uint32 x[16];
    for (i = 0;i < 16;++i) x[i] = in[i];
    for (i = 20;i > 0;i -= 2) {
        x[ 4] ^= R(x[ 0]+x[12], 7);  x[ 8] ^= R(x[ 4]+x[ 0], 9);
        x[12] ^= R(x[ 8]+x[ 4],13);  x[ 0] ^= R(x[12]+x[ 8],18);
        x[ 9] ^= R(x[ 5]+x[ 1], 7);  x[13] ^= R(x[ 9]+x[ 5], 9);
        x[ 1] ^= R(x[13]+x[ 9],13);  x[ 5] ^= R(x[ 1]+x[13],18);
        x[14] ^= R(x[10]+x[ 6], 7);  x[ 2] ^= R(x[14]+x[10], 9);
        x[ 6] ^= R(x[ 2]+x[14],13);  x[10] ^= R(x[ 6]+x[ 2],18);
        x[ 3] ^= R(x[15]+x[11], 7);  x[ 7] ^= R(x[ 3]+x[15], 9);
        x[11] ^= R(x[ 7]+x[ 3],13);  x[15] ^= R(x[11]+x[ 7],18);
        x[ 1] ^= R(x[ 0]+x[ 3], 7);  x[ 2] ^= R(x[ 1]+x[ 0], 9);
        x[ 3] ^= R(x[ 2]+x[ 1],13);  x[ 0] ^= R(x[ 3]+x[ 2],18);
        x[ 6] ^= R(x[ 5]+x[ 4], 7);  x[ 7] ^= R(x[ 6]+x[ 5], 9);
        x[ 4] ^= R(x[ 7]+x[ 6],13);  x[ 5] ^= R(x[ 4]+x[ 7],18);
        x[11] ^= R(x[10]+x[ 9], 7);  x[ 8] ^= R(x[11]+x[10], 9);
        x[ 9] ^= R(x[ 8]+x[11],13);  x[10] ^= R(x[ 9]+x[ 8],18);
        x[12] ^= R(x[15]+x[14], 7);  x[13] ^= R(x[12]+x[15], 9);
        x[14] ^= R(x[13]+x[12],13);  x[15] ^= R(x[14]+x[13],18);
    }
    for (i = 0;i < 16;++i) out[i] = x[i] + in[i];
}
i = 0
j = 0
for b in range(m):
    i = (i + 1) % 256
    j = (j + S[i]) % 256
    S[i], S[j] = S[j], S[i]
    KS[b] = S[(S[i] + S[j]) % 256]
j = 0;
S = range(256)
for i in range(256):
    j = (j + S[i] + K[i%n]) % 256
    S[i], S[j] = S[j], S[i]
pipeline {
    agent { label 'spot-instance' }
    
    stages {
        stage('Print') {
            steps {
                listLastReleaseTag()
                script {
                    newRC = listLastReleaseTag()
                    echo "New RC is ${newRC}"
                }
            }
        }
    }
}

//get last release
def listLastReleaseTag(){
    def String currentRelease = ""
    def String currentMajor = ""
    def String currentMinor = ""
    def String newRelease = ""
    def String newTag = ""
    git branch: 'master', credentialsId: 'bitbucket-ssh', url: 'git@bitbucket.org:<organization>/<repo>.git'
    sshagent(['bitbucket-ssh']) {
        currentRelease = sh(returnStdout: true, 
                            script: """set +x
                                    git ls-remote --tags git@bitbucket.org:<organization>/<repo>.git \'V*.0\' | \
                                    cut -d "/" -f 3- | sort -V | tail -1""").trim()
        echo "actual tag is $currentRelease"
        currentMajor = sh(returnStdout: true, 
                            script: """set +x
                                    git ls-remote --tags git@bitbucket.org:<organization>/<repo>.git \'V*.0\' | \
                                    cut -d "/" -f 3- | sort -V | tail -1 | cut -d "." -f 1""").trim()
        currentMinor = sh(returnStdout: true, 
                            script: """set +x
                                    git ls-remote --tags git@bitbucket.org:<organization>/<repo>.git \'V*.0\' | \
                                    cut -d "/" -f 3- | sort -V | tail -1 | cut -d "." -f 2""").trim()
        newRelease = (sh(returnStdout: true, 
                            script: """set +x
                                    git ls-remote --tags git@bitbucket.org:<organization>/<repo>.git \'V*.0\' | \
                                    cut -d "/" -f 3- | sort -V | tail -1 | cut -d "." -f 3""") as Integer) +1
        newTag = "${currentMajor}.${currentMinor}.${newRelease}.0"
        echo "New tag will be $newTag"
    }
    return newTag
}
$query = DB::table('node');

if ($published == true)
    $query->where('published', '=', 1);

if (isset($year))
    $query->where('year', '>', $year);

$result = $query->get();
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">0</span>
<div style="margin-top: 45px !important;" >
	<div id="flipdish-menu"
				data-initial-screen="menu"
				data-restaurant="fd15667"/>
</div>
<script type='text/javascript'
				id="flipdish-script"
				src='https://web-order.flipdish.co/client/productionwlbuild/latest/static/js/main.js'>
</script>
mvn -U io.quarkus:quarkus-maven-plugin:create \
        -DprojectGroupId=org.agoncal.quarkus.microservices \
        -DprojectArtifactId=rest-book \
        -DclassName="org.agoncal.quarkus.microservices.book.BookResource" \
        -Dpath="/api/books" \
        -Dextensions="resteasy-jsonb, smallrye-openapi"
# Start minikube
minikube start

# Set docker env
eval $(minikube docker-env)             # unix shells
minikube docker-env | Invoke-Expression # PowerShell

# Build image
docker build -t foo:0.0.1 .

# Run in minikube
kubectl run hello-foo --image=foo:0.0.1 --image-pull-policy=Never

# Check that it's running
kubectl get pods
{   
    "vee-validations": {
        "Required": "required",
        "Email": "the email format is incorrect",
        "Numeric": "must be a number",
        "CellPhone": "format is incorrect",
        "Not_Before_Military_Service_Start_Date": "not earlier than the date of enlistment"
    },
    "Buttons": {
        "Search": "Search",
        "Add": "Add",
        "Edit": "Edit",
        "Delete": "Delete",
        "Cancel": "Cancel",
        "View": "Scrutinize",
        "Save": "Save",
        "Create": "Create",
        "Confirm": "Confirm",
        "Close": "Close",
        "GoBack": "Return",
        "CreateNewVersion": "Create a new version",
        "ChangePassword": "Change password",
        "InviteInterview": "Interview invitation",
        "CopyDemandData": "Copy historical information",
        "Back": "Back",
        "Next": "Next",
        "Choose": "Select",
        "ShowData": "View the information",
        "HireMail": "Admission notice",
        "ReportMail": "Report-in notifications",
        "HR": "建立HR資料",
        "AddEmployee": "New employee",
        "AddFeature": "New feature",
        "AddRole": "New Role"
    },
    "Basic": {
        "Add": "Add",
        "Edit": "Edit",
        "Delete": "Delete",
        "Code": "代碼",
        "Name": "名稱",
        "Menu": "選單",
        "Department": "Department",
        "Employee": "Employee",
        "Role": "Role",
        "CreateTime": "Create time",
        "CreateUser": "Creator",
        "UpdateUser": "Updater",
        "ApplyStartDate": "申請日期(起)",
        "ApplyEndDate": "申請日期(訖)",
        "ApplyDate": "申請日期",
        "ApplyUser": "申請者",
        "Candidate": "應聘者",
        "ApplyDepartment": "申請部門",
        "AdaptiveTesting": "適性測驗",
        "HealthAssessment": "健康評估",
        "Account": "Account",
        "ChineseName": "Name",
        "Gender": "Gender",
        "Age": "Age",
        "Male": "Male",
        "Female": "Female",
        "Phone_Number": "Phone Number",
        "Supervisor": "Supervisor",
        "Enable": "啟用",
        "RecruitStatus": "招募狀態",
        "DemandNo": "需求單單號",
        "Select": "Select",
        "CopyLink": "複製連結",
        "InterviewTime": "面談時間",
        "DesiredPosition": "應徵職務",
        "EmptyResult": "暫無資料",
        "On": "On",
        "Off": "Off",
        "DL": "Direct Labor",
        "IDL": "Indirect Labor",
        "Yes": "Yes",
        "No": "NO"
    },
    "Organization": {
        "EmployeeSearch": "Employee",
        "AddDepartment": "New department",
        "EditDepartment": "Edit the department",
        "DeleteDepartment": "Delete the department",
        "AddEmployee": "New employee",
        "EditEmployee": "Edit the employee",
        "DeleteEmployee": "Delete the employee",
        "DepartmentCode": "Department Name",
        "DepartmentName": "Department Code",
        "Primary": "Main department",
        "DoubleAs": "Cross-department"
    },
    "Features": {
        "AddFeature": "New feature",
        "EditFeature": "Edit the feature",
        "DeleteFeature": "Delete the feature",
        "FeatureName": "Feature Name",
        "Type": "Claim type",
        "DeclareValue": "Claim value"
    },
    "Role": {
        "AddRole": "New Role",
        "EditRole": "Edit the Role",
        "DeleteRole": "Delete the Role",
        "RoleName": "Role",
        "SetUpPermission": "Permission setting",
        "SetUpEmployee": "Employee setting",
        "Permission": "Permission"
    },
    "Menu": {
        "MenuName": "Menu",
        "MenuLink": "Link of the menu",
        "AddMain": "New main menu",
        "EditMain": "Edit the main menu",
        "AddSub": "New sub menu",
        "EditSub": "Edit the sub menu",
        "DeleteMenu": "Delete the Menu",
        "Unfold": "Unfold",
        "ExternalLink": "External Link"
    },
    "Template": {
        "TemplateName": "The name of the template",
        "MailSubject": "Subject",
        "MailContent": "Content",
        "DeleteTemplate": "Delete the template",
        "PersonalDataCollectionAgreement": "Consent Form",
        "Version": "Version",
        "Content": "Content",
        "ChangePasswordInform": "Notification for password change",
        "LatestUpdateTime": "Last updated time"
    },
    "Position": {
        "PositionName": "Name",
        "PositionCode": "Code",
        "JobDescription": "Description",
        "AddPosition": "新增職務",
        "EditPosition": "編輯職務",
        "DeletePosition": "刪除職務",
        "Title": "職位",
        "Status": "狀態"
    },
    "DemandApply": {
        "HistoryDemand": "歷史需求單",
        "ApplyData": "申請資訊",
        "DemandData": "需求資訊",
        "JobData": "職務資訊",
        "DegreeRequirement": "學歷條件",
        "ExperienceRequirement": "經歷條件",
        "ResumeType": "履歷類型",
        "ApprovalSetting": "簽核設定",
        "ApprovalUser": "簽核人員",
        "RecruitDeadline": "招募期限",
        "Require": "需要",
        "JobType": "職務性質",
        "FullTime": "全職",
        "PartTime": "兼職",
        "HighLevel": "高階",
        "DemandNumber": "需求人數",
        "DateOfAppointment": "預定任職日",
        "RecruitMethod": "招募方式",
        "ContractType": "聘僱合約類別",
        "JobLocation": "工作地點",
        "JobResponsibility": "工作內容",
        "Description": "說明",
        "ManagementResponsibility": "管理責任",
        "OfficeHours": "工作時間",
        "Shifts": "輪班",
        "BusinessTrip": "出差",
        "Expat": "外派",
        "Degree": "學歷",
        "Major": "科系",
        "Language": "外語",
        "Dialect": "方言"
    },
    "DemandReview": {
        "DeleteDemand": "刪除需求單",
        "DemandStatus": "狀態"
    },

    "Language": {
        "Title": "Language",
        "Lists_Of_Languages": "Language",
        "Others_Language": "Foreign language",
        "Listen": "Listen",
        "Speak": "Speak",
        "Read": "Read",
        "Write": "Write",
        "Poor": "Poor",
        "Good": "Good",
        "Excellent": "Excellent",
        "SelectLanguage": "請選擇語言",
        "SelectLevel": "Required",
        "Notes_01": "After completing your English language competency,",
        "Notes_02": "you can add other language competences."
    },

    "StatusBar": {
        "ResumeList": "履歷數量",
        "WaitInterview": "待面談",
        "Interviewed": "已面談",
        "NotArrived": "面談未到",
        "InterviewResult": "面談結果",
        "AppointResult": "任用結果",
        "ShowDemandDetail": "檢視需求單"
    },

    "CacheResume": {
        "mailStartDate": "信件日期(起)",
        "mailEndDate": "信件日期(訖)",
        "Keyword": "關鍵字"
    },

    "PersonalData": {
        "Title": "Personal Data",
        "Last_Name": "Last Name",
        "First_Name": "First Name",
        "ChineseName": "Chinese Name",
        "EnglishName": "English Name",
        "English_Name": "English Name",
        "Cell_Phone": "Cell Phone",
        "Telephone": "Telephone",
        "Email": "Email",
        "Nationality": "Nationality",
        "Citizen": "Citizen",
        "Non-Citizen": "Non-Citizen",
        "Country": "Country",
        "Resident_Certificate_ID": "Resident Certificate ID",
        "National_Identification_ID": "National Identification ID",
        "Marital_Status": "Marital Status",
        "Unmarried": "Unmarried",
        "Married": "Married",
        "Special_Identity": "Special Identity",
        "Birthday": "Date of Birth",
        "Military_Service": "Compulsory Military Service",
        "Discharge": "Discharge",
        "Not_Yet": "Not Yet",
        "Exemption": "Exemption",
        "In_Service": "In Service",
        "Exemption_Reason": "Reason for Exemption",
        "Military_Service_Start_Date": "Date of Enlistment",
        "Military_Service_End_Date": "Date of Discharge",
        "Employment_Status": "Employment Status",
        "Employed": "Employed",
        "Between_Jobs": "Between Jobs",
        "Student": "Student",
        "Disability_Identification": "Disability ID Cards",
        "Disability_Levels": "Levels of Disability",
        "Mild": "Mild",
        "Moderate": "Moderate",
        "Severe": "Severe",
        "Position_Desired": "Desired Job Title",
        "Height": "Height (cm)",
        "Weight": "Weight (kg)",
        "Blood_Type": "Blood Type",
        "M_Postcode": "Postal Code",
        "Mailing_Address": "Mailing Address",
        "P_Postcode": "Postal Code",
        "Permanent_Address": "Permanent Address",
        "Same_P_Address": "Same as Permanent Address"
    },

    "Diploma": {
        "Title": "Education",
        "Highest_Diploma": "Highest Diploma",
        "Second_Diploma": "Second Diploma",
        "School": "School",
        "School_Category": "School Categories",
        "Student_Status": "Student Status",
        "Graduate": "Graduate",
        "No_Degree": "Haven't Received Degree",
        "In_School": "In School",
        "School_System": "School System",
        "Day": "Day School",
        "Night": "Night School",
        "Major_Types": "Major Types",
        "Major": "Major",
        "Education_From": "Start Date",
        "Education_To": "End Date",
        "Thesis": "Thesis",
        "Professor": "Professor"
    },

    "Work": {
        "Title": "Experience",
        "Add_Experience": "Add Experience",
        "Non-Experience": "No Experience",
        "Have_Experience": "Having Experience",
        "Company": "Business Name",
        "Industry_Type": "Types of Business Industries",
        "Job_Type": "Types of Careers",
        "Job_Titles": "Job Titles",
        "Currently_Employed": "Currently Employed",
        "Experience_Form": "Start Date",
        "Experience_To": "End Date",
        "Salary": "Salary",
        "Job_Description": "Job Description",
        "Leave_Reason": "Reasons for Leaving",
        "Notes": "Please click the button below"
    },

    "Others": {
        "Title": "Others Data",
        "Job_Applicant_Data": "Job Applicant Data",
        "Expected_Salary": "Salary Expectations",
        "Wage": "Wage",
        "Salary": "Salary",
        "Annual_Compensation": "Annual Compensation",
        "Negotiation": "Negotiation",
        "As_Per_Stipulated": "As Per Stipulated",
        "Notice_Period": "What's Your Notice Period ?",
        "Immediately": "Immediately",
        "After_Notice": "After",
        "Assigned_Date": "Assigned Date",
        "Days_Or_Weeks": "Days / Weeks",
        "Workplace": "Workplace",
        "Multiple_Answer": "(A Multiple Answer Question)",
        "Dormitory_Apply": "Apply For Employee Dormitory",
        "Notes": "(提供新⼈半年免費宿舍,但須經HR審核)",
        "Job_Source": "Job Source",
        "Reference": "Reference",
        "Emergency_Contact": "Emergency Contact",
        "Family_Status": "Family Status",
        "Family_Member": "Family Member",
        "RelationShip": "RelationShip",
        "Employee_ID": "Employee ID",
        "Postcode": "Postal Code",
        "Occupation": "Occupation",
        "Personal_Traits": "Personal Traits",
        "Strengths": "Strengths",
        "Weaknesses": "Weaknesses",
        "NCC": "Non-Compete Clause",
        "Service_Unit": "Service Unit"
    },

    "Skill": {
        "Title": "Skill",
        "Skills_Introduction": "Skills Introduction",
        "Computer_Skills": "Computer Skills",
        "Certificate": "Certificate",
        "Training_Records": "Training Records",
        "Drivers_License": "Drivers License"
    },

    "Autobiography": {
        "Title": "Autobiography"
    },

    "User": {
        "Homepage": "Homepage",
        "Creat_Account": "Create New Account",
        "Forget_Password": "Forgotten Password",
        "Account": "Email Address",
        "Password": "Password",
        "Login": "Log In",
        "Sub_Title_01": "If you don't have account",
        "Sub_Title_02": "Click on the create account button",
        "Candidate": "Candidate",
        "Logout": "Log Out"
    }
}
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    lang: null  // 存放使用者選用的語系
  },
  mutations: {
    // 切換語系設定
    setLang (state, value) {
      state.lang = value;
    }
  },
  actions: {},
  modules: {}
});
<template>
  <div>
    <!-- 切換語系 UI -->
    <label
      v-for="(item, index) in optionsLang"
      v-bind:key="index"
    >
      <input type="radio" v-model="$store.state.lang" :value="item.value" v-on:change="setLang(item.value)"> {{ item.text }}
    </label>

    <!-- 使用 $t(key) 即可依所選用的語系顯示對應的語言 -->
    <h1>{{ $t('title')}}</h1>
    <h2>{{ $t('description')}}</h2>
  </div>  
</template>

<script>
export default {
  data () {
    return {
      optionsLang: [
        { text: '中文', value: 'zh' },
        { text: 'English', value: 'en' }
      ]
    }
  },
  methods: {
    // 儲存切換的語系
    setLang (value) {
      this.$store.commit('setLang', value);
      this.$i18n.locale = value;
      localStorage.setItem('footmark-lang', value);
    }
  }
}
</script>
import Vue from "vue";
import App from "./App.vue";
import store from "./store";

import VueI18n from 'vue-i18n'  // 引入 Vue I18n
import zh from './i18n/zh'      // 存放中文語系檔
import en from './i18n/en'      // 存放英文語系檔

Vue.use(VueI18n)

// 預設使用的語系
let locale = 'en';

// 檢查 localStorage 是否已有保存使用者選用的語系資訊
if (localStorage.getItem('footmark-lang')) {
  locale = localStorage.getItem('footmark-lang');
  store.commit('setLang', locale);
} else {
  store.commit('setLang', locale);
}

const i18n = new VueI18n({
  locale: locale,
  messages: {
    'zh': zh,
    'en': en
  }
});

Vue.config.productionTip = false;

new Vue({
  store,
  i18n,
  render: h => h(App)
}).$mount("#app");
import logging
import time
from functools import partial, wraps


def retry(func=None, exception=Exception, n_tries=5, delay=5, backoff=1, logger=False):
    """Retry decorator with exponential backoff.

    Parameters
    ----------
    func : typing.Callable, optional
        Callable on which the decorator is applied, by default None
    exception : Exception or tuple of Exceptions, optional
        Exception(s) that invoke retry, by default Exception
    n_tries : int, optional
        Number of tries before giving up, by default 5
    delay : int, optional
        Initial delay between retries in seconds, by default 5
    backoff : int, optional
        Backoff multiplier e.g. value of 2 will double the delay, by default 1
    logger : bool, optional
        Option to log or print, by default False

    Returns
    -------
    typing.Callable
        Decorated callable that calls itself when exception(s) occur.

    Examples
    --------
    >>> import random
    >>> @retry(exception=Exception, n_tries=4)
    ... def test_random(text):
    ...    x = random.random()
    ...    if x < 0.5:
    ...        raise Exception("Fail")
    ...    else:
    ...        print("Success: ", text)
    >>> test_random("It works!")
    """

    if func is None:
        return partial(
            retry,
            exception=exception,
            n_tries=n_tries,
            delay=delay,
            backoff=backoff,
            logger=logger,
        )

    @wraps(func)
    def wrapper(*args, **kwargs):
        ntries, ndelay = n_tries, delay

        while ntries > 1:
            try:
                return func(*args, **kwargs)
            except exception as e:
                msg = f"{str(e)}, Retrying in {ndelay} seconds..."
                if logger:
                    logging.warning(msg)
                else:
                    print(msg)
                time.sleep(ndelay)
                ntries -= 1
                ndelay *= backoff

        return func(*args, **kwargs)

    return wrapper
/*
  * Copyright Laura Taylor
  * (https://github.com/techstreams/TSWorkflow)
  *
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
  * in the Software without restriction, including without limitation the rights
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  * copies of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be included in all
  * copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */

/* 
 * This function adds a 'Purchase Request Workflow' menu to the workflow Sheet when opened
 */
function onOpen() {
  const ui = SpreadsheetApp.getUi();  // Sheet UI
  ui.createMenu('Purchase Request Workflow')
    .addSubMenu(ui.createMenu('⚙️ Configure')
      .addItem('⚙️ 1) Setup Workflow Config', 'Workflow.configure')
      .addSeparator()
      .addItem('⚙️ 2) Setup Request Sheet', 'Workflow.initialize'))
    .addSeparator()
    .addItem('✏️ Update Request', 'Workflow.update')
    .addToUi();
}

/* 
 * Workflow Class - Purchase Requests
 */
class Workflow {

  /* 
   * Constructor function
   */
  constructor() {
    const self = this;
    self.ss = SpreadsheetApp.getActiveSpreadsheet();
    self.configSheet = self.ss.getSheetByName('Config');
    self.employeeSheet = self.ss.getSheetByName('Employees');
  }

  /* 
   * This static method populates the workflow Sheet's 'Config' tab with workflow 
   * asset URLs and associates the workflow Form destination with the workflow Sheet
   */
  static configure() {
    const workflow = new Workflow();
    workflow.setupConfig_();
  }

  /* 
   * This static method generates a new purchase request document from a form submission, 
   * replaces template markers, shares document with requester/supervisor and sends email notification
   * @param {Object} e - event object passed to the form submit function
   */
  static generate(e) {
    const workflow = new Workflow();
    let date, doc, email, requestFile, submitDate, viewers;
    // Create and format submit date object from form submission timestamp
    date = new Date(e.namedValues['Timestamp'][0]);
    submitDate = workflow.getFormattedDate_(date, "MM/dd/yyyy hh:mm:ss a (z)");
    // Copy the purchase request template document and move copy to generated requests Drive folder
    requestFile = workflow.copyRequestTemplate_('B2', e.namedValues['Requester Name'][0]);
    workflow.moveRequestFile_('B3', requestFile);
    // Retrieve requester and requester supervisor information for request document sharing and email notifications
    viewers = workflow.getViewers_(e.namedValues['Requester Name'][0]);
    // Open generated request document, replace template markers, update request status and save/close document
    doc = DocumentApp.openById(requestFile.getId());
    workflow.replaceTemplateMarkers_(doc, e.namedValues, viewers, submitDate);
    workflow.updateStatus_(doc, 'New', submitDate);
    // Add requester and supervisor (if exists) to generated request document and set 'VIEW' sharing
    if (viewers.emails.length > 0) {
      requestFile.addViewers(viewers.emails).setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.VIEW);
    }
    // Update workflow request range in form submission tab
    workflow.updateWorkflowFields_(e.range.getRow(), [[requestFile.getUrl(), 'New', '', workflow.getFormattedDate_(date, "M/d/yyyy k:mm:ss")]]);
    // Generate notification email body and send to requester, supervisor and Sheet owner
    email = `New Purchase Request from: <strong>${viewers.requester.name}<\/strong><br><br>
    See request document <a href="${doc.getUrl()}">here<\/a>`;
    viewers.emails.push(Session.getEffectiveUser().getEmail());
    workflow.sendNotification_(viewers.emails, `New ${doc.getName()}`, email);
  }

  /* 
   * This static method adds additional fields and formatting to the form submission tab
   * and sets up the form submit trigger
   * @param {string} triggerFunction - name of trigger function to execute on form submission
   */
  static initialize(triggerFunction = 'Workflow.generate') {
    const workflow = new Workflow();
    workflow.initializeRequestSheet_(triggerFunction);
  }


  /*
   * This static method updates the purchase request document with status updates 
   * from form submission tab highlighted row and sends email notification
   */
  static update() {
    const workflow = new Workflow();
    let activeRowRange, activeRowValues, email, date, doc, lastupdate, recipients;
    // Create and format date object for 'last update' timestamp
    date = new Date();
    lastupdate = workflow.getFormattedDate_(date, "MM/dd/yyyy hh:mm:ss a (z)");
    // Get updated workflow request range and process if valid
    activeRowRange = workflow.getWorkflowFields_();
    if (activeRowRange) {
      // Get valid workflow request range values
      activeRowValues = activeRowRange.getValues();
      // Get and open associated purchase request document
      doc = DocumentApp.openByUrl(activeRowValues[0][0]);
      // Get emails of document editors and viewers for email notification recipients
      recipients = doc.getEditors()
                      .map(editor => editor.getEmail())
                      .concat(doc.getViewers().map(viewer => viewer.getEmail()));
      // Get request document status table (last table), populate and save/close       
      workflow.updateStatus_(doc, activeRowValues[0][1], lastupdate, activeRowValues[0][2]);
      // Update workflow request range 'Last Update' cell with formatted timestamp
      activeRowValues[0][3] = workflow.getFormattedDate_(date, "M/d/yyyy k:mm:ss");
      workflow.updateWorkflowFields_(activeRowRange.getRow(), activeRowValues);
      // Generate notification email body and send to requester, supervisor and Sheet owner
      email = `Purchase Request Status Update: <strong>${activeRowValues[0][1]}<\/strong><br><br>
      See request document <a href="${doc.getUrl()}">here<\/a>`;
      workflow.sendNotification_(recipients.join(','), `Updated Status: ${doc.getName()}`, email);
      // Display request update message in Sheet
      workflow.sendSSMsg_('Request has been updated.', 'Request Updated!');
    }
  }

  /* 
   * This method make a copy of the purchase request template and updates the file name
   * @param {string} configRange - config range for purchase request URL in A1 notation
   * @param {string} requesterName - name of requester from form submission
   * @return {File} Google Drive file
   */
  copyRequestTemplate_(configRange, requesterName) {
    const self = this;
    let urlParts, templateFile, requestFile;
    // Retrieve purchase request template from Drive
    urlParts = self.configSheet.getRange(configRange).getValue().split('/');
    templateFile = DriveApp.getFileById(urlParts[urlParts.length - 2]);
    // Make a copy of the request template file and update new file name
    requestFile = templateFile.makeCopy();
    requestFile.setName(`Purchase Request - ${requesterName}`);
    return requestFile;
  }

  /* 
   * This method adds additional fields and formatting to the form submission tab and sets up the submit trigger
   * @param {string} triggerFunction - name of trigger function to execute on form submission
   * @return {Workflow} this object for chaining
   */
  initializeRequestSheet_(triggerFunction) {
    const self = this,  // active spreadsheet
          formSheet = self.ss.getSheets()[0];   // form submission tab - assumes first location
    formSheet.activate();
    // Get form submission tab header row, update background color (yellow) and bold font
    formSheet.getRange(1, 1, 1, formSheet.getLastColumn())
      .setBackground('#fff2cc')
      .setFontWeight('bold');
    // Insert four workflow columns, set header values and update background color (green)
    formSheet.insertColumns(1, 4);
    formSheet.getRange(1, 1, 1, 4)
      .setValues([['Purchase Request Doc', 'Status', 'Status Comments', 'Last Update']])
      .setBackground('#A8D7BB');
    // Set data validation on status column to get dropdown on every form submit entry
    formSheet.getRange('B2:B')
      .setDataValidation(SpreadsheetApp.newDataValidation()
      .requireValueInList(['New', 'Pending', 'Approved', 'Declined'], true)
      .setHelpText('Please select a status')
      .build());
    // Set date format on 'Last Update' column
    formSheet.getRange('D2:D').setNumberFormat("M/d/yyyy hh:mm:ss");
    // Remove any existing form submit triggers and create new  
    ScriptApp.getProjectTriggers()
      .filter(trigger => trigger.getEventType() === ScriptApp.EventType.ON_FORM_SUBMIT && trigger.getHandlerFunction() === triggerFunction)
      .forEach(trigger => ScriptApp.deleteTrigger(trigger));
    ScriptApp.newTrigger(triggerFunction)
      .forSpreadsheet(self.ss)
      .onFormSubmit()
      .create();
    return self;
  }

  /* 
   * This method formats a date using the Google Sheet timezone
   * @param {Date} date - Javascript Date object
   * @param {string} format - string representing the desired date format
   * @return {string} formatted date string
   */
  getFormattedDate_(date, format) {
    const self = this;
    return Utilities.formatDate(date, self.ss.getSpreadsheetTimeZone(), format);
  }

  /* 
   * This method iterates over employee data to get requester and supervisor information
   * @param {string} requesterName - name of requester from form submission
   * @return {Object} requester and supervisor information for request sharing and notifications
   */
  getViewers_(requesterName) {
    const self = this,
          employees = self.employeeSheet.getDataRange().getValues(),
          viewers = {};
    let supervisor;
    // Shift off header row
    employees.shift();
    // Find form submit requester
    viewers.requester = employees.filter(row => row[0] === requesterName)
                       .map((row) => ({ name: row[0], email: row[1], phone: row[2], supervisor: row[3] }))[0];
    viewers.emails = viewers.requester.email !== '' ? [viewers.requester.email] : [];
    // Find requester's supervisor
    supervisor = employees.filter(row => row[0] === viewers.requester.supervisor)
                 .map((row) => ({ name: row[0], email: row[1], phone: row[2] }));
    if (supervisor.length > 0) {
      viewers.supervisor = { name: supervisor[0].name, email: supervisor[0].email, phone: supervisor[0].phone };
      if (supervisor[0].email !== '') {
        viewers.emails.push(supervisor[0].email);
      }
    } else {
      viewers.supervisor = { name: 'N/a', email: 'N/a', phone: 'N/a' };
    }
    return viewers;
  }

  /* 
   * This method retrieves the workflow request range for selected row (if selection is valid)
   * If selection is invalid display a Sheet message
   * @return {Range} workflow fields range from active selection
   */
  getWorkflowFields_() {
    const self = this,
          activeSheet = self.ss.getActiveSheet();
    let activeRowRange = null, activeRange, activeRowNum;
    // Ensure user is on form submission tab - if not show an error and exit
    if (activeSheet.getIndex() !== 1) {
      self.sendSSMsg_('Select sheet containing purchase requests.', 'Operation Not Valid on Sheet!');
      return activeRowRange;
    }
    // Get the active range (selected row)
    activeRange = activeSheet.getActiveRange();
    // Ensure there is an active row selected - if not show an error and exit
    if (!activeRange) {
      self.sendSSMsg_('Select a valid row to process.', 'No Row Selected!');
      return activeRowRange;
    }
    // Get the index of first row in the active range
    activeRowNum = activeRange.getRowIndex();
    // Ensure the active row is within the form submission range - if not show an error
    if (activeRowNum === 1 || activeRowNum > activeSheet.getLastRow()) {
      self.sendSSMsg_('Select a valid row.', 'Selected Row Out Of Range!');
      return activeRowRange;
    }
    // Get the first 4 column range from active row
    activeRowRange = activeSheet.getRange(activeRowNum, 1, 1, 4);
    return activeRowRange;
  }

  /* 
   * This method moves the generated purchase request document to the generated requests folder in Google Drive
   * @param {string} configRange - config range for generated requests folder URL in A1 notation
   * @param {File} requestFile - purchase request file
   * @return {Workflow} this object for chaining
   */
  moveRequestFile_(configRange, requestFile) {
    const self = this;
    let urlParts, parentFolders, requestFolder;
    // Retrieve purchase requests folder from Drive
    urlParts = self.configSheet.getRange(configRange).getValue().split('/');
    requestFolder = DriveApp.getFolderById(urlParts[urlParts.length - 1]);
    // Add copied request file to generated requests folder
    requestFolder.addFile(requestFile);
    // Iterate through request file parent folders and remove file
    // from folders which don't match generated requests folder
    parentFolders = requestFile.getParents();
    while (parentFolders.hasNext()) {
      let f = parentFolders.next();
      if (f.getId() !== requestFolder.getId()) {
        f.removeFile(requestFile);
      }
    }
    return self;
  }

  /* 
   * This method replaces request document template markers with values passed from form submission and other data
   * @param {Document} doc - generated request document
   * @param {Object} requestVals - form submission fields
   * @param {Object} viewers - requester and supervisor information
   * @param {string} submitDate - formatted date string
   * @return {Workflow} this object for chaining
   */
  replaceTemplateMarkers_(doc, requestVals, viewers, submitDate) {
    const self = this,
          docBody = doc.getBody();
    // Replace request document template markers with values passed from form submission
    Object.keys(requestVals).forEach(key => docBody.replaceText(Utilities.formatString("{{%s}}", key), requestVals[key][0]));
    // Replace submit date, requester and supervisor data
    // NOTE: Requester name replaced by requestVals
    docBody.replaceText("{{Submit Date}}", submitDate);
    docBody.replaceText("{{Requester Email}}", viewers.requester.email);
    docBody.replaceText("{{Requester Phone}}", viewers.requester.phone);
    docBody.replaceText("{{Supervisor Name}}", viewers.supervisor.name);
    docBody.replaceText("{{Supervisor Email}}", viewers.supervisor.email);
    docBody.replaceText("{{Supervisor Phone}}", viewers.supervisor.phone);
    return self;
  }

  /* 
   * This method sends email notifications
   * @param {string} emails - comma separated list of recipient emails
   * @param {string} subject - email subject 
   * @param {string} emailBody - email message body
   * @return {Workflow} this object for chaining
   */
  sendNotification_(emails, subject, emailBody) {
    const self = this;
    GmailApp.sendEmail(emails, subject, '', { htmlBody: emailBody });
    return self;
  }

  /* 
   * This method displays Sheet messages with toast()
   * @param {string} message - message content
   * @param {string} title - message title 
   * @return {Workflow} this object for chaining
   */
  sendSSMsg_(msg, title) {
    const self = this;
    self.ss.toast(msg, title);
    return self;
  }

  /* 
   * This method populates the 'Config' tab with workflow asset URLs 
   * and associates the workflow Form destination with the workflow Sheet
   * @return {Workflow} this object for chaining
   */
  setupConfig_() {
    const self = this;
    let requestsFolder, requestForm, ssFolder, templateDoc;
    self.configSheet.activate();
    // Get spreadsheet parent folder - assumes all workflow documents in folder
    ssFolder = DriveApp.getFileById(self.ss.getId()).getParents().next();
    // Get workflow assets
    templateDoc = ssFolder.getFilesByType(MimeType.GOOGLE_DOCS).next();
    requestForm = ssFolder.getFilesByType(MimeType.GOOGLE_FORMS).next();
    requestsFolder = ssFolder.getFolders().next();
    // Add workflow asset URLs to ‘Config’ tab 
    self.configSheet.getRange(1, 2, 3).setValues([[requestForm.getUrl()], [templateDoc.getUrl()], [requestsFolder.getUrl()]]);
    // Set the workflow Form destination to the workflow Sheet
    FormApp.openById(requestForm.getId()).setDestination(FormApp.DestinationType.SPREADSHEET, self.ss.getId());
    return self;
  }

  /* 
   * This method populates the request document status table and saves/closes document
   * @param {Document} doc - generated request document
   * @param {string} status - request status ('New','Pending','Approved','Declined')
   * @param {string} statusDate - formatted date string
   * @param {string} submitComments - request status comments
   * @return {Workflow} this object for chaining
   */
  updateStatus_(doc, status, statusDate, statusComments = '') {
    const self = this,
          docBody = doc.getBody(),
          statusTable = docBody.getTables()[2]; 
    statusTable.getRow(0).getCell(1).editAsText().setText(status);
    statusTable.getRow(1).getCell(1).editAsText().setText(statusDate);
    statusTable.getRow(2).getCell(1).editAsText().setText(statusComments);
    doc.saveAndClose();
    return self;
  }

  /* 
   * This method updates the selected request workflow range in the form submission tab
   * @param {number} row - selected request row number
   * @param {string[][]} vals - two-dimensional array of workflow field values to be written to selected row
   * @return {Workflow} this object for chaining
   */
  updateWorkflowFields_(row, vals) {
    const self = this,
          formSheet = self.ss.getSheets()[0];
    formSheet.getRange(row, 1, 1, 4).setValues(vals);
    return self;
  }

}
/*
 * Copyright Laura Taylor
 * (https://github.com/techstreams/TSDataTable)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */



var CACHEKEY = 'table-data'; 

var CONFIG = {
  nav: {
    show: true,
    title: SpreadsheetApp.getActiveSpreadsheet().getName(),
    alignment: 'left',
    color: '#000FFF'
  },
  table: {
    dark: false,
    dense: true,
    fixedHeader: true,
    numberItems: false,
    height: '300',
    search: {
      show: true,
      text: ''
    },
    sort: true,
    check: {
      show: true,
      type: 'check'
    },
    link: {
      show: true,
      icon: true
    },
    controls: {
      checkoptions: ['check', 'check_circle','check_circle_outline','check_box']
    }
  }
}


/*
 * This function displays a spreadsheet menu
 *
 */
function onOpen() {
   SpreadsheetApp.getUi().createMenu('TSDataTable')
     .addItem('Configure Data Table', 'configureView')
     .addSeparator()
     .addItem('About TSDataTable', 'showAbout')
     .addToUi()

}

/*
 * This function displays the data table site
 *
 */
function doGet() {
  var template= HtmlService.createTemplateFromFile('index');
  template.data = getData();
  template.config = getConfig();
  return template.evaluate().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

/*
 * This function creates a data table configuration dialog
 *
 */
function configureView() {

   var template = HtmlService.createTemplateFromFile('config');
   template.data = getData();
   template.config = getConfig();
   template.showControls = true;
   SpreadsheetApp.getUi().showModelessDialog(template.evaluate().setWidth(700).setHeight(600), 'Configure Data Table');

}


/*
 * This function displays the about dialog
 *
 */
function showAbout() {
   var template = HtmlService.createTemplateFromFile('about');
   SpreadsheetApp.getUi().showModelessDialog(template.evaluate().setHeight(400), ' ');
}


/*
 * This function retrieves the table data from the spreadsheet's first tab.
 * Table data is filterd based on columns hidden by the user and rows hidden by the user or by a filter (does not apply to filter views).
 * Data is cached for ~6 hours to speed up display time.
 *
 * @return {Object} Object containing table headers and data
 */
function getData() {
  var cache = CacheService.getScriptCache().get(CACHEKEY),
      data = {headers:null, values:null},
      ss, sheet, values;
  if (cache) {
    return JSON.parse(cache);   
  } else {  
    ss = SpreadsheetApp.getActiveSpreadsheet();
    sheet = ss.getSheets()[0],
    range = sheet.getDataRange(),
    values = range.getDisplayValues(),
    alignments = range.getHorizontalAlignments(),
    rows = [];
    
    data.headers = values[0].map(function(header, h) {
      return {
        text: header,
        value: header.replace(' ', '').toLowerCase(),
        hidden: sheet.isColumnHiddenByUser(h+1),
        align: alignments[0][h]
      }
    });    
    values.forEach(function(row, r) {
      var rowObj;
      if (r !== 0 && (!sheet.isRowHiddenByFilter(r+1) && !sheet.isRowHiddenByUser(r+1))) {
        rowObj = {};
        row.forEach(function(col, c) {
          if (!data.headers[c].hidden) {
            rowObj[data.headers[c].value] = col;
          }
        });
        rows.push(rowObj);
      }
    });
    data.headers = data.headers.filter(function(header, h) {
      return !header.hidden;
    });    
    data.values = rows;   
    CacheService.getScriptCache().put(CACHEKEY, JSON.stringify(data), 21600); 
    return data;
  }
}


/*
 * This function retrieves the configuration data from the script properties
 *
 * @return {Object} Object containing data table site configuration
 */
function getConfig() {
   var props = PropertiesService.getScriptProperties().getProperty(CACHEKEY);
   if (props) {
     return JSON.parse(props);
   } else {
     setConfig(CONFIG);
     return CONFIG;  
   }
}


/*
 * This function sets the configuration data in the script properties
 *
 * @param {Object} Object containing configuration to add to script properties
 */
function setConfig(props) {
   PropertiesService.getScriptProperties().setProperty(CACHEKEY, JSON.stringify(props));
   return true;
}


/*
 * This function removes the table data from the script cache and returns a rebuild of the table data.
 *
 * @return {Object} Object containing a rebuild of the table data.
 */
function invalidateCache() {
   CacheService.getScriptCache().remove(CACHEKEY);
   return getData();
}
EXPLAIN SELECT count(*) FROM items;

Aggregate  (cost=20834.00..20834.01 rows=1 width=0)
  ->  Seq Scan on items  (cost=0.00..18334.00 rows=1000000 width=0)
$insert_data = collect();

foreach ($json['value'] as $value) {
    $posting_date = Carbon::parse($value['Posting_Date']);

    $posting_date = $posting_date->format('Y-m-d');

    $insert_data->push([
        'item_no'                   => $value['Item_No'],
        'entry_no'                  => $value['Entry_No'], 
        'document_no'               => $value['Document_No'],
        'posting_date'              => $posting_date,
        ....
    ]);
}

foreach ($insert_data->chunk(500) as $chunk)
{
   \DB::table('items_details')->insert($chunk->toArray());
}
star

Thu Aug 05 2021 06:55:08 GMT+0000 (UTC) https://docs.python-guide.org/dev/virtualenvs/

@faisal_maqsood #python #virtualenv #pipenv

star

Thu Aug 05 2021 06:53:24 GMT+0000 (UTC)

@faisal_maqsood #python

star

Thu Aug 05 2021 05:51:13 GMT+0000 (UTC)

@kiroy

star

Thu Aug 05 2021 05:03:35 GMT+0000 (UTC)

@Darkleech

star

Thu Aug 05 2021 05:02:39 GMT+0000 (UTC)

@Darkleech

star

Thu Aug 05 2021 05:01:32 GMT+0000 (UTC)

@Darkleech

star

Thu Aug 05 2021 05:00:44 GMT+0000 (UTC)

@Darkleech

star

Thu Aug 05 2021 02:47:46 GMT+0000 (UTC) https://github.com/termux/termux-packages/pull/7227#issuecomment-893022283

@andy

star

Thu Aug 05 2021 02:45:15 GMT+0000 (UTC)

@Darkleech #vba

star

Thu Aug 05 2021 02:26:27 GMT+0000 (UTC) https://www.thiscodeworks.com/extension/initializing?newuser

@nidhesh

star

Wed Aug 04 2021 22:59:18 GMT+0000 (UTC)

@prokasdimitri

star

Wed Aug 04 2021 22:46:43 GMT+0000 (UTC) https://pipmagazine.com.au/wp-admin/options-general.php?page

@GoldieMR #undefined

star

Wed Aug 04 2021 17:05:38 GMT+0000 (UTC) https://wpglorify.com/show-total-savings/

@Alz #php

star

Wed Aug 04 2021 16:56:10 GMT+0000 (UTC)

@dphillips #server #sync #copy

star

Wed Aug 04 2021 15:05:04 GMT+0000 (UTC)

@jhambach #n8n #halo #json

star

Wed Aug 04 2021 14:38:06 GMT+0000 (UTC)

@hollyhenaghan

star

Wed Aug 04 2021 14:28:03 GMT+0000 (UTC)

@hollyhenaghan

star

Wed Aug 04 2021 13:21:28 GMT+0000 (UTC) https://stackoverflow.com/questions/44628363/socket-io-access-control-allow-origin-error

@davidTheNerdy

star

Wed Aug 04 2021 13:14:59 GMT+0000 (UTC) https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe

@davidTheNerdy

star

Wed Aug 04 2021 09:39:30 GMT+0000 (UTC) https://superuser.com/questions/656301/bash-merge-directories-when-using-mv

@mdcx

star

Wed Aug 04 2021 09:11:31 GMT+0000 (UTC) https://stackoverflow.com/questions/37624699/adding-a-column-of-rowsums-across-a-list-of-columns-in-spark-dataframe

@Zyglak #scala #spark

star

Wed Aug 04 2021 08:30:14 GMT+0000 (UTC)

@kiroy

star

Wed Aug 04 2021 08:03:26 GMT+0000 (UTC) https://www.linuxshelltips.com/check-cpu-information-in-linux/

@mdcx

star

Wed Aug 04 2021 08:01:22 GMT+0000 (UTC) https://cs50.harvard.edu/x/2021/labs/1/hello/

@Lokwong

star

Wed Aug 04 2021 07:39:33 GMT+0000 (UTC) https://www.linuxshelltips.com/exclude-directory-while-finding-files-in-linux/

@mdcx

star

Wed Aug 04 2021 06:11:30 GMT+0000 (UTC)

@Emilgg

star

Wed Aug 04 2021 06:01:18 GMT+0000 (UTC)

@GoodRequest.

star

Wed Aug 04 2021 06:00:28 GMT+0000 (UTC)

@GoodRequest.

star

Wed Aug 04 2021 02:06:45 GMT+0000 (UTC)

@Roy #css

star

Tue Aug 03 2021 20:57:49 GMT+0000 (UTC)

@luisjdominguezp #c

star

Tue Aug 03 2021 19:45:50 GMT+0000 (UTC)

@luisjdominguezp #c

star

Tue Aug 03 2021 19:07:13 GMT+0000 (UTC)

@luisjdominguezp #c

star

Tue Aug 03 2021 18:25:07 GMT+0000 (UTC)

@Devraj #plaintext

star

Tue Aug 03 2021 15:54:10 GMT+0000 (UTC) https://stackoverflow.com/questions/14179758/how-can-i-build-a-condition-based-query-in-laravel

@mvieira #php

star

Tue Aug 03 2021 12:08:53 GMT+0000 (UTC) https://www.roblox.com/users/2488439667/profile

@Jesica #javascript

star

Tue Aug 03 2021 11:05:18 GMT+0000 (UTC)

@hollyhenaghan

star

Tue Aug 03 2021 09:53:41 GMT+0000 (UTC) https://stackoverflow.com/questions/42564058/how-to-use-local-docker-images-with-minikube

@RokoMetek #yaml

star

Tue Aug 03 2021 09:33:38 GMT+0000 (UTC)

@house5324

star

Tue Aug 03 2021 09:33:31 GMT+0000 (UTC)

@Roy #javascript #vue.js

star

Tue Aug 03 2021 09:23:31 GMT+0000 (UTC)

@Roy #html #vue.js

star

Tue Aug 03 2021 09:22:09 GMT+0000 (UTC) https://www.footmark.info/programming-language/vuejs/vue-cli3-i18n/

@Roy #javascript #vue.js

star

Tue Aug 03 2021 08:55:25 GMT+0000 (UTC) https://stackoverflow.com/questions/42521549/retry-function-in-python

@lahiruaruna #python

star

Tue Aug 03 2021 06:58:48 GMT+0000 (UTC) https://github.com/techstreams/TSWorkflow/blob/master/Code.gs

@admariner

star

Tue Aug 03 2021 06:38:27 GMT+0000 (UTC) https://github.com/techstreams/TSDataTable

@admariner

star

Tue Aug 03 2021 06:32:50 GMT+0000 (UTC) sfsdf

@Radharaman #javascript

star

Tue Aug 03 2021 04:37:21 GMT+0000 (UTC) https://www.citusdata.com/blog/2016/10/12/count-performance/

@mvieira

star

Tue Aug 03 2021 04:36:57 GMT+0000 (UTC) https://stackoverflow.com/questions/51487769/how-to-insert-big-data-on-the-laravel

@mvieira #php

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension