Best Python code snippet using pytest-cov
compile.js
Source:compile.js  
...83  }84  // BEGIN VISITOR METHODS85  function tbl(node, options, resume) {86    visit(node.elts[0], options, function (err1, val1) {87      resume([].concat(err1), {88        type: "table",89        args: val1,90      });91    });92  };93  function thead(node, options, resume) {94    visit(node.elts[0], options, function (err1, val1) {95      resume([].concat(err1), {96        type: "thead",97        args: val1,98      });99    });100  };101  function tbody(node, options, resume) {102    visit(node.elts[0], options, function (err1, val1) {103      resume([].concat(err1), {104        type: "tbody",105        args: val1,106      });107    });108  };109  function tr(node, options, resume) {110    visit(node.elts[0], options, function (err1, val1) {111      resume([].concat(err1), {112        type: "tr",113        args: val1,114      });115    });116  };117  function th(node, options, resume) {118    visit(node.elts[0], options, function (err1, val1) {119      resume([].concat(err1), {120        type: "th",121        args: val1,122      });123    });124  };125  function td(node, options, resume) {126    visit(node.elts[0], options, function (err1, val1) {127      resume([].concat(err1), {128        type: "td",129        args: val1,130      });131    });132  };133  function logoWidth(node, options, resume) {134    visit(node.elts[0], options, function (err, val0) {135      visit(node.elts[1], options, function (err, val1) {136        val1.logoWidth = val0;137        resume([], val1);138      });139    });140  }141  function width(node, options, resume) {142    visit(node.elts[0], options, function (err, val0) {143      visit(node.elts[1], options, function (err, val1) {144        val1.width = val0;145        resume([], val1);146      });147    });148  }149  function height(node, options, resume) {150    visit(node.elts[0], options, function (err, val0) {151      visit(node.elts[1], options, function (err, val1) {152        val1.height = val0;153        resume([], val1);154      });155    });156  }157  function packChart(node, options, resume) {158    visit(node.elts[0], options, function (err0, val0) {159      let data = stratify(val0);160      resume([].concat(err0), {161        type: "pack-chart",162        args: {163          data: data,164        }165      });166    });167  }168  function renderCategory(data) {169    let categoryName = data.name;170    let children = data.children;171    let products = [];172    children.forEach(child => {173      products.push({174        "type": "tr",175        "args": [{176          "type": "td",177          "style": {178            "borderWidth": "0px",179            "padding": "0px 0 5",180          },181          "args": [{182            "type": "a",183            "style": {184              "color": "#333",185            },186            "attrs": {187              "href": child.url,188            },189            "args": [{190              "type": "div",191              "style": {192                "background": "#FFF",193                "borderWidth": "1px",194                "padding": "10 10",195                "borderColor": "#cccece",196                "borderStyle": "solid",197                "borderRadius": "5px",198              },199              "args": [{200                "type": "img",201                "style": {202                  "margin": "0 5 0 0",203                  "width": "20",204                  "height": "20",205                },206                "attrs": {207                  "src": child.logo,208                },209              }, {210                "type": "str",211                "style": {212                  "margin": "12px 0",213                },214                "value": child.name,215              }],216            }],217          }],218        }],219      },);220    });221    return {222      "type": "col-2",223      "style": {224        "padding": "5px",225      },226      "args": [{227        "type": "div",228        "style": {229          "background": "#f6f6f6",230          "borderWidth": "1",231          "borderColor": "#cccece",232          "borderStyle": "solid",233          "borderRadius": "5px",234          "padding": "5px",235        },236        "args": [{237          "type": "table",238          "style": {239            "marginBottom": "0",240          },241          "args": [{242            "type": "thead",243            "args": [{244              "type": "tr",245              "args": [{246                "type": "th",247                "style": {248                  "borderWidth": "0px",249                  "padding": "5px 2px 10px",250                },251                "args": [{252                  "type": "str",253                  "style": {254                    "fontSize": "12",255                  },256                  "value": categoryName.toUpperCase(),257                }]258              }],259            }],260          },{261            "type": "tbody",262            "args": products,263          }],264        }],265      }],266    };267  };268  function renderCompany(data) {269    if (!data.name || !data.children) {270      return {271      };272    }273    let companyName = data.name;274    let companyLogo = data.logo;275    let children = data.children;276    let categories = [];277    children.sort((a, b) => {278      return b.children.length - a.children.length;279    });280    children.forEach(child => {281      categories.push(renderCategory(child));282    });283    return {284      "type": "container-fluid",285      "style": {286        "margin": "10 4",287      },288      "args": [{289        "type": "row",290        "style": {291          "margin": "4",292        },293        "args": [{294          "type": "col",295          "args": [{296          }],297        }, {298          "type": "col-4",299          "args": [{300            "type": "str",301            "style": {302              "fontSize": "13",303              "fontWeight": "600",304            },305            "value": "POWERED BY ",306          }, {307          "type": "img",308          "style": {309            "margin": "0 0 2",310            "height": "22",311          },312          "attrs": {313            "src": "https://static.chief.io/static/logo/logo-sm.png",314          },315        }],316        }, {317          "type": "col",318          "args": [{319          }],320        }],321      }, {322        "type": "row",323        "style": {324          "margin": "4",325        },326        "args": [{327          "type": "col-12",328          "style": {329            "margin": "0",330            "padding": "0",331          },332          "args": [{333            "type": "img",334            "style": {335              "margin": "0 5 10 5",336              "width": "30",337              "height": "30",338            },339            "attrs": {340              "src": companyLogo,341            },342          }, {343            "type": "str",344            "style": {345              "margin": "5",346              "fontSize": "30",347              "fontWeight": "400",348            },349            "value": companyName,350          }]351        }],352      }, {353        "type": "row",354        "style": {355          "margin": "4",356        },357        "args": categories,358      }],359    }360  }361  function stackChart(node, options, resume) {362    let data = options.data instanceof Array && options.data || [options.data];363    let root = renderCompany(data[0]);364    resume([], {365      type: "stack-chart",366      root: root,367    });368  }369  function treemapChart(node, options, resume) {370    let data = options.data instanceof Array && options.data || [options.data];371    let root = stratify(data);372    resume([], {373      type: "treemap-chart",374      args: {375        data: root,376      }377    });378  }379  function str(node, options, resume) {380    let val = node.elts[0];381    resume([], val);382  }383  function num(node, options, resume) {384    let val = node.elts[0];385    resume([], +val);386  }387  function ident(node, options, resume) {388    let val = node.elts[0];389    resume([], val);390  }391  function bool(node, options, resume) {392    let val = node.elts[0];393    resume([], !!val);394  }395  function concat(node, options, resume) {396    visit(node.elts[0], options, function (err1, val1) {397      let str = "";398      if (val1 instanceof Array) {399        val1.forEach(v => {400          str += v;401        });402      } else {403        str = val1.toString();404      }405      resume(err1, str);406    });407  }408  function paren(node, options, resume) {409    visit(node.elts[0], options, function (err1, val1) {410      resume(err1, val1);411    });412  }413  function list(node, options, resume) {414    if (node.elts && node.elts.length > 1) {415      visit(node.elts[0], options, function (err1, val1) {416        node = {417          tag: "LIST",418          elts: node.elts.slice(1),419        };420        list(node, options, function (err2, val2) {421          let val = [].concat(val2);422          val.unshift(val1);423          resume([].concat(err1).concat(err2), val);424        });425      });426    } else if (node.elts && node.elts.length > 0) {427      visit(node.elts[0], options, function (err1, val1) {428        let val = [val1];429        resume([].concat(err1), val);430      });431    } else {432      resume([], []);433    }434  }435  function inData(node, options, resume) {436    // If there is input data, then use it, otherwise use default data.437    if (node.elts.length === 0) {438      // No args, so use the given data or empty.439      let data = options.data ? options.data : [];440      resume([], data);441    } else {442      visit(node.elts[0], options, function (err1, val1) {443        if (false) {444          err1 = err1.concat(error("Argument must be a number.", node.elts[0]));445        }446        let data = options.data && Object.keys(options.data).length != 0 ? options.data : val1;447        resume([].concat(err1), data);448      });449    }450  }451  function arg(node, options, resume) {452    visit(node.elts[0], options, function (err1, val1) {453      let key = val1;454      if (false) {455        err1 = err1.concat(error("Argument must be a number.", node.elts[0]));456      }457      resume([].concat(err1), options.args[key]);458    });459  }460  function args(node, options, resume) {461    resume([], options.args);462  }463  function lambda(node, options, resume) {464    // Return a function value.465    visit(node.elts[0], options, function (err1, val1) {466      visit(node.elts[1], options, function (err2, val2) {467        resume([].concat(err1).concat(err2), val2);468      });469    });470  }471  function apply(node, options, resume) {472    // Apply a function to arguments.473    visit(node.elts[1], options, function (err1, val1) {474      // args475      options.args = [val1];476      visit(node.elts[0], options, function (err0, val0) {477        // fn478        resume([].concat(err1).concat(err0), val0);479      });480    });481  }482  function map(node, options, resume) {483    // Apply a function to arguments.484    visit(node.elts[1], options, function (err1, val1) {485      // args486      let errs = [];487      let vals = [];488      val1.forEach((val) => {489        options.args = [val];490        visit(node.elts[0], options, function (err0, val0) {491          vals.push(val0);492          errs = errs.concat(err0);493        });494      });495      resume(errs, vals);496    });497  }498  function binding(node, options, resume) {499    visit(node.elts[0], options, function (err1, val1) {500      visit(node.elts[1], options, function (err2, val2) {501        resume([].concat(err1).concat(err2), {key: val1, val: val2});502      });503    });504  }505  function record(node, options, resume) {506    if (node.elts && node.elts.length > 1) {507      visit(node.elts[0], options, function (err1, val1) {508        node = {509          tag: "RECORD",510          elts: node.elts.slice(1),511        };512        record(node, options, function (err2, val2) {513          val2[val1.key] = val1.val;514          resume([].concat(err1).concat(err2), val2);515        });516      });517    } else if (node.elts && node.elts.length > 0) {518      visit(node.elts[0], options, function (err1, val1) {519        let val = {};520        val[val1.key] = val1.val;521        resume([].concat(err1), val);522      });523    } else {524      resume([], {});525    }526  }527  function exprs(node, options, resume) {528    if (node.elts && node.elts.length > 1) {529      visit(node.elts[0], options, function (err1, val1) {530        node = {531          tag: "EXPRS",532          elts: node.elts.slice(1),533        };534        exprs(node, options, function (err2, val2) {535          let val = [].concat(val2);536          val.unshift(val1);537          resume([].concat(err1).concat(err2), val);538        });539      });540    } else if (node.elts && node.elts.length > 0) {541      visit(node.elts[0], options, function (err1, val1) {542        let val = [val1];543        resume([].concat(err1), val);544      });545    } else {546      resume([], []);547    }548  }549  function program(node, options, resume) {550    if (!options) {551      options = {};552    }553    visit(node.elts[0], options, function (err, val) {554      // Return the value of the last expression.555      resume(err, val.pop());556    });557  }558  function key(node, options, resume) {559    visit(node.elts[0], options, function (err1, val1) {560      let key = val1;561      if (false) {562        err1 = err1.concat(error("Argument must be a number.", node.elts[0]));563      }564      visit(node.elts[1], options, function (err2, val2) {565        let obj = val2;566        if (false) {567          err2 = err2.concat(error("Argument must be a number.", node.elts[1]));568        }569        resume([].concat(err1).concat(err2), Object.keys(obj)[key]);570      });571    });572  }573  function val(node, options, resume) {574    visit(node.elts[0], options, function (err1, val1) {575      let key = val1;576      if (false) {577        err1 = err1.concat(error("Argument must be a number.", node.elts[0]));578      }579      visit(node.elts[1], options, function (err2, val2) {580        let obj = val2;581        if (false) {582          err2 = err2.concat(error("Argument must be a number.", node.elts[1]));583        }584        resume([].concat(err1).concat(err2), obj[key]);585      });586    });587  }588  function len(node, options, resume) {589    visit(node.elts[0], options, function (err1, val1) {590      let obj = val1;591      if (false) {592        err1 = err1.concat(error("Argument must be a number.", node.elts[0]));593      }594      resume([].concat(err1), obj.length);595    });596  }597  function add(node, options, resume) {598    visit(node.elts[0], options, function (err1, val1) {599      val1 = +val1;600      if (isNaN(val1)) {601        err1 = err1.concat(error("Argument must be a number.", node.elts[0]));602      }603      visit(node.elts[1], options, function (err2, val2) {604        val2 = +val2;605        if (isNaN(val2)) {606          err2 = err2.concat(error("Argument must be a number.", node.elts[1]));607        }608        resume([].concat(err1).concat(err2), val1 + val2);609      });610    });611  }612  function mul(node, options, resume) {613    visit(node.elts[0], options, function (err1, val1) {614      val1 = +val1;615      if (isNaN(val1)) {616        err1 = err1.concat(error("Argument must be a number.", node.elts[0]));617      }618      visit(node.elts[1], options, function (err2, val2) {619        val2 = +val2;620        if (isNaN(val2)) {621          err2 = err2.concat(error("Argument must be a number.", node.elts[1]));622        }623        resume([].concat(err1).concat(err2), val1 * val2);624      });625    });626  }627  function style(node, options, resume) {628    visit(node.elts[0], options, function (err1, val1) {629      visit(node.elts[1], options, function (err2, val2) {630        resume([].concat(err1).concat(err2), {631          value: val1,632          style: val2,633        });634      });635    });636  }637  function styleV1(node, options, resume) {638    visit(node.elts[0], options, function (err1, val1) {639      visit(node.elts[1], options, function (err2, val2) {640        resume([].concat(err1).concat(err2), {641          style: val1,642          value: val2,643        });644      });645    });646  }647  return transform;648})();649const render = (function() {650  function escapeXML(str) {651    return String(str)652      .replace(/&(?!\w+;)/g, "&")653      .replace(/\n/g, " ")654      .replace(/\\/g, "\\\\")655      .replace(/</g, "<")656      .replace(/>/g, ">")657      .replace(/"/g, """);658  }659  function render(val, options, resume) {660    // Do some rendering here.661    resume([], val);662  }663  return render;664})();665const unpack = (name, data) => {666  let kids = [];667  if (typeof data === "object") {668    Object.keys(data).forEach((k) => {669      if (k !== "type" && k !== "logo") {670        let kid = {671          name: k,672          type: data[k].type,673          logo: data[k].logo,674        };675        kid["children"] = unpack((data[k].type === "category" || data[k].type === "business") && k, data[k]);676        kids.push(kid);677      }678    });679    // if (name) {680    //   kids.push({681    //     name: name,682    //     type: "label",683    //   });684    // }685  }686  return kids.length && kids || undefined;687};688function stratifyNode(root, {689  type,690  name,691  url,692  logo,693  children,694  category,695  industry,696}) {697  if (!root[name]) {698    root[name] = {699      type: type,700      //      name: name,701      logo: logo,702    };703  }704  if (children) {705    children.forEach(data => {706      stratifyNode(root[name], data);707    });708  }709  return root;710}711function stratify(data) {712  let root = {};713  data.forEach(d => {714    stratifyNode(root, d);715  });716  root = {717    name: "root",718    children: unpack(null, root),719  }720  return root;721};722export let compiler = (function () {723  exports.version = "v1.0.0";724  exports.compile = function compile(code, data, resume) {725    try {726      let options = {727        data: data728      };729      transform(code, options, function (err, val) {730        if (err.length) {731          resume(err, val);732        } else {733          render(val, options, function (err, val) {734            resume(err, val);735          });736        }737      });738    } catch (x) {739      console.log("ERROR with code");740      console.log(x.stack);741      resume(["Compiler error"], {742        score: 0743      });744    }745  }...intelCore.py
Source:intelCore.py  
1'''2Copyright (c) 2013-2015, Joshua Pitts3All rights reserved.4Redistribution and use in source and binary forms, with or without modification,5are permitted provided that the following conditions are met:6    1. Redistributions of source code must retain the above copyright notice,7    this list of conditions and the following disclaimer.8    2. Redistributions in binary form must reproduce the above copyright notice,9    this list of conditions and the following disclaimer in the documentation10    and/or other materials provided with the distribution.11    3. Neither the name of the copyright holder nor the names of its contributors12    may be used to endorse or promote products derived from this software without13    specific prior written permission.14THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"15AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE16IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE17ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE18LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR19CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF20SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS21INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN22CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)23ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE24POSSIBILITY OF SUCH DAMAGE.25'''26import struct27import random28from binascii import unhexlify29from capstone import *30class intelCore():31    nops = [0x90, 0x3690, 0x6490, 0x6590, 0x6690, 0x6790]32    jmp_symbols = ['jns', 'jle', 'jg', 'jp', 'jge', 'js', 'jl', 'jbe', 'jo',33                   'jne', 'jrcxz', 'je', 'jae', 'jno', 'ja', 'jb', 'jnp', 'jmp'34                   ]35    def __init__(self, flItms, file_handle, VERBOSE):36        self.f = file_handle37        self.flItms = flItms38        self.VERBOSE = VERBOSE39    def opcode_return(self, OpCode, instr_length):40        _, OpCode = hex(OpCode).split('0x')41        OpCode = unhexlify(OpCode)42        return OpCode43    def ones_compliment(self):44        """45        Function for finding two random 4 byte numbers that make46        a 'ones compliment'47        """48        compliment_you = random.randint(1, 4228250625)49        compliment_me = int('0xFFFFFFFF', 16) - compliment_you50        if self.VERBOSE is True:51            print "First ones compliment:", hex(compliment_you)52            print "2nd ones compliment:", hex(compliment_me)53            print "'AND' the compliments (0): ", compliment_you & compliment_me54        self.compliment_you = struct.pack('<I', compliment_you)55        self.compliment_me = struct.pack('<I', compliment_me)56    def pe32_entry_instr(self):57        """58        Updated to use Capstone-Engine59        """60        print "[*] Reading win32 entry instructions"61        self.f.seek(self.flItms['LocOfEntryinCode'])62        self.count = 063        self.flItms['ImpList'] = []64        md = Cs(CS_ARCH_X86, CS_MODE_32)65        self.count = 066        for k in md.disasm(self.f.read(12), self.flItms['VrtStrtngPnt']):67            self.count += k.size68            _bytes = bytearray(b'')69            if len(k.bytes) < k.size:70                _bytes = bytearray(b"\x00" * (k.size - len(k.bytes)))71            value_bytes = k.bytes + _bytes72            self.flItms['ImpList'].append([int(hex(k.address).strip('L'), 16),73                                          k.mnemonic.encode("utf-8"),74                                          k.op_str.encode("utf-8"),75                                          int(hex(k.address).strip('L'), 16) + k.size,76                                          value_bytes,77                                          k.size])78            if self.count >= 6 or self.count % 5 == 0 and self.count != 0:79                break80        self.flItms['count_bytes'] = self.count81    def pe64_entry_instr(self):82        """83        For x64 files. Updated to use Capstone-Engine.84        """85        print "[*] Reading win64 entry instructions"86        self.f.seek(self.flItms['LocOfEntryinCode'], 0)87        self.count = 088        self.flItms['ImpList'] = []89        md = Cs(CS_ARCH_X86, CS_MODE_64)90        for k in md.disasm(self.f.read(12), self.flItms['VrtStrtngPnt']):91            self.count += k.size92            _bytes = bytearray(b'')93            if len(k.bytes) < k.size:94                _bytes = bytearray(b"\x00" * (k.size - len(k.bytes)))95            value_bytes = k.bytes + _bytes96            self.flItms['ImpList'].append([int(hex(k.address).strip('L'), 16),97                                          k.mnemonic.encode("utf-8"),98                                          k.op_str.encode("utf-8"),99                                          int(hex(k.address).strip('L'), 16) + k.size,100                                          value_bytes,101                                          k.size])102            if self.count >= 6 or self.count % 5 == 0 and self.count != 0:103                break104        self.flItms['count_bytes'] = self.count105    def patch_initial_instructions(self):106        """107        This function takes the flItms dict and patches the108        executable entry point to jump to the first code cave.109        """110        print "[*] Patching initial entry instructions"111        self.f.seek(self.flItms['LocOfEntryinCode'], 0)112        #This is the JMP command in the beginning of the113        #code entry point that jumps to the codecave114        self.f.write(struct.pack('=B', int('E9', 16)))115        if self.flItms['JMPtoCodeAddress'] < 0:116            self.f.write(struct.pack('<I', 0xffffffff + self.flItms['JMPtoCodeAddress']))117        else:118            self.f.write(struct.pack('<I', self.flItms['JMPtoCodeAddress']))119        # To make any overwritten instructions dissembler friendly120        if self.flItms['count_bytes'] > 5:121            for i in range(self.flItms['count_bytes'] - 5):122                self.f.write(struct.pack('=B', 0x90))123    def resume_execution_64(self):124        """125        For x64 exes...126        """127        print "[*] Creating win64 resume execution stub"128        #pause loop for code cave clearing stub129        resumeExe = ''130        resumeExe += "\x51"             # push ecx131        resumeExe += "\x48\xc7\xc1"             # mov ecx, value below132        resumeExe += struct.pack("<I", (len(self.flItms['shellcode']) - 6))133        resumeExe += "\xe2\xfe"         # loop back on itself134        resumeExe += "\x59"             # pop ecx135        total_opcode_len = 0136        for item in self.flItms['ImpList']:137            startingPoint = item[0]138            OpCode = item[1]139            CallValue = item[2]140            ReturnTrackingAddress = item[3]141            entireInstr = item[4]142            total_opcode_len += item[5]143            self.ones_compliment()144            if OpCode == 'call':  # Call instruction145                CallValue = int(CallValue, 16)146                resumeExe += "\x48\x89\xd0"  # mov rad,rdx147                resumeExe += "\x48\x83\xc0"  # add rax,xxx148                resumeExe += struct.pack("<B", total_opcode_len)  # length from vrtstartingpoint after call149                resumeExe += "\x50"  # push rax150                if len(entireInstr[1:]) <= 4:  # 4294967295:151                    resumeExe += "\x48\xc7\xc1"  # mov rcx, 4 bytes152                    resumeExe += entireInstr[1:]153                elif len(entireInstr[1:]) > 4:  # 4294967295:154                    resumeExe += "\x48\xb9"  # mov rcx, 8 bytes155                    resumeExe += entireInstr[1:]156                resumeExe += "\x48\x01\xc8"  # add rax,rcx157                resumeExe += "\x50"158                resumeExe += "\x48\x31\xc9"  # xor rcx,rcx159                resumeExe += "\x48\x89\xf0"  # mov rax, rsi160                resumeExe += "\x48\x81\xe6"  # and rsi, XXXX161                resumeExe += self.compliment_you162                resumeExe += "\x48\x81\xe6"  # and rsi, XXXX163                resumeExe += self.compliment_me164                resumeExe += "\xc3"165                return ReturnTrackingAddress, resumeExe166            elif any(symbol in OpCode for symbol in self.jmp_symbols):167                #Let's beat ASLR168                CallValue = int(CallValue, 16)169                resumeExe += "\xb8"170                aprox_loc_wo_alsr = (startingPoint +171                                     self.flItms['JMPtoCodeAddress'] +172                                     len(self.flItms['shellcode']) + len(resumeExe) +173                                     200 + self.flItms['buffer'])174                resumeExe += struct.pack("<I", aprox_loc_wo_alsr)175                resumeExe += struct.pack('=B', int('E8', 16))  # call176                resumeExe += "\x00" * 4177                # POP ECX to find location178                resumeExe += struct.pack('=B', int('59', 16))179                resumeExe += "\x2b\xc1"  # sub eax,ecx180                resumeExe += "\x3d\x00\x05\x00\x00"  # cmp eax,500181                resumeExe += "\x77\x0b"  # JA (14)182                resumeExe += "\x83\xC1\x16"183                resumeExe += "\x51"184                resumeExe += "\xb8"  # Mov EAX ..185                if OpCode is int('ea', 16):  # jmp far186                    resumeExe += struct.pack('<BBBBBB', CallValue + 5)187                elif CallValue > 429467295:188                    resumeExe += struct.pack('<I', abs(CallValue + 5 - 0xffffffff + 2))189                else:190                    resumeExe += struct.pack('<I', CallValue + 5)  # Add+ EAX, CallValue191                resumeExe += "\x50\xc3"192                resumeExe += "\x8b\xf0"193                resumeExe += "\x8b\xc2"194                resumeExe += "\xb9"195                resumeExe += struct.pack('<I', startingPoint - 5)196                resumeExe += "\x2b\xc1"197                resumeExe += "\x05"198                if OpCode is int('ea', 16):  # jmp far199                    resumeExe += struct.pack('<BBBBBB', CallValue + 5)200                elif CallValue > 429467295:201                    resumeExe += struct.pack('<I', abs(CallValue + 5 - 0xffffffff + 2))202                else:203                    resumeExe += struct.pack('<I', CallValue)204                resumeExe += "\x50"205                resumeExe += "\x33\xc9"206                resumeExe += "\x8b\xc6"207                resumeExe += "\x81\xe6"208                resumeExe += self.compliment_you209                resumeExe += "\x81\xe6"210                resumeExe += self.compliment_me211                resumeExe += "\xc3"212                return ReturnTrackingAddress, resumeExe213            else:214                resumeExe += entireInstr215        resumeExe += "\x49\x81\xe7"216        resumeExe += self.compliment_you  # zero out r15217        resumeExe += "\x49\x81\xe7"218        resumeExe += self.compliment_me  # zero out r15219        resumeExe += "\x49\x81\xc7"  # ADD r15 <<-fix it this a 4 or 8 byte add does it matter?220        if ReturnTrackingAddress >= 4294967295:221            resumeExe += struct.pack('<Q', ReturnTrackingAddress)222        else:223            resumeExe += struct.pack('<I', ReturnTrackingAddress)224        resumeExe += "\x41\x57"  # push r15225        resumeExe += "\x49\x81\xe7"  # zero out r15226        resumeExe += self.compliment_you227        resumeExe += "\x49\x81\xe7"  # zero out r15228        resumeExe += self.compliment_me229        resumeExe += "\xC3"230        return ReturnTrackingAddress, resumeExe231    def resume_execution_32(self):232        """233        This section of code imports the self.flItms['ImpList'] from pe32_entry_instr234        to patch the executable after shellcode execution235        """236        print "[*] Creating win32 resume execution stub"237        resumeExe = ''238        # buffer for zeroing shellcode (no performance impact)239        resumeExe += "\x51"             # push ecx240        resumeExe += "\xb9"             # mov ecx, value below241        resumeExe += struct.pack("<I", (len(self.flItms['shellcode']) - 6))242        resumeExe += "\xe2\xfe"         # loop back on itself243        resumeExe += "\x59"             # pop ecx244        for item in self.flItms['ImpList']:245            startingPoint = item[0]246            OpCode = item[1]247            CallValue = item[2]248            ReturnTrackingAddress = item[3]249            entireInstr = item[4]250            self.ones_compliment()251            if OpCode == 'call':  # Call instruction252                # Let's beat ASLR :D253                CallValue = int(CallValue, 16)254                resumeExe += "\xb8"255                if self.flItms['LastCaveAddress'] == 0:256                    self.flItms['LastCaveAddress'] = self.flItms['JMPtoCodeAddress']257                #Could make this more exact...258                aprox_loc_wo_alsr = (startingPoint +259                                     self.flItms['LastCaveAddress'] +260                                     len(self.flItms['shellcode']) + len(resumeExe) +261                                     500 + self.flItms['buffer'])262                resumeExe += struct.pack("<I", aprox_loc_wo_alsr)263                resumeExe += struct.pack('=B', int('E8', 16))  # call264                resumeExe += "\x00" * 4265                # POP ECX to find location266                resumeExe += struct.pack('=B', int('59', 16))267                resumeExe += "\x2b\xc1"  # sub eax,ecx268                resumeExe += "\x3d\x00\x05\x00\x00"  # cmp eax,500269                resumeExe += "\x77\x12"  # JA (14)270                resumeExe += "\x83\xC1\x15"  # ADD ECX, 15271                resumeExe += "\x51"272                resumeExe += "\xb8"  # Mov EAX ..273                if CallValue > 4294967295:274                    resumeExe += struct.pack('<I', CallValue - 0xffffffff - 1)275                else:276                    resumeExe += struct.pack('<I', CallValue)277                resumeExe += "\xff\xe0"  # JMP EAX278                resumeExe += "\xb8"  # ADD279                resumeExe += struct.pack('<I', item[3])280                resumeExe += "\x50\xc3"  # PUSH EAX,RETN281                resumeExe += "\x8b\xf0"282                resumeExe += "\x8b\xc2"283                resumeExe += "\xb9"284                resumeExe += struct.pack("<I", startingPoint)285                resumeExe += "\x2b\xc1"286                resumeExe += "\x05"287                resumeExe += struct.pack('<I', ReturnTrackingAddress)288                resumeExe += "\x50"289                resumeExe += "\x05"290                resumeExe += entireInstr[1:]291                resumeExe += "\x50"292                resumeExe += "\x33\xc9"293                resumeExe += "\x8b\xc6"294                resumeExe += "\x81\xe6"295                resumeExe += self.compliment_you296                resumeExe += "\x81\xe6"297                resumeExe += self.compliment_me298                resumeExe += "\xc3"299                return ReturnTrackingAddress, resumeExe300            elif any(symbol in OpCode for symbol in self.jmp_symbols):301                #Let's beat ASLR302                CallValue = int(CallValue, 16)303                resumeExe += "\xb8"304                aprox_loc_wo_alsr = (startingPoint +305                                     self.flItms['LastCaveAddress'] +306                                     len(self.flItms['shellcode']) + len(resumeExe) +307                                     200 + self.flItms['buffer'])308                resumeExe += struct.pack("<I", aprox_loc_wo_alsr)309                resumeExe += struct.pack('=B', int('E8', 16))  # call310                resumeExe += "\x00" * 4311                resumeExe += struct.pack('=B', int('59', 16))312                resumeExe += "\x2b\xc1"  # sub eax,ecx313                resumeExe += "\x3d\x00\x05\x00\x00"  # cmp eax,500314                resumeExe += "\x77\x0b"  # JA (14)315                resumeExe += "\x83\xC1\x16"316                resumeExe += "\x51"317                resumeExe += "\xb8"  # Mov EAX ..318                if OpCode is int('ea', 16):  # jmp far319                    resumeExe += struct.pack('<BBBBBB', CallValue + 5)320                elif CallValue > 429467295:321                    resumeExe += struct.pack('<I', abs(CallValue + 5 - 0xffffffff + 2))322                else:323                    resumeExe += struct.pack('<I', CallValue + 5)  # Add+ EAX,CallV324                resumeExe += "\x50\xc3"325                resumeExe += "\x8b\xf0"326                resumeExe += "\x8b\xc2"327                resumeExe += "\xb9"328                resumeExe += struct.pack('<I', startingPoint - 5)329                resumeExe += "\x2b\xc1"330                resumeExe += "\x05"331                if OpCode is int('ea', 16):  # jmp far332                    resumeExe += struct.pack('<BBBBBB', CallValue + 5)333                elif CallValue > 429467295:334                    resumeExe += struct.pack('<I', abs(CallValue + 5 - 0xffffffff + 2))335                else:336                    resumeExe += struct.pack('<I', CallValue + 5 - 2)337                resumeExe += "\x50"338                resumeExe += "\x33\xc9"339                resumeExe += "\x8b\xc6"340                resumeExe += "\x81\xe6"341                resumeExe += self.compliment_you342                resumeExe += "\x81\xe6"343                resumeExe += self.compliment_me344                resumeExe += "\xc3"345                return ReturnTrackingAddress, resumeExe346            else:347                resumeExe += entireInstr348        resumeExe += "\x25"349        resumeExe += self.compliment_you  # zero out EAX350        resumeExe += "\x25"351        resumeExe += self.compliment_me  # zero out EAX352        resumeExe += "\x05"  # ADD353        resumeExe += struct.pack('<I', ReturnTrackingAddress)354        resumeExe += "\x50"  # push eax355        resumeExe += "\x25"  # zero out EAX356        resumeExe += self.compliment_you357        resumeExe += "\x25"  # zero out EAX358        resumeExe += self.compliment_me359        resumeExe += "\xC3"...candidates.js
Source:candidates.js  
1import { createSelector } from 'reselect'2import unionBy from 'lodash/unionBy'3import differenceBy from 'lodash/differenceBy'4const initialState = {5  search: {6    now: false,7    showAdvanced: false,8    query: '',9    data: [],10    count: null11  },12  data: [],13  page: 1,14  perPage: 30,15  groupId: null,16  groupCandidates: [],17  stats: [],18  scroll: true,19  current: null,20  openLinkedCandidateModal: false,21  sources: [],22  languages: [],23  languagesLevel: [],24  educationLevel: [],25  specialization: [],26  sidebar: {27    showSidebar: false,28    candidateId: null,29  },30  resumeTabSwitcher: 'resume',31  parsedResume: {32    fullName: {33      candidate_vacancies_attributes: [''],34    },35    contactInformation: {36      phones: [''],37      emails: [''],38      additional_contacts_attributes: [''],39    },40    basicInformation: {41      language_skills_attributes: [''],42    },43    resumeText: {},44    experience: {45      resume_work_experiences_attributes: [''],46    },47    achievements: {48      resume_educations_attributes: [''],49    },50    expectations: {},51    recommendations: {52      resume_recommendations_attributes: [''],53    },54  },55  select: [],56  filter: null,57}58const getGroupId = state => state.candidates.groupId59const isSearchNow = state => state.candidates.search.now60const getCandidates = state => state.candidates61export const currentVisibleCandidates = createSelector(62  [getGroupId, isSearchNow, getCandidates], (groupId, searchNow, candidates) => {63    if (searchNow) {64      return candidates.search.data65    } else if (groupId) {66      return candidates.groupCandidates67    } else {68      return candidates.data69    }70  }71)72export const currentGroup = createSelector(73  [getGroupId, getCandidates], (groupId, candidates) => {74    if (groupId === null) {75      return { label: 'ÐÑе', value: 'all' }76    } else if (groupId === -1) {77      return { label: 'СвободнÑе', value: 'free' }78    } else {79      return candidates.stats.vacancy_stage_groups.find(g => g.id === groupId)80    }81  }82)83function preferredContact(contacts) {84  if (contacts.length === 0) return '0-phone'85  const contact = contacts.find(item => item.preferred)86  let prefer = ''87  let emails = 088  let phones = 089  if (!contact) return '0-phone'90  contacts.forEach((item) => {91    if(item.preferred && item.contact_type === 'email') {92      prefer = `${emails}-${item.contact_type}`93    }94    if(item.preferred && item.contact_type === 'phone') {95      prefer = `${phones}-${item.contact_type}`96    }97    if(item.contact_type === 'email') emails = emails + 198    if(item.contact_type === 'phone') phones = phones + 199  })100  return prefer101  // if (contact.contact_type === 'skype') {102  //   return contact.contact_type103  // }104  // if (contact.contact_type === 'email' || contact.contact_type === 'phone') {105  //   const key = contacts.find((item, key) => item.preferred && key)106  //   return `${key}-${contact.contact_type}`107  // }108}109function parsingData(data) {110  const { resume } = data111  let email = resume.resume_contacts.filter(it => it.contact_type === 'email')112  let phone = resume.resume_contacts.filter(it => it.contact_type === 'phone')113  return {114    fullName: {115      city: resume.city,116      first_name: resume.first_name,117      last_name: resume.last_name,118      middle_name: resume.middle_name,119      resume_source_id: resume.resume_source_id,120      candidate_vacancies_attributes: [''],121      photo: resume.photo.url,122      raw_resume_doc_id: resume.raw_resume_doc_id,123      remote_resume_file_url: resume.resume_file.url,124      parsed: resume.parsed,125    },126    contactInformation: {127      emails: email.length > 0 ? resume.resume_contacts.filter(item => item.contact_type === 'email').map(item => ({ email: item.value })) : [''],128      phones: phone.length > 0 ? resume.resume_contacts.filter(item => item.contact_type === 'phone').map(item => ({ phone: item.value.split(' ').join('') })) : [''],129      skype: resume.resume_contacts.find(item => item.contact_type === 'skype') ?130        resume.resume_contacts.find(item => item.contact_type === 'skype').value : '',131      preferred_contact_type: preferredContact(resume.resume_contacts),132      additional_contacts_attributes:133        Array.isArray(resume.additional_contacts) &&134        resume.additional_contacts.length > 0 ? resume.additional_contacts : [''],135    },136    tabResume: {137      resume_text: resume.resume_text,138    },139    basicInformation: {140      birthdate: resume.birthdate,141      sex: resume.sex,142      skills: resume.skill_list,143      skills_description: resume.skills_description,144      language_skills_attributes: resume.language_skills,145    },146    experience: {147      resume_work_experiences_attributes: resume.resume_work_experiences.length > 0 ?148        resume.resume_work_experiences.map(item => {149          return {150            ...item,151            nowadays: !item.end_date,152          }153        }) :154        [''],155    },156    achievements: {157      education_level_id: resume.education_level_id,158      resume_educations_attributes:159        resume.resume_educations.length > 0160          ? resume.resume_educations.map(item => {161            return {162              ...item,163              end_year: item.end_year && `${item.end_year}`,164            }165          })166          : [''],167      resume_courses_attributes:168        resume.resume_courses && resume.resume_courses.length > 0 ?169          resume.resume_courses.map(item => {170            return {171              ...item,172              end_year: item.end_year && `${item.end_year}`,173            }174          }) : [''],175      resume_certificates_attributes:176        resume.resume_certificates && resume.resume_certificates.length > 0 ?177          resume.resume_certificates.map(item => {178            return {179              ...item,180              company_name: item.company_name && `${item.company_name}`,181              name: item.name && `${item.name}`,182              end_date: item.end_date && `${item.end_date}`,183            }184          }) : [''],185    },186    tabExpectations: {187      salary_level: resume.salary_level,188      experience: resume.experience && Object.keys(resume.experience),189      working_schedule: resume.working_schedule && Object.keys(resume.working_schedule),190      employment_type: resume.employment_type && Object.keys(resume.employment_type),191      comment: resume.comment,192      desired_position: resume.desired_position,193    },194    tabRecommendations: {195      resume_recommendations_attributes:196        resume.resume_recommendations.length > 0 ?197          resume.resume_recommendations.map(item => {198            return {199              ...item,200              phone: item.phone ? item.phone : [''],201              email: item.email ? item.email : [''],202            }203          }) :204          [{205            recommender_name: '',206            company_and_position: '',207            phone: [''],208            email: [''],209          }],210    },211  }212}213function updateComment(state, comment) {214  const { current } = state215  if (comment.success){216    const candidateVacancy = current.candidate_vacancies.find(it => (it.id === comment.data.commentable_id))217    candidateVacancy.comments.push(comment.data)218    current.candidate_changes = [219      {220        id: `100000${comment.data.id}`,221        change_type: "comment_added",222        change_for: comment.data,223        account: comment.data.account,224      },225      ...current.candidate_changes,226    ]227  }228  return {229    ...state,230    current,231  }232}233function changedCandidate(list, payload) {234  return list.map(candidate => {235    if (candidate.id === payload.id) {236      return payload237    }238    return candidate239  })240}241function changedCandidates(list, payload) {242  return list.map(candidate => {243    const newCandidate = payload.find(({ id }) => candidate.id === id )244    if (newCandidate) {245      return newCandidate246    }247    return candidate248  })249}250export default (state = initialState, action) => {251  switch (action.type) {252    case 'TOGGLE_SIDEBAR':253      return { ...state, sidebar: action.payload }254    case 'CLOSE_SIDEBAR':255      return { ...state, sidebar: initialState.sidebar }256    case 'TOGGLE_ADVANCED_SEARCH':257      return {258        ...state,259        search: { ...state.search, showAdvanced: !state.search.showAdvanced }260      }261    case 'UPDATE_CANDIDATES_SEARCH_STATE':262      return {263        ...state,264        search: { ...state.search, ...action.payload }265      }266    case 'GET_CANDIDATES_RES':267      return {268        ...state,269        data: unionBy(state.data, action.payload.data, 'id'),270        scroll: action.payload.data.length === state.perPage,271        page: action.page + 1,272      }273    case 'GET_CANDIDATES_GROUP_RES':274      return {275        ...state,276        groupCandidates: unionBy(state.groupCandidates, action.payload.data, 'id'),277        scroll: action.payload.data.length === state.perPage,278        page: action.page + 1,279      }280    case 'GET_CURRENT_CANDIDATE_RES':281    case 'UPLOAD_FILE_TO_CANDIDATE_RES':282    case 'LINK_CANDIDATE_TO_VACANCY_RES':283      return { ...state, current: action.payload }284    case 'SEND_CANDIDATE_COMMENT_RES':285      return updateComment(state, action.payload)286    case 'UPDATE_CURRENT_CANDIDATE_RES':287    case 'CHANGE_STAGE_CANDIDATE_RES':288    case 'SEND_RATING_RES':289      return {290        ...state,291        current: action.payload,292        data: changedCandidate(state.data, action.payload),293      }294    case 'RELEASE_CURRENT_CANDIDATE':295      return { ...state, current: initialState.current }296    case 'RESET_CANDIDATES_GROUP':297      return { ...state, groupCandidates: initialState.groupCandidates, page: action.page, groupId: initialState.groupId }298    case 'RESET_CANDIDATES':299      return { ...state, data: initialState.data, groupCandidates: initialState.groupCandidates, page: initialState.page, groupId: initialState.groupId }300    case 'GET_CANDIDATES_STATS_RES':301      return { ...state, stats: action.payload }302    case 'TOGGLE_LINKED_CANDIDATE_MODAL':303      return { ...state, openLinkedCandidateModal: action.payload }304    case 'ADVANCED_SEARCH_CANDIDATE_RES':305      return {306        ...state,307        search: {308          ...state.search,309          count: action.payload.count,310          now: true,311          data: state.page === 1 ? action.payload.data : [...state.search.data, ...action.payload.data],312        },313        scroll: action.payload.data.length === state.perPage,314        page: state.page + 1,315        filter: action.filter,316      }317    // case 'RESET_ADVANCED_SEARCH_CANDIDATE_RES':318    //   return { ...state, search: initialState.search }319    case 'GET_SELECT_CANDIDATES_RES':320      return { ...state, select: action.payload }321    case 'CLEAR_SELECT_CANDIDATES':322      return { ...state, select: initialState.select }323    case 'RESET_SEARCH_CANDIDATES':324      return { ...state, search: initialState.search , filter: null}325    case 'GET_RESUME_SOURCES_RES':326      return { ...state, sources: action.payload }327    case 'GET_LANGUAGES_RES':328      return { ...state, languages: action.payload }329    case 'GET_LANGUAGES_LEVEL_RES':330      return { ...state, languagesLevel: action.payload }331    case 'GET_SPECIALIZATION_RES':332      return { ...state, specialization: action.payload }333    case 'GET_EDUCATION_LEVEL_RES':334      return { ...state, educationLevel: action.payload }335    case 'PARSING_FILE_TO_CANDIDATE_RES':336      return { ...state, parsedResume: parsingData(action.payload) }337    case 'CREATE_CANDIDATE_RES':338    case 'PARSING_RESET':339      return { ...state, parsedResume: initialState.parsedResume }340    case 'REPLACE_CANDIDATES_AFTER_VACANCY_LINK':341      return {342        ...state,343        data: changedCandidates(state.data, action.payload),344      }345    case 'GET_CANDIDATES_GROUP_REQ':346      return {...state, groupId: action.payload.groupId }347    case 'SET_INITIAL_RESUME_VIEW':348      return { ...state, resumeTabSwitcher: initialState.resumeTabSwitcher }349    case 'SWITCH_RESUME_VIEW':350      return { ...state, resumeTabSwitcher: action.payload }351    case 'CREATE_CANDIDATE_REQ':352    case 'CREATE_CANDIDATE_FAIL':353    case 'PARSING_FILE_TO_CANDIDATE_REQ':354    case 'PARSING_FILE_TO_CANDIDATE_FAIL':355    case 'GET_CURRENT_CANDIDATE_REQ':356    case 'GET_CANDIDATES_GROUP_FAIL':357    case 'UPDATE_CURRENT_CANDIDATE_REQ':358    case 'GET_CURRENT_CANDIDATE_FAIL':359    case 'UPDATE_CURRENT_CANDIDATE_FAIL':360    case 'GET_RESUME_SOURCES_REQ':361    case 'GET_RESUME_SOURCES_FAIL':362    case 'GET_LANGUAGES_REQ':363    case 'GET_LANGUAGES_FAIL':364    case 'GET_SPECIALIZATION_REQ':365    case 'GET_SPECIALIZATION_FAIL':366    case 'GET_LANGUAGES_LEVEL_REQ':367    case 'GET_LANGUAGES_LEVEL_FAIL':368    case 'GET_EDUCATION_LEVEL_REQ':369    case 'GET_EDUCATION_LEVEL_FAIL':370    case 'UPLOAD_FILE_TO_CANDIDATE_REQ':371    case 'UPLOAD_FILE_TO_CANDIDATE_FAIL':372    case 'CHANGE_STAGE_CANDIDATE_REQ':373    case 'CHANGE_STAGE_CANDIDATE_FAIL':374    case 'SEND_CANDIDATE_COMMENT_REQ':375    case 'SEND_CANDIDATE_COMMENT_FAIL':376    case 'SEND_RATING_REQ':377    case 'SEND_RATING_FAIL':378    case 'ADVANCED_SEARCH_CANDIDATE_REQ':379    case 'ADVANCED_SEARCH_CANDIDATE_FAIL':380    case 'GET_SELECT_CANDIDATES_FAIL':381    case 'GET_SELECT_CANDIDATES_REQ':382    case 'GET_CANDIDATES_STATS_REQ':383    case 'GET_CANDIDATES_STATS_FAIL':384      return state385    default:386      return state387  }...index.js
Source:index.js  
1import React, {Component} from 'react'2import {connect} from 'react-redux'3import {FormSection, reduxForm} from 'redux-form'4import {Link} from 'react-router-dom'5import {isEqual, isEmpty, get} from 'lodash'6import {Row, Col} from 'react-bootstrap'7import CandidateTabGetResume from './FormSectionNewCandidate/CandidateTabGetResume'8import CandidateTabFullName from './FormSectionNewCandidate/CandidateTabFullName'9import CandidateTabContactInformation from './FormSectionNewCandidate/CandidateTabContactInformation'10import CandidateTabBasicInformation from './FormSectionNewCandidate/CandidateTabBasicInformation'11import CandidateTabExperience from './FormSectionNewCandidate/CandidateTabExperience'12import CandidateTabAchievements from './FormSectionNewCandidate/CandidateTabAchievements'13import CandidateTabExpectations from './FormSectionNewCandidate/CandidateTabExpectations'14import CandidateTabRecommendations from './FormSectionNewCandidate/CandidateTabRecommendations'15import CandidateTabResume from './FormSectionNewCandidate/CandidateTabResume'16import scrollToComponent from "components-folder/ScrollToComponent";17import {18  createCandidate, parsingReset,19  updateCandidate,20} from '../../../../redux/actions/candidatesActions'21import type {Dispatch} from '../../../../types/actions'22import type {ResumeSourceRaw, VacancyRaw} from '../../../../types/raws'23import compose from "ramda/src/compose";24import {toastr} from "react-redux-toastr";25import ReactDOM from "react-dom";26import moment from "moment/moment";27import {candidateRecommendation} from "../../../../lib/validation";28const cn = require('bem-cn')('new-candidate')29if (process.env.BROWSER) {30  require('./style.css')31  require('./new-candidate.css')32}33type Props = {34  dispatch: Dispatch,35  stageVacancies: Array<VacancyRaw>,36  state: {},37  candidateId: number,38  sources: Array<{}>,39  sources: Array<ResumeSourceRaw>,40}41const connector = compose(reduxForm({42    form: 'NewCandidateForm',43    enableReinitialize: true,44    keepDirtyOnReinitialize: true,45    initialValues: {46      fullName: {47        candidate_vacancies_attributes: [''],48      },49      contactInformation: {50        additional_contacts_attributes: [''],51        preferred_contact_type: '0-phone',52        phones: [''],53        emails: [''],54      },55      achievements: {56        resume_educations_attributes: [''],57        resume_courses_attributes: [''],58        resume_certificates_attributes: [''],59      },60      experience: {61        resume_work_experiences_attributes: [''],62      },63      tabRecommendations: {64        resume_recommendations_attributes: [{}],65      },66      basicInformation: {67        language_skills_attributes: [''],68      },69      tabExpectations: {70        salary_level: null,71        experience: null,72        working_schedule: null,73        employment_type: null,74        comment: null,75        desired_position: null,76      },77      tabResume: {78        resume_text: null,79      }80    },81  }),82  connect(state => ({83    sources: state.candidates.sources,84    form: state.form.NewCandidateForm,85    languagesLevel: state.candidates.languagesLevel,86    languages: state.candidates.languages,87    initialValues: state.candidates.parsedResume,88    candidate: state.candidates.current,89    specialization: state.candidates.specialization,90    education: state.candidates.educationLevel,91    state,92  })))93function preferredContact(contacts) {94  if (contacts.length === 0) return '0-phone'95  const contact = contacts.find(item => item.preferred)96  if (!contact) return '0-phone'97  let prefer = ''98  let emails = 099  let phones = 0100  contacts.forEach((item) => {101    if (item.preferred && item.contact_type === 'email') {102      prefer = `${emails}-${item.contact_type}`103    }104    if (item.preferred && item.contact_type === 'phone') {105      prefer = `${phones}-${item.contact_type}`106    }107    if (item.contact_type === 'email') emails = emails + 1108    if (item.contact_type === 'phone') phones = phones + 1109  })110  return prefer111}112class NewCandidateForm extends Component<Props> {113  componentDidMount() {114    const {initialize, candidateId, candidate, specialization} = this.props115    if (candidateId) {116      const {resume} = candidate117      let group = {}118      if (resume.professional_specializations.length > 0) {119        group = this.specializationOptionsForSelect(specialization).filter(it => it.options.map(({value}) => (value)).includes(resume.professional_specializations[0].id))[0]120      }121      initialize({122        fullName: {123          city: resume.city,124          first_name: candidate.first_name,125          last_name: candidate.last_name,126          middle_name: candidate.middle_name,127          resume_source_id: resume.resume_source_id,128          candidate_vacancies_attributes:129            candidate.candidate_vacancies.length > 0130              ? candidate.candidate_vacancies.map(item => item.vacancy_id)131              : [''],132          photo: resume.photo.url,133          documents: get(resume, 'resume_documents') ? resume.resume_documents.map(item => item) : [''],134        },135        contactInformation: {136          emails: resume.resume_contacts.filter(item => item.contact_type === 'email').length > 0 ?137            resume.resume_contacts.filter(item => item.contact_type === 'email').map(item => ({email: item.value})) : [''],138          phones: resume.resume_contacts.filter(item => item.contact_type === 'phone').length > 0 ?139            resume.resume_contacts.filter(item => item.contact_type === 'phone').map(item => ({phone: item.value})) : [''],140          skype: resume.resume_contacts.find(item => item.contact_type === 'skype') ?141            resume.resume_contacts.find(item => item.contact_type === 'skype').value : '',142          preferred_contact_type: preferredContact(resume.resume_contacts),143          additional_contacts_attributes:144            resume.additional_contacts.length > 0 ? resume.additional_contacts : [''],145        },146        achievements: {147          education_level_id: resume.education_level_id,148          resume_educations_attributes:149            resume.resume_educations && resume.resume_educations.length > 0150              ? resume.resume_educations.map(item => {151                return {152                  ...item,153                  end_year: item.end_year && `${item.end_year}`,154                }155              })156              : [''],157          resume_certificates_attributes:158            resume.resume_certificates && resume.resume_certificates.length > 0159              ? resume.resume_certificates.map(item => {160                return {161                  company_name: item.company_name ? item.company_name : null,162                  name: item.name ? item.name : null,163                  end_date: item.end_date && `${moment(item.end_year).format('YYYY')}`,164                }165              })166              : [''],167          resume_courses_attributes:168            resume.resume_courses && resume.resume_courses.length > 0169              ? resume.resume_courses.map(item => {170                return {171                  company_name: item.company_name ? item.company_name : null,172                  name: item.name ? item.name : null,173                  end_year: item.end_year && `${moment(item.end_year).format('YYYY')}`,174                }175              })176              : [''],177        },178        tabRecommendations: {179          resume_recommendations_attributes:180            resume.resume_recommendations.length > 0 ? resume.resume_recommendations : [''],181        },182        basicInformation: {183          birthdate: !isEmpty(candidate.birthdate) ? moment(candidate.birthdate).format('DD.MM.YYYY') : null,184          sex: resume.sex,185          skills: resume.skills,186          skills_description: resume.skills_description,187          language_skills_attributes:188            resume.language_skills.length > 0 ? resume.language_skills : [''],189        },190        tabResume: {191          resume_text: resume.resume_text,192        },193        tabExpectations: {194          salary_level: resume.salary_level && resume.salary_level.toString().replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 '),195          experience: resume.experience,196          working_schedule: resume.working_schedule,197          employment_type: resume.employment_type,198          comment: resume.comment,199          desired_position: resume.desired_position,200          professional_specialization_ids: resume.professional_specializations.length > 0 ? resume.professional_specializations.map((it) => ({201            group: group,202            label: it.name,203            value: it.id,204          })) : null,205        },206        experience: {207          resume_work_experiences_attributes:208            resume.resume_work_experiences.length > 0209              ? resume.resume_work_experiences.map(item => {210                return {211                  ...item,212                  nowadays: !item.end_date,213                }214              })215              : [''],216        },217      })218    }219  }220  specializationOptionsForSelect = specialization =>221    specialization.map(item => {222      return {223        label: item.name,224        options: item.professional_specializations.map(spec => {225          return {label: spec.name, value: spec.id}226        }),227      }228    })229  onSubmit = () => {230    const {dispatch, state, candidateId} = this.props231    if (candidateId) {232      dispatch(updateCandidate({state}))233    } else {234      dispatch(createCandidate({state}))235    }236  }237  checkError() {238    if (ReactDOM.findDOMNode(this).getElementsByClassName('form-group__error')[0]) {239      scrollToComponent(ReactDOM.findDOMNode(this).getElementsByClassName('form-group__error')[0], {240        offset: 0,241        duration: 1000242      })243    }244  }245  componentDidUpdate(prevProps) {246    if (!prevProps.submitFailed && this.props.submitFailed) {247      scrollToComponent(ReactDOM.findDOMNode(this).getElementsByClassName('form-group__error')[0], {248        offset: 0,249        duration: 1000,250      })251      toastr.error('ÐÑовеÑÑÑе пÑавилÑноÑÑÑ Ð·Ð°Ð¿Ð¾Ð»Ð½ÐµÐ½ÑÑ
 полей.')252    }253  }254  componentWillUnmount() {255    const {dispatch} = this.props256    dispatch(parsingReset())257  }258  componentWillReceiveProps(nextProps) {259    if (!isEqual(this.props.initialValues, nextProps.initialValues)) {260      this.props.initialize(nextProps.initialValues)261    }262  }263  render() {264    const {265      specialization,266      education,267      stageVacancies,268      candidateId,269      handleSubmit,270      dispatch,271      sources,272      form,273      languages,274      languagesLevel,275      contactInformation,276      candidate277    } = this.props278    const checkedLanguageIds = form.values.basicInformation.language_skills_attributes.map( it => get(it, 'language_id.value') )279    const languageForChoose = languages.filter( it => !checkedLanguageIds.includes(it.id) )280    return (281      <div className='candidate'>282        <div className={cn}>283          <form284            onSubmit={handleSubmit(this.onSubmit)}285            onKeyPress={e => {286              if (e.key === 'Enter') e.preventDefault();287            }}288          >289            <FormSection name="candidateDocuments">290              <CandidateTabGetResume dispatch={dispatch}/>291            </FormSection>292            <FormSection name="fullName">293              <CandidateTabFullName form={form} dispatch={dispatch} sources={sources} stageVacancies={stageVacancies}/>294            </FormSection>295            <FormSection name="contactInformation">296              <CandidateTabContactInformation candidateId={candidateId} candidate={candidate}297                                              contactInformation={contactInformation}/>298            </FormSection>299            <FormSection name="tabResume">300              <CandidateTabResume candidateId={candidateId}/>301            </FormSection>302            <FormSection name="basicInformation">303              <CandidateTabBasicInformation candidateId={candidateId} languages={languageForChoose}304                                            languagesLevel={languagesLevel}/>305            </FormSection>306            <FormSection name="experience">307              <CandidateTabExperience/>308            </FormSection>309            <FormSection name="achievements">310              <CandidateTabAchievements candidateId={candidateId} education={education}/>311            </FormSection>312            <FormSection name="tabExpectations">313              <CandidateTabExpectations candidateId={candidateId} specialization={specialization}/>314            </FormSection>315            <FormSection name="tabRecommendations">316              <CandidateTabRecommendations candidateId={candidateId}/>317            </FormSection>318            <Row>319              <Col xs={12}>320                <button className={'btn btn-primary btn-margin-right '} onClick={() => this.checkError()}>СоÑ
ÑаниÑÑ321                </button>322                <Link to={'/recruitment/candidates'}323                      className="btn btn-outline">ÐÑмениÑÑ</Link>324              </Col>325            </Row>326          </form>327        </div>328      </div>329    )330  }331}...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
