def test_strxfrm(): str1 = "this is a test !" str2 = _locale.strxfrm(str1) cmp(str1, str2) str1 = "this is a test&^%%^$%$ !" str2 = _locale.strxfrm(str1) cmp(str1, str2) str1 = "this \" \"is a test&^%%^$%$ !" str2 = _locale.strxfrm(str1) cmp(str1, str2) str1 = "123456789" str2 = _locale.strxfrm(str1) cmp(str1, str2) #argument is int type i = 12 AssertError(TypeError, _locale.strxfrm, i) #argument is random type obj = _random.Random() AssertError(TypeError, _locale.strxfrm, obj)
def test_strxfrm(self): str1 = "this is a test !" str2 = _locale.strxfrm(str1) str1.__eq__(str2) str1 = "this is a test&^%%^$%$ !" str2 = _locale.strxfrm(str1) str1.__eq__(str2) str1 = "this \" \"is a test&^%%^$%$ !" str2 = _locale.strxfrm(str1) str1.__eq__(str2) str1 = "123456789" str2 = _locale.strxfrm(str1) str1.__eq__(str2) #argument is int type i = 12 self.assertRaises(TypeError,_locale.strxfrm,i) #argument is random type obj = _random.Random() self.assertRaises(TypeError,_locale.strxfrm,obj)
def test_random(self): import _random random = _random.Random() from System.Threading import Thread, ParameterizedThreadStart global zeroCount zeroCount = 0 def foo((ntimes, nbits)): for i in xrange(ntimes): x = random.getrandbits(nbits) if x == 0: zeroCount += 1 def run_many(nthreads, ntimes, nbits): lst_threads = [] for i in xrange(nthreads): t = Thread(ParameterizedThreadStart(foo)) t.Start((ntimes, nbits)) lst_threads.append(t) for t in lst_threads: t.Join() run_many(10, 10**6, 63) self.assertTrue(zeroCount < 3)
def test_randbits(self): import _random rnd = _random.Random() for n in range(1, 10) + range(10, 1000, 15): k = rnd.getrandbits(n) assert 0 <= k < 2 ** n
def test_jumpahead(self): import sys import _random rnd = _random.Random() rnd.jumpahead(100) rnd.jumpahead(sys.maxint + 2)
def test_seedargs(self): import _random rnd = _random.Random() for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20), 3.14, 1+2j, 'a', tuple('abc'), 0xffffffffffL]: rnd.seed(arg)
(1, 3): 0, (2, 0): 0.6, (2, 1): 0, (2, 2): 0, (2, 3): 0.4, (3, 0): 0, (3, 1): 0, (3, 2): 0, (3, 3): 1 } sum_days = 0 m = 1000 seasons = [] r = _random.Random() for l in range(0, m): season_number = 0 s_cur = (0, 0) x = 0 fl = False while s_cur[0] < 3: i, j = s_cur p_array = r.random() if s_cur == (0, 0): season_number += 1
import _random r = _random.Random(42) print r.random() s = r.getstate() print r.getrandbits(100) r.jumpahead(100) print r.getrandbits(100) r.setstate(s) print r.getrandbits(100) class Random(_random.Random): def __init__(self, a=None): super(Random, self).seed(a) for i in xrange(100): r = Random(i) print r.getrandbits(100)
def test_exact_result(self): # this passes on CPython 2.7.9 on Linux 32 and Linux 64 import _random rnd = _random.Random(-3**31) x = rnd.random() assert x == 0.8181851342382107
def test_jumpahead(self): rand = _random.Random() old_state = rand.getstate() rand.jumpahead(100) self.assertTrue(old_state != rand.getstate())
def __init__(self): self._tasks_pq = [] self._random = _random.Random()
print "Test subprocess module: run 'pwd'=", cmd("pwd")[:-1] print "Test os module: current dictory = ", os.getcwd() print "Test os module: change dictory to / " os.chdir("/") print "Test os module: current dictory = ", os.getcwd() print "Test os module: get dictory content(first 3) = ", os.listdir( "/")[:3] print "Test re module:", re.findall("aaa", "111bbbaaacccc") print "Test math module: math.sin(1) =", math.sin(1) print "Test threading module : threading.Lock()", threading.Lock() print "Test os module: os.sys.path:" for x in os.sys.path: print " ", x print "Test binascii module: b2a =0x", binascii.b2a_hex("abcde") print "Test struct module: pack =", [struct.pack('>I', 10240099)] print "Test random module: random.random =", _random.Random().random() except Exception as e: print e print "##################### Test failed ######################"
def recombine(mating_pool): xover_number = int(pop_size * xover_rate) # cross over number must always be an even number if xover_number % 2 == 1: xover_number -= 1 # print( 'xover_number is {0}'.format( xover_number ) ) rand = _random.Random() temp = rand.random() # xover_point = int( temp * genotype_size ) xover_point = int(0.5 * genotype_size) # print( 'xover_point is {0}'.format( xover_point ) ) # because cross over involves two parents... n = 0 loop_counter = 0 loop_counter = xover_number / 2 # print( 'xover loop counter is {0}'.format( loop_counter ) ) i = 0 ints = [] while i < genotype_size: ints.append(i) i += 1 # print( ints ) while n < loop_counter: number1 = rand.random() length1 = len(ints) # print( 'BEFORE: length of ints is: {0}'.format( length1 ) ) number1 = number1 * len(ints) temp1 = int(number1) # print( 'BEFORE: temp1 is: {0}'.format( temp1 ) ) index1 = ints[temp1] # ints.remove( temp1 ) remove by value! del ints[temp1] number2 = rand.random() length2 = len(ints) # print( 'BEFORE: length of ints is: {0}'.format( length2 ) ) number2 = number2 * len(ints) temp2 = int(number2) # print( 'BEFORE: temp2 is: {0}'.format( temp2 ) ) index2 = ints[temp2] # ints.remove( temp2 ) remove by value! del ints[temp2] # print( 'BEFORE: index1 is: {0} and index2 is: {1}'.format( index1, index2 ) ) ind1 = mating_pool[index1] ind2 = mating_pool[index2] # print( 'BEFORE: ind1 is: {0} and ind2 is: {1}'.format( ind1.barr, ind2.barr ) ) # print( 'BEFORE: ints is: {0}'.format( ints ) ) i = xover_point barr1 = bytearray() barr2 = bytearray() while i < genotype_size: barr1.append(ind1.barr[i]) barr2.append(ind2.barr[i]) # print( 'barr1 is: {0} and barr2 is: {1}'.format( barr1, barr2 ) ) i += 1 # print( 'BEFORE: barr1 is: {0} and barr2 is: {1}'.format( barr1, barr2 ) ) i = 0 while i < xover_point: ind1.barr.pop() ind2.barr.pop() i += 1 # print( 'BEFORE: cropped ind1 is: {0} and ind2 is: {1} and i is: {2}'.format( ind1.barr, ind2.barr, i ) ) i = xover_point barr_counter = 0 while i < genotype_size: ind1.barr.append(barr2[barr_counter]) ind2.barr.append(barr1[barr_counter]) i += 1 barr_counter += 1 # print( 'AFTER: ind1 is: {0} and ind2 is: {1}'.format( ind1.barr, ind2.barr ) ) # print( 'AFTER: ints is: {0}'.format( ints ) ) n += 1
def mutate(mating_pool): rand = _random.Random() number1 = rand.random() number1 = number1 * pop_size index1 = int(number1) mating_pool[index1].mutate()
# https://github.com/praashie/fl-novation-impulse from flatmate.control import MIDIControl, MIDIButton from flatmate.hooker import Hooker import _random as random random_generator = random.Random() class ImpulseEncoder(MIDIControl): def updateValueFromEvent(self, event): self.value = event.controlVal - 0x40 event.inEv = self.value event.outEv = self.value event.isIncrement = True class ImpulseSoloMode(MIDIControl): _mixermode_callback = None onSoloModeCallback = None def callback(self, control, event): if self.value == self.value_previous: self._mixermode_callback(self, event) else: self.onSoloModeCallback(self, event) def set_callback(self, callback): self._mixermode_callback = callback
This script plays individual notes as chords. Author: Miguel Guthridge [[email protected]] """ import _random import math import internal.consts import eventconsts from internal.notemanager import notesDown, pads import processorhelpers import lightingconsts # Create random number generator rng = _random.Random() MAX_VEL_OFFSET = 10 # The name of your mode NAME = "Chord" # The colour used to represent your mode DEFAULT_COLOUR = lightingconsts.colours["TEAL"] # The colour used to represent your mode while active... # you can change this while your script is running COLOUR = lightingconsts.colours["TEAL"] # Whether your mode should be unlisted in the note mode menu SILENT = False
def test_jumpahead(): rand = _random.Random() old_state = rand.getstate() rand.jumpahead(100)
class Actions: """Class that houses all action functions available. NOTE: Doc-strings are used to document the macro. This allows for a two-button press plus bank button to display the doc-string to the user. As such, try to limit doc strings to 16-chars for the help-system implementation. """ RANDOM_GENERATOR = _random.Random() # ---------------------- AVAILABLE ACTIONS -------------------------- @staticmethod def toggle_playlist_visibility(unused_param_value): """Playlist""" transport.globalTransport(midi.FPT_F5, 1) @staticmethod def toggle_channel_rack_visibility(unused_param_value): """Channel Rack""" transport.globalTransport(midi.FPT_F6, 1) @staticmethod def toggle_piano_roll_visibility(unused_param_value): """Piano Roll""" transport.globalTransport(midi.FPT_F7, 1) @staticmethod def toggle_mixer_visibility(unused_param_value): """Toggle mixer""" transport.globalTransport(midi.FPT_F9, 1) @staticmethod def toggle_browser_visibility(unused_param_value): """Toggle browser""" if PYKEYS_ENABLED: Actions.fl_windows_shortcut('f8', alt=1) else: if ui.getVisible(midi.widBrowser): ui.hideWindow(midi.widBrowser) else: ui.showWindow(midi.widBrowser) ui.setFocused(midi.widBrowser) @staticmethod def toggle_plugin_visibility(unused_param_value): """Toggle plugin""" if SCRIPT_VERSION >= 9: channels.showCSForm(channels.channelNumber(), -1) else: channels.focusEditor(channels.channelNumber()) @staticmethod def undo(unused_param_value): """Undo""" general.undoUp() @staticmethod def redo(unused_param_value): """Redo""" general.undoDown() @staticmethod def close_all_plugin_windows(unused_param_value): """Close all plugin""" Actions.fl_windows_shortcut('f12', alt=1) @staticmethod def cycle_active_window(unused_param_value): """Cycle active win""" ui.selectWindow(False) @staticmethod def name_first_empty_pattern(unused_param_value): """First empty pat""" Actions.fl_windows_shortcut('f4', shift=1) @staticmethod def name_next_empty_pattern(unused_param_value): """Next empty pat""" transport.globalTransport(midi.FPT_F4, 1) @staticmethod def rename_and_color(unused_param_value): """Rename & color""" transport.globalTransport(midi.FPT_F2, 1) @staticmethod def toggle_script_output_visibility(unused_param_value): """Script output""" Actions._navigate_to_menu('view') Actions.fl_windows_shortcut('s') @staticmethod def clone_pattern(unused_param_value): """Clone pattern""" Actions.fl_windows_shortcut('c', ctrl=1, shift=1) @staticmethod def clone_channel(unused_param_value): """Clone channel""" ui.showWindow(midi.widChannelRack) ui.setFocused(midi.widChannelRack) Actions.fl_windows_shortcut('c', alt=1) @staticmethod def enter(unused_param_value): """Press enter""" if PYKEYS_ENABLED: Actions.fl_windows_shortcut('return') else: ui.enter() @staticmethod def escape(unused_param_value): """Press escape""" if PYKEYS_ENABLED: Actions.fl_windows_shortcut('escape') else: ui.escape() @staticmethod def toggle_snap(unused_param_value): """Toggle snap""" ui.snapOnOff() @staticmethod def cut(unused_param_value): """Cut""" ui.cut() @staticmethod def copy(unused_param_value): """Copy""" ui.copy() @staticmethod def paste(unused_param_value): """Paste""" ui.paste() @staticmethod def delete(unused_param_value): """Delete""" ui.delete() @staticmethod def insert(unused_param_value): """Insert""" ui.insert() @staticmethod def up(unused_param_value): """Press up""" ui.up() @staticmethod def down(unused_param_value): """Press down""" ui.down() @staticmethod def left(unused_param_value): """Press left""" ui.left() @staticmethod def right(unused_param_value): """Press right""" ui.right() @staticmethod def channel_rack_up(unused_param_value): """Channelrack up""" select = (channels.channelNumber() - 1) % channels.channelCount() channels.deselectAll() channels.selectChannel(select, 1) @staticmethod def channel_rack_down(unused_param_value): """Channelrack down""" select = (channels.channelNumber() + 1) % channels.channelCount() channels.deselectAll() channels.selectChannel(select, 1) @staticmethod def current_channel_toggle_mute(unused_param_value): """Mute channel""" current = channels.channelNumber() if current >= 0: channels.muteChannel(current) @staticmethod def mixer_track_left(unused_param_value): """Prev mixer track""" select = (mixer.trackNumber() - 1) % (mixer.trackCount() - 1) mixer.setTrackNumber(select, midi.curfxScrollToMakeVisible) @staticmethod def mixer_track_right(unused_param_value): """Next mixer track""" select = (mixer.trackNumber() + 1) % (mixer.trackCount() - 1) mixer.setTrackNumber(select, midi.curfxScrollToMakeVisible) @staticmethod def start_edison_recording(unused_param_value): """Start Edison Rec""" Actions._navigate_to_menu('tools') Actions.fl_windows_shortcut('o') # One click audio recording Actions.fl_windows_shortcut('e') # Edison @staticmethod def random_pattern_generator(unused_param_value): """Random pattern""" Actions._navigate_to_menu('tools') Actions.fl_windows_shortcut('r') @staticmethod def toggle_start_on_input(unused_param_value): """Start on input""" transport.globalTransport(midi.FPT_WaitForInput, 1) @staticmethod def toggle_metronome(unused_param_value): """Metronome""" transport.globalTransport(midi.FPT_Metronome, 1) @staticmethod def toggle_loop_recording(unused_param_value): """Loop recording""" transport.globalTransport(midi.FPT_LoopRecord, 1) @staticmethod def toggle_step_edit(unused_param_value): """Step edit""" transport.globalTransport(midi.FPT_StepEdit, 1) @staticmethod def toggle_start_count(unused_param_value): """Start Count""" transport.globalTransport(midi.FPT_CountDown, 1) @staticmethod def toggle_overdub(unused_param_value): """Toggle Overdub""" transport.globalTransport(midi.FPT_Overdub, 1) @staticmethod def tap_tempo(unused_param_value): """Tap tempo""" transport.globalTransport(midi.FPT_TapTempo, 1) @staticmethod def open_menu(unused_param_value): """Open menu""" transport.globalTransport(midi.FPT_Menu, 1) @staticmethod def item_menu(unused_param_value): """Item menu""" transport.globalTransport(midi.FPT_ItemMenu, 1) @staticmethod def open_mixer_plugin(channel_index): """Open mixer plugin""" if SCRIPT_VERSION < 8: return Actions.noop mixer_track_index = channel_index + 1 mixer.setTrackNumber(mixer_track_index, midi.curfxScrollToMakeVisible) for i in range(Actions._num_effects(mixer_track_index)): transport.globalTransport(midi.FPT_MixerWindowJog, 1) @staticmethod def sync_all_colors(unused_param_value): """Sync all colors""" num_channels = channels.channelCount() for i in range(num_channels): color = channels.getChannelColor(i) mixer_index = channels.getTargetFxTrack(i) if mixer_index <= 0: # Nothing to sync continue mixer.setTrackColor(mixer_index, color) @staticmethod def sync_current_color(unused_param_value): """Sync channel color""" selected = channels.selectedChannel() if selected < 0: return mixer_index = channels.getTargetFxTrack(selected) if mixer_index <= 0: return color = channels.getChannelColor(selected) mixer.setTrackColor(mixer_index, color) @staticmethod def random_color(unused_param_value): """Random color""" selected = channels.selectedChannel() if selected < 0: return rgb = int(Actions.RANDOM_GENERATOR.random() * 16777215.0) channels.setChannelColor(selected, rgb) @staticmethod def rewind_to_beginning(unused_param_value): """Rewind to start""" transport.setSongPos(0) @staticmethod def pianoroll_quick_legato(unused_param_value): """Quick legato""" Actions.fl_windows_shortcut('l', ctrl=1) @staticmethod def pianoroll_quick_quantize(unused_param_value): """Quick quantize""" if ui.getVisible(midi.widPianoRoll) and ui.getFocused( midi.widPianoRoll): Actions.fl_windows_shortcut('q', ctrl=1) @staticmethod def pianoroll_quick_quantize_start_times(unused_param_value): """Qck quantize start""" Actions.fl_windows_shortcut('q', shift=1) @staticmethod def duplicate(unused_param_value): """Duplicate""" Actions.fl_windows_shortcut('b', ctrl=1) @staticmethod def select_all(unused_param_value): """Select All""" Actions.fl_windows_shortcut('a', ctrl=1) @staticmethod def deselect_all(unused_param_value): """Deselect All""" Actions.fl_windows_shortcut('d', ctrl=1) @staticmethod def step_one_step(unused_param_value): """Move 1-step""" Actions._move_song_pos(1, unit='steps') @staticmethod def step_back_one_step(unused_param_value): """Step 1-step back""" Actions._move_song_pos(-1, unit='steps') @staticmethod def step_one_bar(unused_param_value): """Step 1-bar""" Actions._move_song_pos(1, unit='bars') @staticmethod def step_back_one_bar(unused_param_value): """Step 1-bar back""" Actions._move_song_pos(-1, unit='bars') @staticmethod def move_left(unused_param_value): """Move sel. left""" Actions.fl_windows_shortcut('left', shift=1) @staticmethod def move_right(unused_param_value): """Move sel. right""" Actions.fl_windows_shortcut('right', shift=1) @staticmethod def move_up(unused_param_value): """Move sel. up""" Actions.fl_windows_shortcut('up', shift=1) @staticmethod def move_down(unused_param_value): """Move sel. down""" Actions.fl_windows_shortcut('down', shift=1) @staticmethod def add_time_marker(unused_param_value): """Add time marker""" window_active = ui.getVisible(midi.widPianoRoll) and ui.getFocused( midi.widPianoRoll) window_active |= ui.getVisible(midi.widPlaylist) and ui.getFocused( midi.widPlaylist) if not window_active: window = midi.widPlaylist if transport.getLoopMode( ) else midi.widPianoRoll ui.showWindow(window) ui.setFocused(window) Actions.fl_windows_shortcut('t', ctrl=1) @staticmethod def jump_next_time_marker(unused_param_value): """Next marker""" Actions.fl_windows_shortcut('keypad*', alt=1) @staticmethod def jump_prev_time_marker(unused_param_value): """Prev marker""" Actions.fl_windows_shortcut('keypad/', alt=1) @staticmethod def select_next_time_marker(unused_param_value): """Select prev marker""" Actions.fl_windows_shortcut('keypad*', alt=1, ctrl=1) @staticmethod def select_prev_time_marker(unused_param_value): """Select next marker""" Actions.fl_windows_shortcut('keypad/', alt=1, ctrl=1) @staticmethod def mute_current_playlist_track(unused_param_value): """Mute playlist track""" playlist.muteTrack(arturia_playlist.current_playlist_track()) @staticmethod def playlist_track_next(unused_param_value): """Next playlist track""" next_track = min(playlist.trackCount(), arturia_playlist.current_playlist_track() + 1) arturia_playlist.set_playlist_track(next_track) @staticmethod def playlist_track_prev(unused_param_value): """Prev playlist track""" prev_track = max(1, arturia_playlist.current_playlist_track() - 1) arturia_playlist.set_playlist_track(prev_track) @staticmethod def noop(unused_param_value): """Not assigned""" # Do nothing pass # ---------------------- ACTIONS FOR KNOBS ----------------------------- @staticmethod def horizontal_zoom(delta): """Horizontal zoom""" transport.globalTransport(midi.FPT_HZoomJog, delta) # Hack to adjust zoom so that it's centered on current time position. transport.globalTransport(midi.FPT_Jog, 0) @staticmethod def vertical_zoom(delta): """Vertical zoom""" transport.globalTransport(midi.FPT_VZoomJog, delta) @staticmethod def jog2(delta): """Jog2""" transport.globalTransport(midi.FPT_Jog2, delta) @staticmethod def window_jog(delta): """Window Jog""" delta = 0 if delta < 0 else 1 transport.globalTransport(midi.FPT_WindowJog, delta) @staticmethod def mixer_window_jog(delta): """Mixer Window Jog""" delta = 0 if delta < 0 else 1 transport.globalTransport(midi.FPT_MixerWindowJog, delta) @staticmethod def scrub_time_by_bars(delta): """Scrub time 1-bar""" Actions._move_song_pos(delta, unit='bars') @staticmethod def scrub_time_by_half_bars(delta): """Scrub 1/2 bar""" Actions._move_song_pos(STEPS_PER_BAR / 2 * delta, unit='steps') @staticmethod def scrub_time_by_quarter_bars(delta): """Scrub 1/4 bar""" Actions._move_song_pos(STEPS_PER_BAR / 4 * delta, unit='steps') @staticmethod def scrub_time_by_eigth_bars(delta): """Scrub 1/8 bar""" Actions._move_song_pos(STEPS_PER_BAR / 8 * delta, unit='steps') @staticmethod def scrub_time_by_steps(delta): """Scrub pos 1-step""" Actions._move_song_pos(delta, unit='steps') @staticmethod def scrub_time_by_half_steps(delta): """Scrub 1/2 step""" Actions._move_song_pos(_ticks_per_step() / 2 * delta, unit='ticks') @staticmethod def scrub_time_by_quarter_steps(delta): """Scrub 1/4 step""" Actions._move_song_pos(_ticks_per_step() / 4 * delta, unit='ticks') @staticmethod def scrub_time_by_eigth_steps(delta): """Scrub 1/8 step""" Actions._move_song_pos(_ticks_per_step() / 8 * delta, unit='ticks') @staticmethod def scrub_time_by_sixteenth_steps(delta): """Scrub 1/16 step""" Actions._move_song_pos(_ticks_per_step() / 16 * delta, unit='ticks') @staticmethod def scrub_time_by_ticks(delta): """Scrub time 1-tic""" Actions._move_song_pos(delta, unit='ticks') @staticmethod def scrub_active_channel(delta): """Active channel""" if delta < 0: Actions.channel_rack_up(delta) else: Actions.channel_rack_down(delta) @staticmethod def scrub_active_mixer(delta): """Active mixer""" if delta < 0: Actions.mixer_track_left(delta) else: Actions.mixer_track_right(delta) @staticmethod def scrub_left_right(delta): """Left/Right""" if delta < 0: ui.left() elif delta > 0: ui.right() @staticmethod def scrub_up_down(delta): """Up/Down""" if delta < 0: ui.up() elif delta > 0: ui.down() @staticmethod def strip_jog(delta): """Strip jog""" ui.stripJog(delta) @staticmethod def scrub_move_horizontal(delta): """Move horizontally""" if delta < 0: Actions.move_left(delta) else: Actions.move_right(delta) @staticmethod def scrub_move_vertical(delta): """Move vertically""" if delta < 0: Actions.move_up(delta) else: Actions.move_down(delta) @staticmethod def scrub_selection_start_by_sixteenth_steps(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=(_ticks_per_step() / 16.0)) @staticmethod def scrub_selection_start_by_eighth_steps(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=(_ticks_per_step() / 8.0)) @staticmethod def scrub_selection_start_by_quarter_steps(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=(_ticks_per_step() / 4.0)) @staticmethod def scrub_selection_start_by_half_steps(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=(_ticks_per_step() / 2.0)) @staticmethod def scrub_selection_start_by_steps(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=_ticks_per_step()) @staticmethod def scrub_selection_start_by_eighth_bars(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=_ticks_per_bar() / 8.0) @staticmethod def scrub_selection_start_by_quarter_bars(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=_ticks_per_bar() / 4.0) @staticmethod def scrub_selection_start_by_half_bars(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=_ticks_per_bar() / 2.0) @staticmethod def scrub_selection_start_by_bars(delta): """Adjust sel start""" Actions._adjust_selection_range(start_delta=delta, factor=_ticks_per_bar()) @staticmethod def scrub_selection_end_by_sixteenth_steps(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=(_ticks_per_step() / 16.0)) @staticmethod def scrub_selection_end_by_eighth_steps(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=(_ticks_per_step() / 8.0)) @staticmethod def scrub_selection_end_by_quarter_steps(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=(_ticks_per_step() / 4.0)) @staticmethod def scrub_selection_end_by_half_steps(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=(_ticks_per_step() / 2.0)) @staticmethod def scrub_selection_end_by_steps(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=_ticks_per_step()) @staticmethod def scrub_selection_end_by_eighth_bars(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=_ticks_per_bar() / 8.0) @staticmethod def scrub_selection_end_by_quarter_bars(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=_ticks_per_bar() / 4.0) @staticmethod def scrub_selection_end_by_half_bars(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=_ticks_per_bar() / 2.0) @staticmethod def scrub_selection_end_by_bars(delta): """Adjust sel end""" Actions._adjust_selection_range(end_delta=delta, factor=_ticks_per_bar()) # TODO: Mixer plugin scrub # TODO: Preset scrub # TODO: Selection start scrub # TODO: Selection end scrub # ---------------------- ACTION TRANSFORMERS -------------------------- @staticmethod def execute_list(*args_fn, help=None): """Combine multiple actions.""" def _execute_all_fn(unused_param_value): for fn in args_fn: fn(unused_param_value) if help is None and args_fn: help = args_fn[0].__doc__ _execute_all_fn.__doc__ = help return _execute_all_fn @staticmethod def scale_input_by(factor, fn): """Scale the input of a function by a constant factor.""" def scaled_fn(delta): fn(factor * delta) # Make sure to preserve the help doc scaled_fn.__doc__ == fn.__doc__ return scaled_fn @staticmethod def repeated(fn): """Repeat the function based on the absolute input value.""" def repeat_fn(delta): for _ in range(abs(delta)): fn(1 if delta > 0 else -1) # Make sure to preserve the help doc repeat_fn.__doc__ = fn.__doc__ return repeat_fn @staticmethod def scrub(up_action, down_action, display=None): """Returns a function that implements a scrub wheel action from two other actions""" def scrub_fn(delta): if delta < 0: down_action(abs(delta)) elif delta > 0: up_action(delta) if display is None: display = up_action.__doc__ scrub_fn.__doc__ = display return scrub_fn @staticmethod def shortcut(shortcut_sequence, display=None): """Returns a function that implements a shortcut action from a given shortcut string sequence. The sequence is specified in the format "key", "mod1+key", "mod1+mod2+key", "mod1+mod2+...+modN+key". For scenarios where the key is '+', please use '(+)' insteaed. modN keys can be one of ['ctrl', 'alt', 'shift']. Only one key can be specified. The sequence is case insensitive so capitalization does not matter. """ shortcut_sequence = shortcut_sequence.replace('(+)', '[plus]').lower() tokens = set(shortcut_sequence.split('+')) ctrl = 'ctrl' in tokens alt = 'alt' in tokens shift = 'shift' in tokens if display is None: display = shortcut_sequence # Determine the key key = None for t in tokens: if t in ('ctrl', 'alt', 'shift'): continue t = t.replace('[plus]', '+') key = t break print('Key: %s, ctrl=%d, alt=%d, shift=%d' % (key, ctrl, alt, shift)) def shortcut_fn(unused_param): Actions.fl_windows_shortcut(key, ctrl=int(ctrl), alt=int(alt), shift=int(shift)) shortcut_fn.__doc__ = display return shortcut_fn # ---------------------- HELPER METHODS -------------------------- @staticmethod def _num_effects(mixer_track_index): if SCRIPT_VERSION < 8: return 0 cnt = 0 for i in range(10): try: if plugins.isValid(mixer_track_index, i): cnt += 1 except: pass return cnt @staticmethod def _open_app_menu(): # FPT_Menu needs to be triggered when channel rack in focus in order to bring up the app menu. # Save the visibility state of the channel rack and restore at the end. ui.closeActivePopupMenu() channel_rack_visible = ui.getVisible(midi.widChannelRack) # Need to reset focus state of channel rack to ensure menu brought up ui.hideWindow(midi.widChannelRack) ui.showWindow(midi.widChannelRack) ui.setFocused(midi.widChannelRack) transport.globalTransport(midi.FPT_Menu, 1) if not channel_rack_visible: ui.hideWindow(midi.widChannelRack) # Give some time for popup to appear time.sleep(0.2) timeout_time = time.monotonic() + 1 # Avoid exceed waiting more than 1 second while not ui.isInPopupMenu() and time.monotonic() < timeout_time: time.sleep(0.05) @staticmethod def _navigate_to_menu(menu): Actions._open_app_menu() for _ in range(_MENU_LEFT_COUNT[menu]): transport.globalTransport(midi.FPT_Left, 1) @staticmethod def fl_windows_shortcut(key, shift=0, ctrl=0, alt=0): if not PYKEYS_ENABLED: return False if pykeys.platform() == 'win': # FL Studio does not use the win modifier key. pykeys.send(key, shift, 0, ctrl, alt) else: # FL Studio maps the ctrl windows modifier to cmd modifier on macs. Mac version does not use control key. pykeys.send(key, shift, ctrl, 0, alt) return True @staticmethod def _move_song_pos(delta, unit='bars'): """Move the song position by delta units. Params: delta: +/- value indicating amount to move the song position by. unit: one of 'bars', 'steps', 'ticks """ if unit == 'bars': delta_ticks = delta * _ticks_per_bar() elif unit == 'steps': delta_ticks = delta * _ticks_per_step() elif unit == 'ticks': delta_ticks = delta else: raise NotImplementedError( '%s is not a supported unit. Must be one of: bars, steps, ticks' % unit) current_ticks = transport.getSongPos(midi.SONGLENGTH_ABSTICKS) transport.setSongPos(current_ticks + delta_ticks, midi.SONGLENGTH_ABSTICKS) if PYKEYS_ENABLED: # Center on the current time marker Actions.fl_windows_shortcut("0", shift=1) @staticmethod def _adjust_selection_range(start_delta=0, end_delta=0, factor=1.0): start_time = arrangement.selectionStart() end_time = arrangement.selectionEnd() if start_time < 0: start_time = arrangement.currentTime(False) start_time += int(start_delta * factor) start_time = max(0, start_time) if end_time < 0: end_time = start_time + 1 end_time += int(end_delta * factor) end_time = max(0, end_time) arrangement.liveSelection(start_time, False) arrangement.liveSelection(end_time, True)
def test_random(self): rand = _random.Random() result = rand.random() flag = result<1.0 and result >= 0.0 self.assertTrue(flag, "Result is not the value as expected,expected the result between 0.0 to 1.0,but the actual is not")
def __init__(self, controller): def by_midi_id(event): return event.midiId def by_control_num(event): return event.controlNum def ignore_release(event): return self._is_pressed(event) self._controller = controller self._button_hold_action_committed = False self._button_mode = 0 self._locked_mode = 0 self._random = _random.Random() self._mixer_plugins_visible = False self._mixer_plugins_last_track = 0 self._midi_id_dispatcher = (MidiEventDispatcher(by_midi_id).SetHandler( 144, self.OnCommandEvent).SetHandler(176, self.OnKnobEvent).SetHandler( 224, self.OnSliderEvent)) # Sliders 1-9 self._midi_command_dispatcher = ( MidiEventDispatcher(by_control_num).SetHandler( 91, self.OnTransportsBack).SetHandler( 92, self.OnTransportsForward).SetHandler( 93, self.OnTransportsStop).SetHandler( 94, self.OnTransportsPausePlay).SetHandler( 95, self.OnTransportsRecord).SetHandler( 86, self.OnTransportsLoop).SetHandler( 80, self.OnGlobalSave).SetHandler( 87, self.OnGlobalIn, ignore_release).SetHandler( 88, self.OnGlobalOut, ignore_release).SetHandler( 89, self.OnGlobalMetro, ignore_release). SetHandler(81, self.OnGlobalUndo).SetHandlerForKeys( range(8, 16), self.OnTrackSolo, ignore_release).SetHandlerForKeys( range(16, 24), self.OnTrackMute, ignore_release).SetHandlerForKeys( range(0, 8), self.OnTrackRecord).SetHandler( 74, self.OnTrackRead, ignore_release).SetHandler(75, self.OnTrackWrite, ignore_release). SetHandler(98, self.OnNavigationLeft).SetHandler( 99, self.OnNavigationRight).SetHandler( 84, self.OnNavigationKnobPressed, ignore_release).SetHandler(49, self.OnBankNext).SetHandler( 48, self.OnBankPrev).SetHandler( 47, self.OnLivePart1, ignore_release).SetHandler( 46, self.OnLivePart2, ignore_release).SetHandlerForKeys( range(24, 32), self.OnBankSelect, ignore_release).SetHandlerForKeys( range(104, 112), self.OnStartOrEndSliderEvent)) self._knob_dispatcher = ( MidiEventDispatcher(by_control_num).SetHandlerForKeys( range(16, 25), self.OnPanKnobTurned).SetHandler(60, self.OnNavigationKnobTurned)) def get_volume_line(): return ' [%d%%]' % int( channels.getChannelVolume(channels.selectedChannel()) * 100) def get_panning_line(): return ' [%d%%]' % int( channels.getChannelPan(channels.selectedChannel()) * 100) def get_pitch_line(): return ' [%d%%]' % int( channels.getChannelPitch(channels.selectedChannel()) * 100) def get_pattern_line(): return arturia_playlist.get_playlist_track_name( patterns.patternNumber()) def get_channel_line(): return '[%s]' % (channels.getChannelName( channels.selectedChannel())) def get_plugin_line(): return '[%s]' % channels.getChannelName(channels.selectedChannel()) def get_playlist_track(): current_track = arturia_playlist.current_playlist_track() name = arturia_playlist.get_playlist_track_name(current_track) return '%d: [%s]' % (current_track, name) def get_target_mixer_track(): track = channels.getTargetFxTrack(channels.selectedChannel()) return '%d' % track if track > 0 else 'MASTER' self._navigation = (NavigationMode( self._controller.paged_display()).AddMode( 'Channel', self.OnUpdateChannel, self.OnChannelKnobPress, get_channel_line).AddMode( 'Volume', self.OnUpdateVolume, self.OnVolumeKnobPress, get_volume_line).AddMode('Panning', self.OnUpdatePanning, self.OnPanningKnobPress, get_panning_line)) if SCRIPT_VERSION >= 8: self._navigation.AddMode('Pitch', self.OnUpdatePitch, self.OnPitchKnobPress, get_pitch_line) (self._navigation.AddMode( 'Auto Color', self.OnUpdateChannel, self.OnColorKnobPress, get_channel_line).AddMode( 'Plugin Preset', self.OnUpdatePlugin, self.OnChannelKnobPress, get_plugin_line).AddMode('Pattern', self.OnUpdatePattern, self.OnPatternKnobPress, get_pattern_line).AddMode( 'Playlist Track', self.OnUpdatePlaylistTrack, self.OnTrackPlaylistKnobPress, get_playlist_track).AddMode( 'Target Mix Track', self.OnUpdateTargetMixerTrack, self.OnMixerTrackKnobPress, get_target_mixer_track)) self._update_focus_time_ms = 0 self._debug_value = 0 # Mapping of string -> entry corresponding to scheduled long press task self._long_press_tasks = {} # Indicates if punch button is pressed (needed for essential keyboards) self._punched = False # Indicates pad is recording self._is_pad_recording = False self._macros = arturia_macros.ArturiaMacroBank( display_fn=self._display_hint)
def test_setstate_negative(self): # XXX does only make sense on a 32 bit platform import _random rnd1 = _random.Random() # does not crash rnd1.setstate((-1, ) * 624 + (0, ))
import requests import json import _random api = "101090506" r = requests.get('http://t.weather.sojson.com/api/weather/city/' + api) r.encoding = r.apparent_encoding a = r.text data = json.loads(a) city = data["cityInfo"]["city"] shi = data["cityInfo"]["parent"] date = data['time'] forecastdata = data["data"]["forecast"][0] quality = data["data"]["quality"] high = forecastdata["high"] low = forecastdata["low"] week = forecastdata["week"] typea = forecastdata["type"] fx = forecastdata["fx"] fl = forecastdata["fl"] ra = _random.Random(1, 20) print("早上好,我是你爹啊~~") print("爹猜你肯定没看天气预报") print("所以现在爹给你播报天气") print("你现在处在的位置是:憋屈的" + shi + city) print("现在时间为:" + date + " " + week) print("今天的天气是:" + typea + " " + fx + fl + " " + high + " " + low + " 天气指数:" + quality) print("您的亲爹真诚的提醒您,今天也要元气满满哦!") print(ra)