code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# together with waitkeys later, helps to close the video window effectively _cv2.startWindowThread() for frame in stream.frame_generator(): if frame is not None: _cv2.imshow('Video', frame) _cv2.moveWindow('Video',5,5) else: break key = _...
def preview_stream(stream)
Display stream in an OpenCV window until "q" key is pressed
3.915099
3.664649
1.068342
try: recst = recst.decode('UTF-8') except AttributeError: pass recs=[ x for x in recst.split('\r\n') if x ] for rec in recs: print(rec) print("\n")
def printrec(recst)
Pretty-printing rtsp strings
3.052402
2.908397
1.049513
resp = connection.describe(verbose=False).split('\r\n') resources = [x.replace('a=control:','') for x in resp if (x.find('control:') != -1 and x[-1] != '*' )] return resources
def get_resources(connection)
Do an RTSP-DESCRIBE request, then parse out available resources from the response
8.337197
6.208644
1.342837
self.rtsp_seq += 1 uri = '/'.join([s.strip('/') for s in (self.server,self.stream_path,resource_path)]) ## example: SETUP rtsp://example.com/foo/bar/baz.rm RTSP/2.0 request = f"SETUP rtsp://{uri} {RTSP_VER}\r\n" request+= f"CSeq: {self.rtsp_seq}\r\n" re...
def setup(self,resource_path = "track1")
SETUP method defined by RTSP Protocol - https://tools.ietf.org/html/rfc7826#section-13.3
3.543703
3.29459
1.075613
self._check_ffmpeg() cmd = "ffmpeg -rtsp_transport tcp -i {} -loglevel quiet -frames 1 -f image2pipe -".format(rtsp_server_uri) #stdout = _sp.check_output(ffmpeg_cmd,timeout = timeout_secs) with _sp.Popen(cmd, shell=True, stdout=_sp.PIPE) as process: try: ...
def fetch_image(self,rtsp_server_uri = _source,timeout_secs = 15)
Fetch a single frame using FFMPEG. Convert to PIL Image. Slow.
2.851722
2.741007
1.040392
'''根据命令执行操作''' global CUR_RANGE,CUR_SCALE if cmd in ('exit','teardown'): rtsp.do_teardown() elif cmd == 'pause': CUR_SCALE = 1; CUR_RANGE = 'npt=now-' rtsp.do_pause() elif cmd == 'help': PRINT(play_ctrl_help()) elif cmd == 'forward': if CUR_SCALE < 0: CUR_...
def exec_cmd(rtsp,cmd)
根据命令执行操作
2.863341
2.823296
1.014184
'''解析url,返回(ip,port,target)三元组''' (ip,port,target) = ('',DEFAULT_SERVER_PORT,'') m = re.match(r'[rtspRTSP:/]+(?P<ip>(\d{1,3}\.){3}\d{1,3})(:(?P<port>\d+))?(?P<target>.*)',url) if m is not None: ip = m.group('ip') port = int(m.group('port')) tar...
def _parse_url(self,url)
解析url,返回(ip,port,target)三元组
3.430026
2.987263
1.148217
'''连接服务器,建立socket''' try: self._sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self._sock.connect((self._server_ip,self._server_port)) #PRINT('Connect [%s:%d] success!'%(self._server_ip,self._server_port), GREEN) except socket.error, e: sy...
def _connect_server(self)
连接服务器,建立socket
2.850253
2.69454
1.057788
'''如果未指定DEST_IP,默认与RTSP使用相同IP''' global DEST_IP if not DEST_IP: DEST_IP = self._sock.getsockname()[0] PRINT('DEST_IP: %s\n'%DEST_IP, CYAN)
def _update_dest_ip(self)
如果未指定DEST_IP,默认与RTSP使用相同IP
8.877783
4.027512
2.204285
'''收取一个完整响应消息或ANNOUNCE通知消息''' try: while True: if HEADER_END_STR in self._recv_buf: break more = self._sock.recv(2048) if not more: break self._recv_buf += more except socket.error, e: PRINT('Receive data err...
def recv_msg(self)
收取一个完整响应消息或ANNOUNCE通知消息
3.70702
2.879825
1.287238
'''从消息中解析Content-length''' m = re.search(r'[Cc]ontent-length:\s?(?P<len>\d+)',msg,re.S) return (m and int(m.group('len'))) or 0
def _get_content_length(self,msg)
从消息中解析Content-length
4.361485
3.5575
1.225997
'''处理响应消息''' status,headers,body = self._parse_response(msg) rsp_cseq = int(headers['cseq']) if self._cseq_map[rsp_cseq] != 'GET_PARAMETER': PRINT(self._get_time_str() + '\n' + msg) if status == 302: self.location = headers['location'] if status !=...
def _process_response(self,msg)
处理响应消息
4.194813
4.1423
1.012677
'''处理ANNOUNCE通知消息''' global CUR_RANGE,CUR_SCALE PRINT(msg) headers = self._parse_header_params(msg.splitlines()[1:]) x_notice_val = int(headers['x-notice']) if x_notice_val in (X_NOTICE_EOS,X_NOTICE_BOS): CUR_SCALE = 1 self.do_play(CUR_RANGE,CUR_SC...
def _process_announce(self,msg)
处理ANNOUNCE通知消息
7.100718
6.50393
1.091758
'''解析响应消息''' header,body = msg.split(HEADER_END_STR)[:2] header_lines = header.splitlines() version,status = header_lines[0].split(None,2)[:2] headers = self._parse_header_params(header_lines[1:]) return int(status),headers,body
def _parse_response(self,msg)
解析响应消息
4.039508
3.708806
1.089167
'''解析头部参数''' headers = {} for line in header_param_lines: if line.strip(): # 跳过空行 key,val = line.split(':', 1) headers[key.lower()] = val.strip() return headers
def _parse_header_params(self,header_param_lines)
解析头部参数
2.849157
2.546879
1.118686
'''从sdp中解析trackID=2形式的字符串''' m = re.search(r'a=control:(?P<trackid>[\w=\d]+)',sdp,re.S) return (m and m.group('trackid')) or ''
def _parse_track_id(self,sdp)
从sdp中解析trackID=2形式的字符串
6.502192
3.626939
1.792749
'''发送消息''' msg = '%s %s %s'%(method,url,RTSP_VERSION) headers['User-Agent'] = DEFAULT_USERAGENT cseq = self._next_seq() self._cseq_map[cseq] = method headers['CSeq'] = str(cseq) if self._session_id: headers['Session'] = self._session_id for (k,v) in header...
def _sendmsg(self,method,url,headers)
发送消息
4.677595
4.716898
0.991668
'''获取SETUP时需要的Transport字符串参数''' transport_str = '' ip_type = 'unicast' #if IPAddress(DEST_IP).is_unicast() else 'multicast' for t in TRANSPORT_TYPE_LIST: if t not in TRANSPORT_TYPE_MAP: PRINT('Error param: %s'%t,RED) sys.exit(1) if ...
def _get_transport_type(self)
获取SETUP时需要的Transport字符串参数
6.021136
4.341588
1.386851
'''定时发送GET_PARAMETER消息保活''' if self.running: self.do_get_parameter() threading.Timer(HEARTBEAT_INTERVAL, self.send_heart_beat_msg).start()
def send_heart_beat_msg(self)
定时发送GET_PARAMETER消息保活
7.363174
3.670775
2.005891
if self.state == self.INIT: self.sendRtspRequest(self.SETUP)
def setupMovie(self)
Setup button handler.
16.312798
17.267254
0.944724
self.sendRtspRequest(self.TEARDOWN) #self.handler() os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video rate = float(self.counter/self.frameNbr) print('-'*60 + "\nRTP Packet Loss Rate :" + str(rate) +"\n" + '-'*60) sys.exit(0)
def exitClient(self)
Teardown button handler.
10.886162
10.216319
1.065566
if self.state == self.PLAYING: self.sendRtspRequest(self.PAUSE)
def pauseMovie(self)
Pause button handler.
11.251997
10.454156
1.076318
try: photo = ImageTk.PhotoImage(Image.open(imageFile)) #stuck here !!!!!! except: print("photo error") print('-'*60) traceback.print_exc(file=sys.stdout) print('-'*60) self.label.configure(image = photo, height=288) self.label.image = photo
def updateMovie(self, imageFile)
Update the image file as video frame in the GUI.
4.525313
4.368531
1.035889
self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.rtspSocket.connect((self.serverAddr, self.serverPort)) except: tkinter.messagebox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
def connectToServer(self)
Connect to the Server. Start a new RTSP/TCP session.
2.861819
2.503272
1.143231
#------------- # TO COMPLETE #------------- # Setup request if requestCode == self.SETUP and self.state == self.INIT: threading.Thread(target=self.recvRtspReply).start() # Update RTSP sequence number. # ... self.rtspSeq = 1 # Write the RTSP request to be sent. ...
def sendRtspRequest(self, requestCode)
Send RTSP request to the server.
2.066765
2.045581
1.010356
while True: reply = self.rtspSocket.recv(1024) if reply: self.parseRtspReply(reply) # Close the RTSP socket upon requesting Teardown if self.requestSent == self.TEARDOWN: self.rtspSocket.shutdown(socket.SHUT_RDWR) self.rtspSocket.close() break
def recvRtspReply(self)
Receive RTSP reply from the server.
3.722929
3.622947
1.027597
print("Parsing Received Rtsp data...") lines = data.split('\n') seqNum = int(lines[1].split(' ')[1]) # Process only if the server reply's sequence number is the same as the request's if seqNum == self.rtspSeq: session = int(lines[2].split(' ')[1]) # New RTSP session ID if se...
def parseRtspReply(self, data)
Parse the RTSP reply from the server.
5.246989
5.115132
1.025778
#------------- # TO COMPLETE #------------- # Create a new datagram socket to receive RTP packets from the server # self.rtpSocket = ... # Set the timeout value of the socket to 0.5sec # ... self.rtpSocket.settimeout(0.5) # try: # Bind the socket to the address using the R...
def openRtpPort(self)
Open RTP socket binded to a specified port.
6.098792
6.128047
0.995226
stream = BytesIO() self.cam.capture(stream, format='png') # "Rewind" the stream to the beginning so we can read its content stream.seek(0) return Image.open(stream)
def read(self)
https://picamera.readthedocs.io/en/release-1.13/recipes1.html#capturing-to-a-pil-image
4.538608
3.161322
1.435667
win_name = 'Camera' cv2.namedWindow(win_name, cv2.WINDOW_AUTOSIZE) cv2.moveWindow(win_name,20,20) self.open() while(self.isOpened()): cv2.imshow(win_name,self._stream.read()[1]) if cv2.waitKey(25) & 0xFF == ord('q'): break ...
def preview(self)
Blocking function. Opens OpenCV window to display stream.
2.479739
2.144326
1.156419
# Create Setup button self.setup = Button(self.master, width=20, padx=3, pady=3) self.setup["text"] = "Setup" self.setup["command"] = self.setupMovie self.setup.grid(row=1, column=0, padx=2, pady=2) # Create Play button self.start = Button(self.master, width=20, padx=3, pady=3) sel...
def createWidgets(self)
Build GUI.
1.619957
1.599979
1.012486
if self.state == self.READY: # Create a new thread to listen for RTP packets print "Playing Movie" threading.Thread(target=self.listenRtp).start() self.playEvent = threading.Event() self.playEvent.clear() self.sendRtspRequest(self.PLAY)
def playMovie(self)
Play button handler.
5.354016
5.373193
0.996431
cachename = CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT try: file = open(cachename, "wb") except: print "file open error" try: file.write(data) except: print "file write error" file.close() return cachename
def writeFrame(self, data)
Write the received frame to a temp image file. Return the image file.
3.667716
3.362419
1.090797
self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.rtspSocket.connect((self.serverAddr, self.serverPort)) except: tkMessageBox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
def connectToServer(self)
Connect to the Server. Start a new RTSP/TCP session.
2.818536
2.433594
1.158178
#------------- # TO COMPLETE #------------- # Create a new datagram socket to receive RTP packets from the server # self.rtpSocket = ... # Set the timeout value of the socket to 0.5sec # ... self.rtpSocket.settimeout(0.5) # try: # Bind the socket to the address using the R...
def openRtpPort(self)
Open RTP socket binded to a specified port.
5.956524
5.987744
0.994786
self.pauseMovie() if tkMessageBox.askokcancel("Quit?", "Are you sure you want to quit?"): self.exitClient() else: # When the user presses cancel, resume playing. #self.playMovie() print "Playing Movie" threading.Thread(target=self.listenRtp).start() #self.playEvent = threa...
def handler(self)
Handler on explicitly closing the GUI window.
6.49712
6.377662
1.018731
timestamp = int(time()) print("timestamp: " + str(timestamp)) self.header = bytearray(HEADER_SIZE) #-------------- # TO COMPLETE #-------------- # Fill the header bytearray with RTP header fields #RTP-version filed(V), must set to 2 #padding(P),extension(X),number of contributing sources(CC) and ...
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload)
Encode the RTP packet with header fields and payload.
3.477155
3.436831
1.011733
for pos, element in self.element_iter: tag, class_attr = _tag_and_class_attr(element) if tag == "div" and "thread" in class_attr and pos == "end": break
def skip(self)
Eats through the input iterator without recording the content.
8.394455
8.023551
1.046227
tag, class_attr = _tag_and_class_attr(e) start_of_message = tag == 'div' and class_attr == 'message' and pos == 'start' end_of_thread = tag == 'div' and 'thread' in class_attr and pos == 'end' if start_of_message and not self.messages_started: self.messages_started...
def _process_element(self, pos, e)
Parses an incoming HTML element/node for data. pos -- the part of the element being parsed (start/end) e -- the element being parsed
4.270434
4.283091
0.997045
if not self.thread_filter: return True if len(participants) != len(self.thread_filter): return False participants = [[p.lower()] + p.lower().split(" ") for p in participants] matches = defaultdict(set) for e, p in enumerate...
def should_record_thread(self, participants)
Determines if the thread should be parsed based on the participants and the filter given. For example, if the filter states ['jack', 'billy joe'], then only threads with exactly two participants (excluding the owner of the chat history) containing someone with the first or last ...
2.713082
2.663224
1.018721
# Very rarely threads may lack information on who the # participants are. We will consider those threads corrupted # and skip them. participants_text = _truncate(', '.join(participants), 60) if participants: skip_thread = not self.should_record_thread(partic...
def parse_thread(self, participants, element_iter, require_flush)
Parses a thread with appropriate CLI feedback. :param participants: The participants in this thread. :param element_iter: The XML iterator to parse the data from. :param require_flush: Whether the iterator needs to be flushed if it is determined that the thread sho...
4.642066
4.487044
1.034549
# If progress output was being written, clear it from the screen. if self.progress_output: sys.stderr.write("\r".ljust(self.last_line_len)) sys.stderr.write("\r") sys.stderr.flush()
def _clear_output(self)
Clears progress output (if any) that was written to the screen.
5.573839
4.176919
1.334438
# Cast to str to ensure not unicode under Python 2, as the parser # doesn't like that. parser = XMLParser(encoding=str('UTF-8')) element_iter = ET.iterparse(self.handle, events=("start", "end"), parser=parser) for pos, element in element_iter: tag, class_att...
def parse_impl(self)
Parses the HTML content as a stream. This is far less memory intensive than loading the entire HTML file into memory, like BeautifulSoup does.
4.948129
4.717462
1.048897
with colorize_output(nocolor): try: chat_history = _process_history( path=path, thread=thread, timezones=timezones, utc=utc, noprogress=noprogress, resolve=resolve) except ProcessingFailure: return if directory: set_all...
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory)
Conversion of Facebook chat history.
5.07418
5.089791
0.996933
with colorize_output(nocolor): try: chat_history = _process_history( path=path, thread='', timezones=timezones, utc=utc, noprogress=noprogress, resolve=resolve) except ProcessingFailure: return statistics = ChatHistoryStatistics( ...
def stats(path, fmt, nocolor, timezones, utc, noprogress, most_common, resolve, length)
Analysis of Facebook chat history.
3.039294
2.934081
1.035859
original_stdout = sys.stdout original_stderr = sys.stderr init(strip=disabled) if stream != original_stdout: sys.stdout = original_stdout sys.stderr = BinaryStreamWrapper(stream, sys.stderr) if stream != original_stderr: sys.stderr = original_stderr sys.stdout ...
def set_stream_color(stream, disabled)
Remember what our original streams were so that we can colorize them separately, which colorama doesn't seem to natively support.
3.760164
3.282047
1.145676
resp = self._session.get( 'https://www.facebook.com/%s' % facebook_id, allow_redirects=True, timeout=10 ) # No point in trying to get this using BeautifulSoup. The HTML here # is the very epitome of what it is to be invalid... m = _MANUAL_NAME_MAT...
def _manual_lookup(self, facebook_id, facebook_id_string)
People who we have not communicated with in a long time will not appear in the look-ahead cache that Facebook keeps. We must manually resolve them. :param facebook_id: Profile ID of the user to lookup. :return:
5.34867
5.572765
0.959787
global FACEBOOK_TIMESTAMP_FORMATS timestamp_string, offset = raw_timestamp.rsplit(" ", 1) if "UTC+" in offset or "UTC-" in offset: if offset[3] == '-': offset = [-1 * int(x) for x in offset[4:].split(':')] else: offset = [int(x) for x in offset[4:].split(':')] ...
def parse_timestamp(raw_timestamp, use_utc, hints)
Facebook is highly inconsistent with their timezone formatting. Sometimes it's in UTC+/-HH:MM form, and other times its in the ambiguous PST, PDT. etc format. We have to handle the ambiguity by asking for cues from the user. raw_timestamp -- The timestamp string to parse and convert to UTC.
3.758707
3.689757
1.018687
# Verify params if not isinstance(name, str) or (not name): raise TypeError("invalid name: %r" % name) if not issubclass(base_class, Component): raise TypeError("invalid base_class: %r, must be a %r subclass" % (base_class, Component)) def decorator(cls): # --- Verify ...
def register_exporter(name, base_class)
Register an exporter to use for a :class:`Part <cqparts.Part>`, :class:`Assembly <cqparts.Assembly>`, or both (with :class:`Component <cqparts.Component>`). Registration is necessary to use with :meth:`Component.exporter() <cqparts.Component.exporter>`. :param name: name (or 'key') of exporter ...
3.831322
4.010418
0.955342
if name not in exporter_index: raise TypeError( ("exporter type '%s' is not registered: " % name) + ("registered types: %r" % sorted(exporter_index.keys())) ) for base_class in exporter_index[name]: if isinstance(obj, base_class): return exporter...
def get_exporter(obj, name)
Get an exporter for the :param obj: object to export :type obj: :class:`Component <cqparts.Component>` :param name: registered name of exporter :type name: :class:`str` :return: an exporter instance of the given type :rtype: :class:`Exporter` :raises TypeError: if exporter cannot be found
3.170455
3.265628
0.970856
if name not in importer_index: raise TypeError( ("importer type '%s' is not registered: " % name) + ("registered types: %r" % sorted(importer_index.keys())) ) for base_class in importer_index[name]: if issubclass(cls, base_class): return importer...
def get_importer(cls, name)
Get an importer for the given registered type. :param cls: class to import :type cls: :class:`type` :param name: registered name of importer :type name: :class:`str` :return: an importer instance of the given type :rtype: :class:`Importer` :raises TypeError: if importer cannot be found
3.386106
3.337271
1.014633
# Check if page is out of range no_more_products = re.search( r'No matching products were found', response.css('div.paged-results').extract_first(), flags=re.I ) if no_more_products: pass # no more pages to populate, stop scrapin...
def parse(self, response)
Parse pagenated list of products
3.286917
3.152157
1.042752
# Product Information (a start) product_data = { 'url': response.url, 'name': response.css('div.page-title h1::text').extract_first(), } # Inventory Number inventory_number = re.search( r'(?P<inv_num>\d+)$', response.css('...
def parse_detail(self, response)
Parse individual product's detail
3.105494
3.140933
0.988717
if coord_sys is None: coord_sys = CoordSystem() # default # Verify list contains constraints for constraint in constraints: if not isinstance(constraint, Constraint): raise ValueError("{!r} is not a constraint".format(constraint)) solved_count = 0 indexed = list...
def solver(constraints, coord_sys=None)
Solve constraints. Solutions pair :class:`Constraint <cqparts.constraint.Constraint>` instances with their suitable :class:`CoordSystem <cqparts.utils.geometry.CoordSystem>` world coordinates. :param constraints: constraints to solve :type constraints: iterable of :class:`Constraint <cqparts.constraint...
4.448999
4.138938
1.074913
if isinstance(solid_in, cadquery.Solid): return solid_in elif isinstance(solid_in, cadquery.CQ): return solid_in.val() raise CastingError( "Cannot cast object type of {!r} to a solid".format(solid_in) )
def solid(solid_in)
:return: cadquery.Solid instance
3.530418
3.200902
1.102945
if isinstance(vect_in, cadquery.Vector): return vect_in elif isinstance(vect_in, (tuple, list)): return cadquery.Vector(vect_in) raise CastingError( "Cannot cast object type of {!r} to a vector".format(vect_in) )
def vector(vect_in)
:return: cadquery.Vector instance
3.28914
2.815633
1.168171
return cadquery.Workplane('XY') \ .circle(self.access_diameter / 2) \ .extrude(self.access_height)
def make_cutter(self)
Create solid to subtract from material to make way for the fastener's head (just the head)
4.73715
3.968466
1.193698
# cast version version = LooseVersion(version_str) for (test_ver, classifier) in reversed(sorted(VERSION_CLASSIFIER_MAP, key=lambda x: x[0])): if version >= test_ver: return classifier raise ValueError("could not find valid 'Development Status' classifier for v{}".format(versi...
def version_classifier(version_str)
Verify version consistency: version number must correspond to the correct "Development Status" classifier :raises: ValueError if error found, but ideally this function does nothing
5.497758
4.401357
1.249105
" top of the stator" return Mate(self, CoordSystem( origin=(0, 0, self.length/2), xDir=(0, 1, 0), normal=(0, 0, 1) ))
def mate_top(self)
top of the stator
5.574539
4.253803
1.310484
" bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
def mate_bottom(self)
bottom of the stator
5.183771
4.176589
1.241149
" return mount points" wp = cq.Workplane("XY") h = wp.rect(self.hole_spacing,self.hole_spacing ,forConstruction=True).vertices() return h.objects
def mount_points(self)
return mount points
15.137451
15.737667
0.961861
" shaft cutout " stepper_shaft = self.components['shaft'] top = self.components['topcap'] local_obj = top.local_obj local_obj = local_obj.cut(stepper_shaft.get_cutout(clearance=0.5))
def apply_cutout(self)
shaft cutout
9.77994
8.433398
1.159668
param_names = set( k for (k, v) in cls.__dict__.items() if isinstance(v, Parameter) ) for parent in cls.__bases__: if hasattr(parent, 'class_param_names'): param_names |= parent.class_param_names(hidden=hidden) if not hidden: ...
def class_param_names(cls, hidden=True)
Return the names of all class parameters. :param hidden: if ``False``, excludes parameters with a ``_`` prefix. :type hidden: :class:`bool` :return: set of parameter names :rtype: :class:`set`
2.131265
2.430652
0.876828
param_names = cls.class_param_names(hidden=hidden) return dict( (name, getattr(cls, name)) for name in param_names )
def class_params(cls, hidden=True)
Gets all class parameters, and their :class:`Parameter` instances. :return: dict of the form: ``{<name>: <Parameter instance>, ... }`` :rtype: :class:`dict` .. note:: The :class:`Parameter` instances returned do not have a value, only a default value. To g...
3.081489
4.123779
0.747249
param_names = self.class_param_names(hidden=hidden) return dict( (name, getattr(self, name)) for name in param_names )
def params(self, hidden=True)
Gets all instance parameters, and their *cast* values. :return: dict of the form: ``{<name>: <value>, ... }`` :rtype: :class:`dict`
3.906739
4.778984
0.817483
return { # Encode library information (future-proofing) 'lib': { 'name': 'cqparts', 'version': __version__, }, # class & name record, for automated import when decoding 'class': { 'module': type(...
def serialize(self)
Encode a :class:`ParametricObject` instance to an object that can be encoded by the :mod:`json` module. :return: a dict of the format: :rtype: :class:`dict` :: { 'lib': { # library information 'name': 'cqparts', 'ver...
8.65287
5.586523
1.548883
# Get parameter data class_params = self.class_params() instance_params = self.params() # Serialize each parameter serialized = {} for name in class_params.keys(): param = class_params[name] value = instance_params[name] seri...
def serialize_parameters(self)
Get the parameter data in its serialized form. Data is serialized by each parameter's :meth:`Parameter.serialize` implementation. :return: serialized parameter data in the form: ``{<name>: <serial data>, ...}`` :rtype: :class:`dict`
3.472149
3.313366
1.047922
# Import module & get class try: module = import_module(data.get('class').get('module')) cls = getattr(module, data.get('class').get('name')) except ImportError: raise ImportError("No module named: %r" % data.get('class').get('module')) except...
def deserialize(data)
Create instance from serial data
2.657076
2.608432
1.018649
def inner(cls): # Add class references to search index class_list.add(cls) for (category, value) in criteria.items(): index[category][value].add(cls) # Retain search criteria _entry = dict((k, set([v])) for (k, v) in criteria.items()) if cls not in ...
def register(**criteria)
class decorator to add :class:`Part <cqparts.Part>` or :class:`Assembly <cqparts.Assembly>` to the ``cqparts`` search index: .. testcode:: import cqparts from cqparts.params import * # Created Part or Assembly @cqparts.search.register( type='motor', cur...
3.758141
3.909836
0.961202
# Find all parts that match the given criteria results = copy(class_list) # start with full list for (category, value) in criteria.items(): results &= index[category][value] return results
def search(**criteria)
Search registered *component* classes matching the given criteria. :param criteria: search criteria of the form: ``a='1', b='x'`` :return: parts registered with the given criteria :rtype: :class:`set` Will return an empty :class:`set` if nothing is found. :: from cqparts.search import se...
10.586845
13.131239
0.806234
# Find all parts that match the given criteria results = search(**criteria) # error cases if len(results) > 1: raise SearchMultipleFoundError("%i results found" % len(results)) elif not results: raise SearchNoneFoundError("%i results found" % len(results)) # return found P...
def find(**criteria)
Find a single *component* class with the given criteria. Finds classes indexed with :meth:`register` :raises SearchMultipleFoundError: if more than one result found :raises SearchNoneFoundError: if nothing found :: from cqparts.search import find import cqparts_motors # example of a...
6.349393
5.652617
1.123266
def decorator(func): def inner(*args, **kwargs): merged_kwargs = copy(common) merged_kwargs.update(kwargs) return func(*args, **merged_kwargs) return inner return decorator
def common_criteria(**common)
Wrap a function to always call with the given ``common`` named parameters. :property common: criteria common to your function call :return: decorator function :rtype: :class:`function` .. doctest:: >>> import cqparts >>> from cqparts.search import register, search, find >>> fr...
2.967277
4.145309
0.715816
# Verify types if not all(isinstance(x, cadquery.BoundBox) for x in bb_list): raise TypeError( "parameters must be cadquery.BoundBox instances: {!r}".format(bb_list) ) if len(bb_list) <= 1: return bb_list[0] # if only 1, nothing to merge; simply return it # Fi...
def merge_boundboxes(*bb_list)
Combine bounding boxes to result in a single BoundBox that encloses all of them. :param bb_list: List of bounding boxes :type bb_list: :class:`list` of :class:`cadquery.BoundBox`
3.735316
3.565063
1.047756
return cls( origin=plane.origin.toTuple(), xDir=plane.xDir.toTuple(), normal=plane.zDir.toTuple(), )
def from_plane(cls, plane)
:param plane: cadquery plane instance to base coordinate system on :type plane: :class:`cadquery.Plane` :return: duplicate of the given plane, in this class :rtype: :class:`CoordSystem` usage example: .. doctest:: >>> import cadquery >>> from cqparts.ut...
4.123015
4.478142
0.920698
r # Create reference points at origin offset = FreeCAD.Vector(0, 0, 0) x_vertex = FreeCAD.Vector(1, 0, 0) # vertex along +X-axis z_vertex = FreeCAD.Vector(0, 0, 1) # vertex along +Z-axis # Transform reference points offset = matrix.multiply(offset) x_ve...
def from_transform(cls, matrix)
r""" :param matrix: 4x4 3d affine transform matrix :type matrix: :class:`FreeCAD.Matrix` :return: a unit, zero offset coordinate system transformed by the given matrix :rtype: :class:`CoordSystem` Individual rotation & translation matricies are: .. math:: R...
3.173533
3.163812
1.003073
if seed is not None: random.seed(seed) def rand_vect(min, max): return ( random.uniform(min, max), random.uniform(min, max), random.uniform(min, max), ) while True: try: ret...
def random(cls, span=1, seed=None)
Creates a randomized coordinate system. Useful for confirming that an *assembly* does not rely on its origin coordinate system to remain intact. For example, the :class:`CoordSysIndicator` *assembly* aligns 3 boxes along each of the :math:`XYZ` axes. Positioning it randomly by ...
4.513255
5.015549
0.899853
from .. import Part def inner(*args, **kwargs): part_class = type(func.__name__, (Part,), { 'make': lambda self: func(*args, **kwargs), }) return part_class() inner.__doc__ = func.__doc__ return inner
def as_part(func)
Converts a function to a :class:`Part <cqparts.Part>` instance. So the conventionally defined *part*:: import cadquery from cqparts import Part from cqparts.params import Float class Box(Part): x = Float(1) y = Float(2) z = Float(4) ...
3.511014
4.500966
0.780058
result = self.search(*args, **kwargs) if len(result) == 0: raise SearchNoneFoundError("nothing found") elif len(result) > 1: raise SearchMultipleFoundError("more than one result found") return result[0]
def find(self, *args, **kwargs)
Performs the same action as :meth:`search` but asserts a single result. :return: :raises SearchNoneFoundError: if nothing was found :raises SearchMultipleFoundError: if more than one result is found
3.035281
2.125671
1.427916
# Verify component if not isinstance(obj, Component): raise TypeError("can only add(%r), component is a %r" % ( Component, type(obj) )) # Serialize object obj_data = obj.serialize() # Add to database q = tinydb.Query() ...
def add(self, id, obj, criteria={}, force=False, _check_id=True)
Add a :class:`Component <cqparts.Component>` instance to the database. :param id: unique id of entry, can be anything :type id: :class:`str` :param obj: component to be serialized, then added to the catalogue :type obj: :class:`Component <cqparts.Component>` :param criteria: arb...
3.764938
3.435478
1.095899
result = self.find(*args, **kwargs) return self.deserialize_item(result)
def get(self, *args, **kwargs)
Combination of :meth:`find` and :meth:`deserialize_item`; the result from :meth:`find` is deserialized and returned. Input is a :mod:`tinydb` query. :return: deserialized object instance :rtype: :class:`Component <cqparts.Component>`
7.368346
3.888218
1.895044
edge = self.result.wire().val().Edges()[0] return edge.Vertices()[0].Center()
def start_point(self)
Start vertex of effect :return: vertex (as vector) :rtype: :class:`cadquery.Vector`
32.338856
22.580807
1.432139
coordsys = copy(self.location) coordsys.origin = self.start_point return coordsys
def start_coordsys(self)
Coordinate system at start of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's start point. :return: coordinate system at start of effect :rtype: :class:`CoordSys`
8.651795
8.911314
0.970878
coordsys = copy(self.location) coordsys.origin = self.end_point return coordsys
def end_coordsys(self)
Coordinate system at end of effect. All axes are parallel to the original vector evaluation location, with the origin moved to this effect's end point. :return: coordinate system at end of effect :rtype: :class:`CoordSys`
8.682883
9.155908
0.948337
return self.start_point.sub(self.location.origin).dot(-self.location.zDir)
def origin_displacement(self)
planar distance of start point from self.location along :math:`-Z` axis
17.523947
7.631797
2.296176
# Method: using each solid's bounding box: # - get vector from start to bounding box center # - get vector from bounding box center to any corner # - add the length of both vectors # - return the maximum of these from all solids def max_length_iter(): ...
def max_effect_length(self)
:return: The longest possible effect vector length. :rtype: float In other words, the *radius* of a sphere: - who's center is at ``start``. - all ``parts`` are contained within the sphere.
8.103177
7.712042
1.050717
# Create effect vector (with max length) if not self.max_effect_length: # no effect is possible, return an empty list return [] edge = cadquery.Edge.makeLine( self.location.origin, self.location.origin + (self.location.zDir * -(self.max_ef...
def perform_evaluation(self)
Determine which parts lie along the given vector, and what length :return: effects on the given parts (in order of the distance from the start point) :rtype: list(:class:`VectorEffect`)
5.315223
4.611396
1.152628
disp_env = get_display_environment() if disp_env is None: raise LookupError('valid display environment could not be found') disp_env.display(component, **kwargs)
def display(component, **kwargs)
Display the given component based on the environment it's run from. See :class:`DisplayEnvironment <cqparts.display.environment.DisplayEnvironment>` documentation for more details. :param component: component to display :type component: :class:`Component <cqparts.Component>` Additional parameters ...
6.069875
4.898984
1.239007
# Pop named args template = kwargs.pop('template', 'default') doc = kwargs.pop('doc', "render properties") params = {} # Template parameters if template in TEMPLATE: params.update(TEMPLATE[template]) # override template with any additional params params.update(kwargs) ...
def render_props(**kwargs)
Return a valid property for cleaner referencing in :class:`Part <cqparts.Part>` child classes. :param template: name of template to use (any of ``TEMPLATE.keys()``) :type template: :class:`str` :param doc: description of parameter for sphinx docs :type doc: :class:`str` :return: render propert...
8.055707
6.016451
1.338947
self.world_coords = world_coords return workplane.cut(self.world_obj)
def apply(self, workplane, world_coords=CoordSystem())
Application of screwdrive indentation into a workplane (centred on the given world coordinates). :param workplane: workplane with solid to alter :type workplane: :class:`cadquery.Workplane` :param world_coords: coorindate system relative to ``workplane`` to move ...
8.886472
7.849154
1.132157
from ..params import ParametricObject def param_lines(app, obj): params = obj.class_params(hidden=(not hide_private)) # Header doc_lines = [] if params: # only add a header if it's relevant doc_lines += [ ":class:`ParametricObject <cqparts.par...
def add_parametric_object_params(prepend=False, hide_private=True)
Add :class:`ParametricObject <cqparts.params.ParametricObject>` parameters in a list to the *docstring*. This is only intended to be used with *sphinx autodoc*. In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import add_parametric_object_params def setup(app): ...
4.26597
3.947648
1.080636
from ..search import class_criteria from .. import Component COLUMN_INFO = [ # (<title>, <width>, <method>), ('Key', 50, lambda k, v: "``%s``" % k), ('Value', 10, lambda k, v: ', '.join("``%s``" % w for w in v)), ] # note: last column width is irrelevant def param_li...
def add_search_index_criteria(prepend=False)
Add the search criteria used when calling :meth:`register() <cqparts.search.register>` on a :class:`Component <cqparts.Component>` as a table to the *docstring*. This is only intended to be used with *sphinx autodoc*. In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import add_sear...
4.446895
3.938601
1.129055
from ..params import Parameter def callback(app, what, name, obj, skip, options): if (what == 'class') and isinstance(obj, Parameter): return True # yes, skip this object return None return callback
def skip_class_parameters()
Can be used with :meth:`add_parametric_object_params`, this removes duplicate variables cluttering the sphinx docs. This is only intended to be used with *sphinx autodoc* In your *sphinx* ``config.py`` file:: from cqparts.utils.sphinx import skip_class_parameters def setup(app): ...
7.96408
5.372631
1.482343
last_index = len(items) - 1 for (i, item) in enumerate(items): yield (i == last_index, item)
def indicate_last(items)
iterate through list and indicate which item is the last, intended to assist tree displays of hierarchical content. :return: yielding (<bool>, <item>) where bool is True only on last entry :rtype: generator
3.059236
3.89493
0.785441
initial_path = os.getcwd() os.chdir(path) yield os.chdir(initial_path)
def working_dir(path)
Change working directory within a context:: >>> import os >>> from cqparts.utils import working_dir >>> print(os.getcwd()) /home/myuser/temp >>> with working_dir('..'): ... print(os.getcwd()) ... /home/myuser :param path: working path to use wh...
2.871968
6.607512
0.434652
if self._profile is None: self._profile = self.build_profile() return self._profile
def profile(self)
Buffered result of :meth:`build_profile`
4.08721
2.53229
1.614037
bb = self.profile.val().BoundingBox() return (bb.xmin, bb.xmax)
def get_radii(self)
Get the inner and outer radii of the thread. :return: (<inner radius>, <outer radius>) :rtype: :class:`tuple` .. note:: Ideally this method is overridden in inheriting classes to mathematically determine the radii. Default action is to generate the profile...
25.874237
20.116919
1.286193
(inner_radius, outer_radius) = self.get_radii() radius = (inner_radius + outer_radius) / 2 return cadquery.Workplane('XY') \ .circle(radius).extrude(self.length)
def make_simple(self)
Return a cylinder with the thread's average radius & length. :math:`radius = (inner_radius + outer_radius) / 2`
3.69406
2.431172
1.519456
# get pilothole ratio # note: not done in .initialize_parameters() because this would cause # the thread's profile to be created at initialisation (by default). pilothole_radius = self.pilothole_radius if pilothole_radius is None: (inner_radius, outer_rad...
def make_pilothole_cutter(self)
Make a solid to subtract from an interfacing solid to bore a pilot-hole.
4.831001
4.790383
1.008479
if self._components is None: self.build(recursive=False) return self._components
def components(self)
Returns full :class:`dict` of :class:`Component` instances, after a successful :meth:`build` :return: dict of named :class:`Component` instances :rtype: :class:`dict` For more information read about the :ref:`parts_assembly-build-cycle` .
6.443737
6.936112
0.929013
if self._constraints is None: self.build(recursive=False) return self._constraints
def constraints(self)
Returns full :class:`list` of :class:`Constraint <cqparts.constraint.Constraint>` instances, after a successful :meth:`build` :return: list of named :class:`Constraint <cqparts.constraint.Constraint>` instances :rtype: :class:`list` For more information read about the :ref:`parts_assem...
7.41497
5.943017
1.247678