Ejemplo n.º 1
0
def clickBtnRoot() : # 관리자페이지 로그인
    if edtId.get() == 'admin' and edtPw.get() == '1234' :
        #messagebox.showerror('성공', '로그인 성공')
        print("관리자 페이지 로그인 성공")
        window.destroy()
        Root.main()
    else :
        messagebox.showerror('실패', '로그인 실패')
        print('로그인 실패')
        pass
Ejemplo n.º 2
0
    def getMatplotlibData(self, key):
        '''
        Get root_numpy data converted into python object most useful for plotting with matplotlib
        :param key: ROOT name of object
        :return: root object converted to format most useful for plotting with matplotlib
        '''

        if self._rootType[key] == "TH1":
            return _Root.TH1(self.getRootData(key))
        elif self._rootType[key] == "TTree":
            return _Root.TTree(self.getRootNumpyData(key))
Ejemplo n.º 3
0
 def test_duplicates_indices(self):
     self.assertEqual(Root.duplicates_indices(self.testArray),
                      {"Dan": [0, 4]})
     self.assertEqual(Root.duplicates_indices(self.testArray1), {
         "Dan": [0, 4],
         "Bob": [1, 2]
     })
     self.assertEqual(Root.duplicates_indices(self.testArray2), {
         "Dan": [0, 4],
         "Bob": [1, 2, 5],
         "Zellinger": [3, 6]
     })
Ejemplo n.º 4
0
def main(argv):
	a=13;
	b=9;
	p=7951;
	output='Order\t';

	bigOrder=1;
	for x in range(0,p):
		root=Root.findRoot(x,a,b,p);
		if root!='NOT_A_ROOT':
			root1=(x,root[0]);
			root2=(x,root[1]);
			res=();
			order=Order.findOrder(root1,a,p);
			

			output = str(order)+'\t1-'+str(root1)+' ';
			if bigOrder< order:
				bigOrder=order;
				res=root1;
			#R=Addition.doubleP(root1,a,p);
			#output=output+'2-'+str(R)+' ';
			#for i in range(3,order):
			#	R=Addition.addP(root1,R,a,p);
			#	output=output+str(i)+'-'+str(R)+' ';

			#print output;
			order=Order.findOrder(root2,a,p);
			if bigOrder< order:
				bigOrder=order;
				res=root2;
			output = str(order)+'\t1-'+str(root2)+' ';
			#print output;

	print bigOrder, res;
Ejemplo n.º 5
0
    def do(self, configuration, arguments):
        #
        # Parameters setup
        #
        Command.add_option(self,
                           "-f",
                           "--force",
                           action="store_true",
                           dest="force",
                           help="force operation")
        Command.add_option(self,
                           "-n",
                           "--name",
                           action="store",
                           dest="name",
                           help="specify root node name")

        (opts, args) = Command.parse_args(self, arguments)
        if (len(args) > 0):
            raise Exceptions.UnknownParameter(args[0])

        if (opts.name != None):
            name = opts.name
        else:
            name = configuration.get(self.name, 'name', str,
                                     "Nameless " + PROGRAM_NAME + " database")
        assert (isinstance(name, str))

        db_file = configuration.get(PROGRAM_NAME, 'database', str)
        assert (db_file != None)

        if (opts.force is not True):
            debug("Force mode disabled")
            assert (db_file != None)
            if (os.path.isfile(db_file)):
                raise Exceptions.ForceNeeded("database file "
                                             "`" + db_file + "' "
                                             "already exists")

        #
        # Work
        #

        # We are in force mode (which means we must write the DB whatsover)
        # or the DB file is not present at all ...

        db = DB.Database()

        # Create an empty tree
        tree = Root.Root(name)
        assert (tree != None)

        #
        # Save database back to file
        #
        db.save(db_file, tree)

        debug("Success")
Ejemplo n.º 6
0
def with_busy_cursor(thunk):
    """
  Execute the thunk with the cursor changed to a watch.
  """
    root = Root.get_root()
    # Traverse widget hierarchy changing all custom cursors
    # to watches. Remember what to change back afterwards.
    changed = []
    for toplevel in root.children.values():
        install_watches(toplevel, changed, 1)
        toplevel.update()
    try:
        thunk()
    finally:
        for widget, old_cursor in changed:
            try:
                widget.configure(cursor=old_cursor)
            except:
                pass
Ejemplo n.º 7
0
    def make2DHistogram(self,
                        command,
                        selector="",
                        name="hist",
                        title="hist",
                        xnbins=-1,
                        xlow=-1.,
                        xhigh=1.,
                        ynbins=-1,
                        ylow=-1.,
                        yhigh=1.):
        '''
        Use TTree.Draw to create a histogram, useful when the size of the data cannot be extracted using getNumpyBranch
        :param command:
        :param selector:
        :param name: histogram name
        :param title: histogram title
        :param xnbins: x number of bins
        :param xlow: x histogram lowest edge
        :param xhigh: x histogram highest edge
        :param ynbins: y number of bins
        :param ylow: y histogram lowest edge
        :param yhigh: y histogram highest edge
        :return: Root.TH1 object
        '''

        # just in case
        _ROOT.TH2.AddDirectory(True)

        # check for existing histogram
        h = _ROOT.gDirectory.Get(name)
        if h != None:
            _ROOT.gDirectory.Delete(name)

        # make histogram if bins are defined
        if xnbins != -1 and ynbins != -1:
            h = _ROOT.TH2D(name, title, xnbins, xlow, xhigh, ynbins, ylow,
                           yhigh)
        nSelected = self._tree.Draw(command + " >> " + name, selector, "goff")
        rootH = _gDirectory.Get(name)  # root histogram object
        maplH = _Root.TH2(rootH)  # matplotlib histogram object

        return maplH
Ejemplo n.º 8
0
def main():
  tk = Root.create_root()
  args = sys.argv[1:]
  if args:
    cwd = os.getcwd()
    for arg in args:
      path = os.path.normpath(os.path.join(cwd, arg))
      if debug_cmd_line_args:
        print "main:"
        print "...cwd =", cwd
        print "...arg =", arg
        print "...path =", path
      try:
        open_project_file(path)
      except Errors.Cancelled:
        pass
      except:
        if debug_cmd_line_args:
          print "Exception processing command line arg"
        Errors.report_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)
  else:
    new_project()
  tk.mainloop()
Ejemplo n.º 9
0
 def test_duplicates(self):
     self.assertEqual(Root.duplicates(self.testArray), ["Dan"])
     self.assertEqual(Root.duplicates(self.testArray1), ["Dan", "Bob"])
     self.assertEqual(Root.duplicates(self.testArray2),
                      ["Dan", "Bob", "Zellinger"])
Ejemplo n.º 10
0
 def test_sortDictResult(self):
     self.assertIsNone(Root.sortDictResult(self.dict))
Ejemplo n.º 11
0
 def test_timeOperation(self):
     result = Root.timeOperation(self.timesAA)
     self.assertEqual(result, [1800.0, 1200.0, 4500.0])
Ejemplo n.º 12
0
def Main():
    VideoDeviceNumber = 0
    CamList, CamDict = RefreshCamList(
    )  #this will update the list of new devices ,if any new is connected
    MainWindow = Root(VideoDeviceNumber, CamList, CamDict)
    MainWindow.CreateMainWindow()
Ejemplo n.º 13
0
class Player(Repeatable):

    # Set private values

    __vars = []
    __init = False

    # These are used by FoxDot
    keywords = ('degree', 'oct', 'freq', 'dur', 'delay', 'blur', 'amplify',
                'scale', 'bpm', 'sample')

    # Base attributes
    base_attributes = ('sus', 'fmod', 'vib', 'slide', 'slidefrom', 'pan',
                       'rate', 'amp', 'room', 'buf', 'bits')
    play_attributes = ('scrub', 'cut')
    fx_attributes = FxList.kwargs()

    metro = None
    server = None

    # Tkinter Window
    widget = None

    default_scale = Scale.default()
    default_root = Root.default()

    def __init__(self):

        # Inherit

        Repeatable.__init__(self)

        # General setup

        self.synthdef = None
        self.id = None
        self.quantise = False
        self.stopping = False
        self.stop_point = 0
        self.following = None
        self.queue_block = None
        self.playstring = ""
        self.buf_delay = []

        # Visual feedback information

        self.envelope = None
        self.line_number = None
        self.whitespace = None
        self.bang_kwargs = {}

        # Modifiers

        self.reversing = False
        self.degrading = False

        # Keeps track of which note to play etc

        self.event_index = 0
        self.event_n = 0
        self.notes_played = 0
        self.event = {}

        # Used for checking clock updates

        self.old_dur = None
        self.old_pattern_dur = None

        self.isplaying = False
        self.isAlive = True

        # These dicts contain the attribute and modifier values that are sent to SuperCollider

        self.attr = {}
        self.modf = {}

        # Keyword arguments that are used internally

        self.scale = None
        self.offset = 0

        # List the internal variables we don't want to send to SuperCollider

        self.__vars = self.__dict__.keys()
        self.__init = True

        self.reset()

    # Class methods

    @classmethod
    def Attributes(cls):
        return cls.keywords + cls.base_attributes + cls.fx_attributes + cls.play_attributes

    # Player Object Manipulation

    def __rshift__(self, other):
        """ The PlayerObject Method >> """

        if isinstance(other, SynthDefProxy):
            self.update(other.name, other.degree, **other.kwargs)
            self + other.mod
            for method, arguments in other.methods.items():
                args, kwargs = arguments
                getattr(self, method).__call__(*args, **kwargs)
            return self
        raise TypeError(
            "{} is an innapropriate argument type for PlayerObject".format(
                other))
        return self

    def __setattr__(self, name, value):
        if self.__init:
            # Force the data into a TimeVar or Pattern if the attribute is used with SuperCollider
            if name not in self.__vars:
                value = asStream(value) if not isinstance(
                    value, (PlayerKey, TimeVar.var)) else value
                # Update the attribute dict
                self.attr[name] = value
                # Update the current event
                self.event[name] = modi(value, self.event_index)
                return
        self.__dict__[name] = value
        return

    def __eq__(self, other):
        return self is other

    def __ne__(self, other):
        return not self is other

    # --- Startup methods

    def reset(self):

        # --- SuperCollider Keywords

        # Left-Right panning (-1,1)
        self.pan = 0

        # Sustain and blur (aka legato)
        self.sus = 1

        # Amplitude
        self.amp = 1

        # Rate - varies between SynthDef
        self.rate = 1

        # Audio sample buffer number
        self.buf = 0

        # Reverb
        self.verb = 0.05
        self.room = 0.01

        # Frequency modifier
        self.fmod = 0

        # Buffer
        self.sample = 0

        # --- FoxDot Keywords

        # Duration of notes
        self.dur = 0.5 if self.synthdef == SamplePlayer else 1
        self.old_pattern_dur = self.old_dur = self.attr['dur']

        self.delay = 0

        # Degree of scale / Characters of samples

        self.degree = " " if self.synthdef is SamplePlayer else 0

        # Octave of the note
        self.oct = 5

        # Amplitude mod
        self.amplify = 1

        # Legato
        self.blur = 1

        # Tempo
        self.bpm = None

        # Frequency and modifier
        self.freq = 0

        # Offbeat delay
        self.offset = 0

        self.modf = dict([(key, [0]) for key in self.attr])
        return self

    # --- Update methods

    def __call__(self, **kwargs):

        # If stopping, kill the event

        if self.stopping and self.metro.now() >= self.stop_point:
            self.kill()
            return

        # If the duration has changed, work out where the internal markers should be

        if self.dur_updated():

            self.event_n, self.event_index = self.count()

            self.old_dur = self.attr['dur']

        # Get the current state

        dur = 0

        while True:

            self.get_event()

            dur = float(self.event['dur'])

            if dur == 0:

                self.event_n += 1

            else:

                break

        # Play the note

        if self.metro.solo == self and kwargs.get(
                'verbose', True) and type(self.event['dur']) != rest:

            self.freq = 0 if self.synthdef == SamplePlayer else self.calculate_freq(
            )

            self.send()

        # If using custom bpm

        if self.event['bpm'] is not None:

            dur *= (float(self.metro.bpm) / float(self.event['bpm']))

        # Schedule the next event

        self.event_index = self.event_index + dur

        self.metro.schedule(self, self.event_index, kwargs={})

        # Change internal marker

        self.event_n += 1 if not self.reversing else -1
        self.notes_played += 1

        return

    def count(self, time=None):

        # Count the events that should have taken place between 0 and now()

        n = 0
        acc = 0
        dur = 0
        now = time if time is not None else self.metro.now()

        durations = self.rhythm()
        total_dur = float(sum(durations))

        if total_dur == 0:

            WarningMsg("Player object has a total duration of 0. Set to 1")

            self.dur = total_dur = durations = 1

        acc = now - (now % total_dur)

        try:

            n = int(len(durations) * (acc / total_dur))

        except TypeError as e:

            WarningMsg(e)

            self.stop()

            return 0, 0

        while True:

            dur = float(modi(durations, n))

            if acc + dur > now:

                break

            else:

                acc += dur
                n += 1

        # Store duration times

        self.old_dur = self.attr['dur']

        # Returns value for self.event_n and self.event_index

        self.notes_played = n

        return n, acc

    def update(self, synthdef, degree, **kwargs):

        # SynthDef name

        self.synthdef = synthdef

        if self.isplaying is False:

            self.reset()

        # If there is a designated solo player when updating, add this at next bar

        if self.metro.solo.active() and self.metro.solo != self:

            self.metro.schedule(lambda: self.metro.solo.add(self),
                                self.metro.next_bar() - 0.001)

        # Update the attribute values

        special_cases = ["scale", "root", "dur"]

        # Set the degree

        if synthdef is SamplePlayer:

            self.playstring = degree

            setattr(self, "degree", degree if len(degree) > 0 else " ")

        elif degree is not None:

            self.playstring = str(degree)

            setattr(self, "degree", degree)

        # Set special case attributes

        self.scale = kwargs.get("scale", self.__class__.default_scale)
        self.root = kwargs.get("root", self.__class__.default_root)

        # If only duration is specified, set sustain to that value also

        if "dur" in kwargs:

            self.dur = kwargs['dur']

            if "sus" not in kwargs and synthdef != SamplePlayer:

                self.sus = self.attr['dur']

        if synthdef is SamplePlayer: pass

        # self.old_pattern_dur

        # self.old_dur = self.attr['dur']

        # Set any other attributes

        for name, value in kwargs.items():

            if name not in special_cases:

                setattr(self, name, value)

        # Calculate new position if not already playing

        if self.isplaying is False:

            # Add to clock
            self.isplaying = True
            self.stopping = False

            self.event_index = self.metro.next_bar()
            self.event_n = 0

            self.event_n, _ = self.count(self.event_index)

            self.metro.schedule(self, self.event_index)

        return self

    def dur_updated(self):
        dur_updated = self.attr['dur'] != self.old_dur
        if self.synthdef == SamplePlayer:
            dur_updated = (self.pattern_rhythm_updated() or dur_updated)
        return dur_updated

    def step_duration(self):
        return 0.5 if self.synthdef is SamplePlayer else 1

    def rhythm(self):
        # If a Pattern TimeVar
        if isinstance(self.attr['dur'], TimeVar.Pvar):
            r = asStream(self.attr['dur'].now().data)

        # If duration is a TimeVar
        elif isinstance(self.attr['dur'], TimeVar.var):
            r = asStream(self.attr['dur'].now())

        else:
            r = asStream(self.attr['dur'])

        # TODO: Make sure degree is a string
        if self.synthdef is SamplePlayer:
            try:
                d = self.attr['degree'].now()
            except:
                d = self.attr['degree']
            r = r * [(char.dur if hasattr(char, "dur") else 1)
                     for char in d.flat()]
        return r

    def pattern_rhythm_updated(self):
        r = self.rhythm()
        if self.old_pattern_dur != r:
            self.old_pattern_dur = r
            return True
        return False

    def char(self, other=None):
        if other is not None:
            try:
                if type(other) == str and len(other) == 1:  #char
                    return BufferManager.bufnum(self.now('buf')) == other
                raise TypeError("Argument should be a one character string")
            except:
                return False
        else:
            try:
                return BufferManager.bufnum(self.now('buf'))
            except:
                return None

    def calculate_freq(self):
        """ Uses the scale, octave, and degree to calculate the frequency values to send to SuperCollider """

        # If the scale is frequency only, just return the degree

        if self.scale == Scale.freq:

            try:

                return list(self.event['degree'])

            except:

                return [self.event['degree']]

        now = {}

        for attr in ('degree', 'oct'):

            now[attr] = self.event[attr]

            try:

                now[attr] = list(now[attr])

            except:

                now[attr] = [now[attr]]

        size = max(len(now['oct']), len(now['degree']))

        f = []

        for i in range(size):

            try:

                midinum = midi(self.scale, modi(now['oct'], i),
                               modi(now['degree'], i), self.now('root'))

            except:

                WarningMsg(
                    "Invalid degree / octave arguments for frequency calculation, reset to default"
                )

                raise

            f.append(miditofreq(midinum))

        return f

    def f(self, *data):
        """ adds value to frequency modifier """

        self.fmod = tuple(data)

        p = []
        for val in self.attr['fmod']:

            try:
                pan = tuple((item / ((len(val) - 1) / 2.0)) - 1
                            for item in range(len(val)))
            except:
                pan = 0
            p.append(pan)

        self.pan = p

        return self

    # Methods affecting other players - every n times, do a random thing?

    def stutter(self, n=2, **kwargs):
        """ Plays the current note n-1 times over the current durations """

        if self.metro.solo == self and n > 0:

            dur = float(kwargs.get("dur", self.event['dur'])) / int(n)

            delay = 0

            for stutter in range(1, n):

                delay += dur

                sub = {
                    kw: modi(val, stutter - 1)
                    for kw, val in kwargs.items()
                }

                self.metro.schedule(func_delay(self.send, **sub),
                                    self.event_index + delay)

        return self

    # --- Misc. Standard Object methods

    def __int__(self):
        return int(self.now('degree'))

    def __float__(self):
        return float(self.now('degree'))

    def __add__(self, data):
        """ Change the degree modifier stream """
        self.modf['degree'] = asStream(data)
        return self

    def __sub__(self, data):
        """ Change the degree modifier stream """
        data = asStream(data)
        data = [d * -1 for d in data]
        self.modf['degree'] = data
        return self

    def __mul__(self, data):
        """ Multiplying an instrument player multiplies each amp value by
            the input, or circularly if the input is a list. The input is
            stored here and calculated at the update stage """

        if type(data) in (int, float):

            data = [data]

        self.modf['amp'] = asStream(data)

        return self

    def __div__(self, data):

        if type(data) in (int, float):

            data = [data]

        self.modf['amp'] = [1.0 / d for d in data]

        return self

    # --- Data methods

    def largest_attribute(self):
        """ Returns the length of the largest nested tuple in the attr dict """

        # exclude = 'degree' if self.synthdef is SamplePlayer else None
        exclude = None

        size = len(self.attr['freq'])

        for attr, value in self.event.items():
            if attr != exclude:
                try:
                    l = len(value)
                    if l > size:
                        size = l
                except:
                    pass

        return size

    # --- Methods for preparing and sending OSC messages to SuperCollider

    def now(self, attr="degree", x=0):
        """ Calculates the values for each attr to send to the server at the current clock time """

        modifier_event_n = self.event_n

        attr_value = self.attr[attr]

        attr_value = modi(asStream(attr_value), self.event_n + x)

        ## If this player is following another, update that player first

        if attr == "degree" and self.following != None:

            if self.following in self.queue_block.objects():

                self.queue_block.call(self.following, self)

        # If the attribute isn't in the modf dictionary, default to 0

        try:

            modf_value = modi(self.modf[attr], modifier_event_n + x)

        except:

            modf_value = 0

        # If any values are time-dependant, get the now values

        try:

            attr_value = attr_value.now()

        except:

            pass

        try:

            modf_value = modf_value.now()

        except:

            pass

        # Combine attribute and modifier values

        try:

            ##            if attr == "dur" and type(attr_value) == rest:
            ##
            ##                value = rest(attr_value + modf_value)
            ##
            ##            else:

            value = attr_value + modf_value

        except:

            value = attr_value

        return value

    def get_event(self):
        """ Returns a dictionary of attr -> now values """

        # Get the current event

        self.event = {}

        attributes = copy(self.attr)

        for key in attributes:

            # Eg. sp.sus returns the currently used value for sustain

            self.event[key] = self.now(key)

            #  Make sure the object's dict uses PlayerKey instances

            if key not in self.__dict__:

                self.__dict__[key] = PlayerKey(self.event[key])

            elif not isinstance(self.__dict__[key], PlayerKey):

                self.__dict__[key] = PlayerKey(self.event[key])

            else:

                self.__dict__[key].update(self.event[key])

        # Special case: sample player

        if self.synthdef == SamplePlayer:

            try:

                event_dur = self.event['dur']

                if isinstance(self.event['degree'], PlayGroup):

                    buf_list = ((0, self.event['degree']), )
                    event_buf = [0]

                else:

                    buf_list = enumerate(self.event['degree'])
                    event_buf = list(range(len(self.event['degree'])))

                self.buf_delay = []

                for i, bufchar in buf_list:

                    if isinstance(bufchar, PlayGroup):

                        char = BufferManager[bufchar[0]]

                        # Get the buffer number to play

                        buf_mod_index = modi(self.event['sample'], i)

                        event_buf[i] = char.bufnum(buf_mod_index).bufnum

                        delay = 0

                        for n, b in enumerate(bufchar[1:]):

                            char = BufferManager[b]

                            buf_mod_index = modi(self.event['sample'], i)

                            delay += (bufchar[n].dur * self.event['dur'])

                            self.buf_delay.append(
                                (char.bufnum(buf_mod_index), delay))

                    else:

                        char = BufferManager[bufchar]

                        # Get the buffer number to play
                        buf_mod_index = modi(self.event['sample'], i)

                        event_buf[i] = char.bufnum(buf_mod_index).bufnum

                self.event['buf'] = P(event_buf)

            except TypeError:

                pass

        return self

    def osc_message(self, index=0, **kwargs):
        """ NEW: Creates an OSC packet to play a SynthDef in SuperCollider,
            use kwargs to force values in the packet, e.g. pan=1 will force ['pan', 1] """

        freq = float(modi(self.attr['freq'], index))

        message = ['freq', freq]
        fx_dict = {}

        attributes = self.attr.copy()

        # Go through the attr dictionary and add kwargs

        for key in attributes:

            try:

                # Don't use fx keywords or foxdot keywords

                if key not in FxList.kwargs() and key not in self.keywords:

                    val = modi(kwargs.get(key, self.event[key]), index)

                    # Special case modulation

                    if key == "sus":

                        val = val * self.metro.beat() * modi(
                            kwargs.get('blur', self.event['blur']), index)

                    elif key == "amp":

                        val = val * modi(
                            kwargs.get('amplify', self.event['amplify']),
                            index)

                    message += [key, float(val)]

            except:

                print("Issue in OSC message for '{}'. Problem with {}".format(
                    self.synthdef, key))

        # See if any fx_attributes

        for key in self.fx_attributes:

            if key in attributes:

                # All effects use sustain to release nodes

                fx_dict[key] = []

                # Look for any other attributes require e.g. room and verb

                for sub_key in FxList[key].args:

                    if sub_key in self.event:

                        val = float(
                            modi(kwargs.get(sub_key, self.event[sub_key]),
                                 index))

                        # Don't send fx with zero values

                        if val == 0:

                            del fx_dict[key]

                            break

                        else:

                            fx_dict[key] += [sub_key, val]

        return message, fx_dict

    def send(self, **kwargs):
        """ Sends the current event data to SuperCollder.
            Use kwargs to overide values in the """

        size = self.largest_attribute()
        banged = False
        sent_messages = []
        delayed_messages = []

        for i in range(size):

            osc_msg, effects = self.osc_message(i, **kwargs)

            delay = modi(kwargs.get('delay', self.event['delay']), i)
            buf = modi(kwargs.get('buf', self.event['buf']), i)

            amp = osc_msg[osc_msg.index('amp') + 1]

            # Any messages with zero amps or 0 buf are not sent

            if (self.synthdef != SamplePlayer
                    and amp > 0) or (self.synthdef == SamplePlayer and buf > 0
                                     and amp > 0):

                if self.synthdef == SamplePlayer:

                    numChannels = BufferManager.getBuffer(buf).channels

                    if numChannels == 1:

                        synthdef = "play1"

                    else:

                        synthdef = "play2"

                else:

                    synthdef = str(self.synthdef)

                if delay > 0:

                    if (delay, osc_msg, effects) not in delayed_messages:

                        self.metro.schedule(
                            send_delay(self, synthdef, osc_msg, effects),
                            self.event_index + delay)

                        delayed_messages.append((delay, osc_msg, effects))

                    if self.bang_kwargs:

                        self.metro.schedule(self.bang,
                                            self.metro.now() + delay)

                else:

                    # Don't send duplicate messages

                    if (osc_msg, effects) not in sent_messages:

                        self.server.sendPlayerMessage(synthdef, osc_msg,
                                                      effects)

                        sent_messages.append((osc_msg, effects))

                    if not banged and self.bang_kwargs:

                        self.bang()

                        banged = True

            if self.buf_delay:

                for buf_num, buf_delay in self.buf_delay:

                    # Only send messages with amps > 0

                    i = osc_msg.index('amp') + 1

                    if osc_msg[i] > 0:

                        # Make sure we use an integer number

                        buf_num = int(buf_num)

                        if buf_num > 0:

                            i = osc_msg.index('buf') + 1

                            osc_msg[i] = buf_num

                            numChannels = BufferManager.getBuffer(
                                buf_num).channels

                            if numChannels == 1:

                                synthdef = "play1"

                            else:

                                synthdef = "play2"

                            if (buf_delay + delay, osc_msg,
                                    effects) not in delayed_messages:

                                self.metro.schedule(
                                    send_delay(self, synthdef, osc_msg,
                                               effects),
                                    self.event_index + buf_delay + delay)

                                delayed_messages.append(
                                    (buf_delay + delay, osc_msg, effects))
        return

    #: Methods for stop/starting players

    def kill(self):
        """ Removes this object from the Clock and resets itself"""
        self.isplaying = False
        self.repeat_events = {}
        self.reset()
        return

    def stop(self, N=0):
        """ Removes the player from the Tempo clock and changes its internal
            playing state to False in N bars time
            - When N is 0 it stops immediately"""

        self.stopping = True
        self.stop_point = self.metro.now()

        if N > 0:

            self.stop_point += self.metro.next_bar() + (
                (N - 1) * self.metro.bar_length())

        else:

            self.kill()

        return self

    def pause(self):

        self.isplaying = False

        return self

    def play(self):

        self.isplaying = True
        self.stopping = False
        self.isAlive = True

        self.__call__()

        return self

    def follow(self, lead, follow=True):
        """ Takes a now object and then follows the notes """

        self.degree = lead.degree
        self.following = lead

        return self

    def solo(self, arg=True):

        if arg:

            self.metro.solo.set(self)

        else:

            self.metro.solo.reset()

        return self

    def num_key_references(self):
        """ Returns the number of 'references' for the
            attr which references the most other players """
        num = 0
        for attr in self.attr.values():
            if isinstance(attr, PlayerKey):
                if attr.num_ref > num:
                    num = attr.num_ref
        return num

    """
        State-Shift Methods
        --------------

        These methods are used in conjunction with Patterns.Feeders functions.
        They change the state of the Player Object and return the object.

        See 'Player.Feeders' for more info on how to use

    """

    def lshift(self, n=1):
        self.event_n -= (n + 1)
        return self

    def rshift(self, n=1):
        self.event_n += n
        return self

    def reverse(self):
        """ Sets flag to reverse streams """
        self.reversing = not self.reversing
        if self.reversing:
            self.event_n -= 1
        else:
            self.event_n += 1
        return self

    def shuffle(self):
        """ Shuffles the degree of a player. If possible, do it visually """
        if self.synthdef == SamplePlayer:
            self._replace_string(PlayString(self.playstring).shuffle())
        else:
            self._replace_degree(self.attr['degree'].shuffle())
        # self.degree = self.attr['degree'].shuffle()
        return self

    def mirror(self):
        if self.synthdef == SamplePlayer:
            self._replace_string(PlayString(self.playstring).mirror())
        else:
            self._replace_degree(self.attr['degree'].mirror())
        # self.degree = self.attr['degree'].mirror()
        return self

    def rotate(self, n=1):
        if self.synthdef == SamplePlayer:
            self._replace_string(PlayString(self.playstring).rotate(n))
        else:
            self._replace_degree(self.attr['degree'].rotate(n))
        # self.degree = self.attr['degree'].rotate(n)
        return self

    def _replace_string(self, new_string):
        # Update the GUI if possible
        if self.widget:
            # Replace old_string with new string
            self.widget.addTask(target=self.widget.replace,
                                args=(self.line_number, self.playstring,
                                      new_string))
        self.playstring = new_string
        setattr(self, 'degree', new_string)
        return

    def _replace_degree(self, new_degree):
        # Update the GUI if possible
        if self.widget:
            # Replace old_string with new string
            self.widget.addTask(target=self.widget.replace_re,
                                args=(self.line_number, ),
                                kwargs={'new': str(new_degree)})
        self.playstring = str(new_degree)
        setattr(self, 'degree', new_degree)
        return

    def multiply(self, n=2):
        self.attr['degree'] = self.attr['degree'] * n
        return self

    def degrade(self, amount=0.5):
        """ Sets the amp modifier to a random array of 0s and 1s
            amount=0.5 weights the array to equal numbers """
        if not self.degrading:
            self.amp = Pwrand([0, 1], [1 - amount, amount])
            self.degrading = True
        else:
            ones = int(self.amp.count(1) * amount)
            zero = self.amp.count(0)
            self.amp = Pshuf(Pstutter([1, 0], [ones, zero]))
        return self

    def changeSynth(self, list_of_synthdefs):
        new_synth = choice(list_of_synthdefs)
        if isinstance(new_synth, SynthDef):
            new_synth = str(new_synth.name)
        self.synthdef = new_synth
        # TODO, change the >> name
        return self

    """

        Modifier Methods
        ----------------

        Other modifiers for affecting the playback of Players

    """

    def offbeat(self, dur=0.5):
        """ Off sets the next event occurence """

        self.attr['delay'] += (dur - self.offset)

        self.offset = dur

        return self

    def strum(self, dur=0.025):
        """ Adds a delay to a Synth Envelope """
        x = self.largest_attribute()
        if x > 1:
            self.delay = asStream([tuple(a * dur for a in range(x))])
        else:
            self.delay = asStream(dur)
        return self

    def __repr__(self):
        return "a '%s' Player Object" % self.synthdef

    def info(self):
        s = "Player Instance using '%s' \n\n" % self.synthdef
        s += "ATTRIBUTES\n"
        s += "----------\n\n"
        for attr, val in self.attr.items():
            s += "\t{}\t:{}\n".format(attr, val)
        return s

    def bang(self, **kwargs):
        """
        Triggered when sendNote is called. Responsible for any
        action to be triggered by a note being played. Default action
        is underline the player
        """
        if kwargs:

            self.bang_kwargs = kwargs

        elif self.bang_kwargs:

            print self.bang_kwargs

            bang = Bang(self, self.bang_kwargs)

        return self
Ejemplo n.º 14
0
 def test_lineOperation(self):
     file = open('test1.txt', "r")
     #linebyline = "Alex: 41 miles @ 34 mph", "Dan: 39 miles @ 47 mph", "Bob: 0 miles"
     self.assertEqual(Root.lineOperation(file), 'None')
Ejemplo n.º 15
0
 def test_peopleWithZeroMiles(self):
     self.assertEqual(
         Root.peopleWithZeroMiles(self.testArray, self.testArray1),
         ['Alex'])
Ejemplo n.º 16
0
def main(net):
    my_interfaces = net.interfaces(
    )  # gets a list of interfaces on this router
    mymacs = [intf.ethaddr for intf in my_interfaces
              ]  # gets the ethernet addresses for every interface
    cache = lruCache(5)

    myId, myMAC, myName = findMyId(my_interfaces)

    root = Root(myId, myMAC, 0, myName)
    log_debug("My ID = {} root {}".format(myId, root.rootMAC))

    #sendSTP(root, my_interfaces, net) # flood to nodes
    emitSTP(root, myMAC, myId, my_interfaces, net)

    forwardTable = {}
    # dictionary of interface:forward
    for intf in my_interfaces:
        forwardTable[intf.name] = True

    while True:
        try:
            timestamp, input_port, packet = net.recv_packet()
        except NoPackets:
            continue
        except Shutdown:
            return

        # src and dest are mac addresses
        # input_port appears to be the name of the port

        #add src and input port pair to cache
        newSrc = lruEntry(packet[0].src, input_port)

        cache.print()
        cache.push(newSrc)

        log_debug("In {} received packet {} on {}".format(
            net.name, packet, input_port))

        if packet.has_header(SpanningTreeMessage):  #STP packet
            msg = SpanningTreeMessage()

            msg.from_bytes(packet[1].to_bytes())
            log_debug(
                "Spanning Tree Message found with root {} {}, current root is {} {} on {}"
                .format(msg.root, msg.hops_to_root, root.rootMAC, root.hops,
                        root.srcPort))

            # log_debug("||||||||||||||||||| msg {}  root {}".format(msg.root), root.rootMAC())

            if ethToId(msg.root) < root.rootID:
                log_debug(
                    "Spanning Tree Message root was less than current root")

                root = Root(ethToId(msg.root), msg.root, msg.hops_to_root + 1,
                            input_port)

                forwardTable[input_port] = True
                sendSTP(root, myMAC, my_interfaces, net, input_port)
            elif ethToId(msg.root
                         ) == root.rootID and msg.hops_to_root + 1 < root.hops:
                log_debug(
                    "Spanning Tree Message root was same as current but shorter distance found"
                )

                forwardTable[input_port] = True
                root.hops = msg.hops_to_root + 1
                root.srcPort = input_port
                sendSTP(root, myMAC, my_interfaces, net, input_port)
            elif input_port != root.srcPort and msg.hops_to_root + 1 == root.hops:
                log_debug(
                    "Spanning Tree Message different roots but same distance, blocking {}"
                    .format(input_port))
                forwardTable[input_port] = False

        elif packet[0].dst in mymacs:
            log_debug("Packet intended for me")

        elif cache.contains(packet[0].dst):
            log_debug("Packet destination in LRU cache")
            dstPort = cache.getPort(packet[0].dst)
            for intf in my_interfaces:
                if dstPort == intf.name:
                    log_debug("Sending packet {} to {}".format(
                        packet, intf.name))
            #log_debug("Packet destination in LRU cache")
            dstPort = cache.getPort(packet[0].dst)
            for intf in my_interfaces:
                if dstPort == intf.name:
                    #log_debug("Sending packet {} to {}".format(packet, intf.name))
                    net.send_packet(intf.name, packet)

        else:  # broadcast
            for intf in my_interfaces:
                log_debug(intf.name + " " + str(forwardTable[intf.name]))
                if input_port != intf.name and forwardTable[intf.name]:
                    log_debug("Flooding packet {} to {}".format(
                        packet, intf.name))
                    net.send_packet(intf.name, packet)

    net.shutdown()
if __name__ == "__main__":
  #if not os.path.exists(pipe_name):
   # os.mkfifo(pipe_name)
  #print "hello"
 # pipein = open(pipe_name, 'r')
  webpipeque = Queue()
  webpipe = Process(target = pipeprocess, args = (webpipeque, pipe_name))
  webpipe.start()
  conn = sqlite3.connect(sqlite_file, check_same_thread=False)
  conn.isolation_level =None
  c = conn.cursor()

  # Make Queeue
  que = Queue()
  queue = []
  root = Root(c)
  '''
  lightSensingThread = myThread(root, "light", queue)
  temperSensingThread = myThread(root, "temper", queue)
  humidSensingThread = myThread(root, "humid", queue)
  magnetSensingThread = myThread(root, "magnet", queue)
  infraredSensingThread = myThread(root, "infrared", queue)
  lightSensingThread.start()
  temperSensingThread.start()
  humidSensingThread.start()
  magnetSensingThread.start()
  '''
  root.makeDAG()
  
  c.execute('CREATE TABLE {tn} ({nf} {ft})'\
      .format(tn = lighttable, nf = "ID", ft="INTEGER"))
Ejemplo n.º 18
0
# Twisted Application Framework setup:
application = service.Application('twisted-django')


# WSGI container for Django, combine it with twisted.web.Resource:
# XXX this is the only 'ugly' part: see the 'getChild' method in twresource.Root 
# The MultiService allows to start Django and Twisted server as a daemon.

multi = service.MultiService()
pool = threadpool.ThreadPool()
tps = ThreadPoolService(pool)
tps.setServiceParent(multi)
import UGM_Database.wsgi

resource = Root.WSGIResource(reactor, tps.pool, UGM_Database.wsgi.application)
root = Root.Root(resource)


mediasrc = static.File(os.path.join(os.path.abspath("."), "static/media"))
staticsrc = static.File(os.path.join(os.path.abspath("."), "static"))
root.putChild("static", staticsrc)
root.putChild("media", mediasrc)




# The cool part! Add in pure Twisted Web Resouce in the mix
# This 'pure twisted' code could be using twisted's XMPP functionality, etc:

Ejemplo n.º 19
0
import Root as r
from tkinter import *

if __name__ == "__main__":
    # "WinProb Files/8L vs 16L vs Blk36Pg24 Fail Raw.prb"
    filename = ""
    x = r.RootPane(Tk(), filename)
    x.show()
Ejemplo n.º 20
0
 def test_calOperation(self):
     self.assertEqual(Root.calOperation(self.names, self.miles, self.times),
                      self.dict1)
Ejemplo n.º 21
0
def fromxml(input_node):
    #debug("XML -> Tree in progress")

    #debug("Handling tag " + xml.tag)
    node = None

    if (input_node.nodeType == 1):
        text = None
        priority = None
        start = None
        end = None
        comment = None
        children = []

        # Collecting entry and comment children and node text data
        for child in input_node.childNodes:
            if (child.nodeType == 1):
                if (child.nodeName == "entry"):
                    children.append(child)
                elif (child.nodeName == "comment"):
                    # Collecting comment string
                    for i in child.childNodes:
                        assert (i.nodeType == 3)

                        if (comment == None):
                            comment = i.data
                        else:
                            comment = comment + i.data
                    comment = comment.strip()
                else:
                    raise Exceptions.MalformedDatabase("Unknown tag `" +
                                                       child.nodeName + "'")
            elif (child.nodeType == 3):
                if (not child.data.isspace()):
                    if (text == None):
                        text = child.data
                    else:
                        text = text + child.data

                    text = text.strip()
            elif ((child.nodeType == 2) or (4 <= child.nodeType <= 10)):
                # Skip unused nodes
                pass
            else:
                raise Exceptions.UnknownElement(child)

    # If we are on root node, build it and skip attributes processing
        if (input_node.nodeName == "root"):
            if (text == None):
                #warning("Database has no name, using default one")
                #text = "Default DB name"
                raise Exceptions.MalformedDatabase("Missing database name")
            node = Root.Root(text)
        elif (input_node.nodeName == "entry"):
            if (text == None):
                raise Exceptions.MalformedDatabase()

            # Looking for priority attribute
            # debug("Priority is:      `" + input_node.getAttribute("start") +
            #       "'")
            priority = Priority.Priority()
            if (not input_node.hasAttribute("priority")):
                #warning("No priority for entry `" + text + "', using default")
                raise Exceptions.MalformedDatabase("No priority for entry " +
                                                   "`" + text + "'")
            else:
                priority.fromstring(str(input_node.getAttribute("priority")))

            # Looking for start attribute
            value = None

            if (input_node.hasAttribute("start")):
                value = input_node.getAttribute("start")
                try:
                    start = Time.Time(int(value))
                    debug("Start time value: `" + str(value) + "'")
                # Our exceptions first
                except Exceptions, e:
                    error("Wrong start time format for entry " + "`" + text +
                          "' (" + str(e) + ")")
                    raise Exceptions.MalformedDatabase()
                except ValueError:
                    error("Wrong start time for entry " + "`" + text + "'")
                    raise Exceptions.MalformedDatabase()
                except Exception, e:
                    bug(str(e))
Ejemplo n.º 22
0
import SCLang
from SCLang import SynthDefs, Env
from SCLang.SynthDefs import *
""" CLOCK """

Clock = TempoClock()
Clock.when_statements = when

when.metro = var.metro = Clock
PlayerObject.metro = Clock

Clock.start()

PlayerObject.server = Server
PlayerObject.default_scale = Scale.default()
PlayerObject.default_root = Root.default()

BufferManager.server = Server
BufferManager.load()

FoxDotCode.namespace = globals()
""" Preset PlayerObjects """

alphabet = 'abcdefghijklmnopqrstuvwxyz'
numbers = '0123456789'

# 1 Letter Player Objects

for char in alphabet:

    FoxDotCode.namespace[char] = PlayerObject()
Ejemplo n.º 23
0
from Root import *

if __name__ == '__main__':
    main = Root()
    main.mainloop()
Ejemplo n.º 24
0
    This module also handles the time keeping aspect. There is a constant tempo
    clock running that has a queue and plays the items accordingly

    Note: The code below IS executed in the Environment and can be accessed by the user!

"""
from random import choice as choose

from TempoClock import *
from ServerManager import *
from Players import *
from Patterns import *
from Code import *
from TimeVar import *
from SuperCollider import *
import Scale
import Root

""" SERVER """
     
Server = ServerManager()

""" CLOCK """

Clock = TempoClock()

Var.metro = Clock
PlayerObject.metro, PlayerObject.server = Clock, Server
Player.default_scale = Scale.default()
Player.default_root  = Root.default()
Ejemplo n.º 25
0
    this module, which is analysed and sent back as the raw python code to execute.

    This module also handles the time keeping aspect. There is a constant tempo
    clock running that has a queue and plays the items accordingly

    Note: The code below IS executed in the Environment and can be accessed by the user!

"""
from random import choice as choose

from TempoClock import *
from ServerManager import *
from Players import *
from Patterns import *
from Code import *
from TimeVar import *
from SuperCollider import *
import Scale
import Root
""" SERVER """

Server = ServerManager()
""" CLOCK """

Clock = TempoClock()

Var.metro = Clock
PlayerObject.metro, PlayerObject.server = Clock, Server
Player.default_scale = Scale.default()
Player.default_root = Root.default()