Exemple #1
0
    def __init__(self, *args, **kwargs):
        from E-Commerce.admin.modules.settings import consts
        from E-Commerce.admin.modules.settings.enums import OrderReferenceNumberMethod
        shop = kwargs.pop("shop")
        kwargs["initial"] = {
            consts.ORDER_REFERENCE_NUMBER_LENGTH_FIELD: configuration.get(
                shop, consts.ORDER_REFERENCE_NUMBER_LENGTH_FIELD, settings.E-Commerce_REFERENCE_NUMBER_LENGTH),
            consts.ORDER_REFERENCE_NUMBER_PREFIX_FIELD: configuration.get(
                shop, consts.ORDER_REFERENCE_NUMBER_PREFIX_FIELD, settings.E-Commerce_REFERENCE_NUMBER_PREFIX),
        }
        super(ShopOrderConfigurationForm, self).__init__(*args, **kwargs)

        reference_method = configuration.get(
            shop, consts.ORDER_REFERENCE_NUMBER_METHOD_FIELD, settings.E-Commerce_REFERENCE_NUMBER_METHOD)

        self.prefix_disabled = (reference_method in
                                [OrderReferenceNumberMethod.UNIQUE.value,
                                 OrderReferenceNumberMethod.SHOP_RUNNING.value])

        self.fields[consts.ORDER_REFERENCE_NUMBER_PREFIX_FIELD].disabled = self.prefix_disabled

        decimal_places = 2  # default
        if shop.currency in babel.core.get_global('currency_fractions'):
            decimal_places = babel.core.get_global('currency_fractions')[shop.currency][0]

        self.fields[ORDER_MIN_TOTAL_CONFIG_KEY] = FormattedDecimalFormField(
            label=_("Order minimum total"),
            decimal_places=decimal_places,
            max_digits=FORMATTED_DECIMAL_FIELD_MAX_DIGITS,
            min_value=0,
            required=False,
            initial=configuration.get(shop, ORDER_MIN_TOTAL_CONFIG_KEY, Decimal(0)),
            help_text=_("The minimum sum that an order needs to reach to be created.")
        )
Exemple #2
0
def assert_config_value(rf, admin_user, form_id, key, value, expected_value, shop=None):
    if not shop:
        shop = get_default_shop()

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    view_func = SystemSettingsView.as_view()
    response = view_func(request)
    assert response.status_code == 200

    form_field = "%s-%s" % (form_id, key)
    data = {form_field: value}
    request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
    response = view_func(request)
    assert response.status_code == 302
    if expected_value == "unset":
        expected_value = value
    assert configuration.get(None, key) == expected_value

    assert len(messages.get_messages(request)) == 1

    # Double save the form and the configuration should still be unchanged
    response = view_func(request)
    assert response.status_code == 302
    assert configuration.get(None, key) == expected_value

    assert len(messages.get_messages(request)) == 2

    return shop
Exemple #3
0
async def filternou(self, chan, src, msg):
    if src == self.nickname:
        return

    if not self.users[src]["identified"]:
        return
    user = self.users[src]["account"]

    enabled_chan = configuration.get(self.network,
                                     chan,
                                     "respond-to-nou",
                                     cast=bool)
    enabled_user = configuration.get(self.network,
                                     user,
                                     "respond-to-nou",
                                     cast=bool)

    if not enabled_chan or not enabled_user:
        return

    # don't say "no u" twice within the same TIMEOUT-second period
    if chan in timeouts and timeouts[chan] + TIMEOUT >= time.time():
        return
    timeouts[chan] = time.time()

    await self.message(chan, "no u")
Exemple #4
0
def test_global_configurations():
    with override_settings(CACHES={
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'test_global_configurations',
        }
    }):
        cache.init_cache()
        shop = get_default_shop()
        configuration.set(None, "key1", {"data": "test1"})
        configuration.set(shop, "key2", {"data": "test2"})

        # key1 from shop should come from global configuration
        assert configuration.get(shop, "key1").get("data") == "test1"
        # key2 shouldn't be in global configurations
        assert configuration.get(None, "key2") is None

        # Update global configuration
        configuration.set(None, "key1", {"data": "test_bump"})
        assert configuration.get(shop, "key1").get("data") == "test_bump"

        # Override shop data for global key1
        configuration.set(shop, "key1", "test_data")
        assert configuration.get(shop, "key1") == "test_data"

        # Update shop configuration for global key1
        configuration.set(shop, "key1", "test_data1")
        assert configuration.get(shop, "key1") == "test_data1"
Exemple #5
0
def test_simple_set_and_get_cascading():
    with override_settings(CACHES={
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'test_simple_set_and_get_cascading',
        }
    }):
        cache.init_cache()
        shop = get_default_shop()
        configuration.set(None, "answer", 42)
        assert configuration.get(None, "answer") == 42
        assert configuration.get(shop, "answer", 42)

        assert configuration.get(None, "non-existing") is None
        assert configuration.get(shop, "non-existing") is None
        configuration.set(shop, "non-existing", "hello")
        assert configuration.get(None, "non-existing") is None
        assert configuration.get(shop, "non-existing") == "hello"

        assert configuration.get(None, "foo") is None
        assert configuration.get(shop, "foo") is None
        configuration.set(None, "foo", "bar")
        configuration.set(shop, "foo", "baz")
        assert configuration.get(None, "foo") == "bar"
        assert configuration.get(shop, "foo") == "baz"
Exemple #6
0
    def is_valid(self):
        shipping_required = configuration.get(self.request.shop, SHIPPING_METHOD_REQUIRED_CONFIG_KEY, True)
        payment_required = configuration.get(self.request.shop, PAYMENT_METHOD_REQUIRED_CONFIG_KEY, True)

        if shipping_required and not self.storage.get("shipping_method_id"):
            return False
        if payment_required and not self.storage.get("payment_method_id"):
            return False

        return True
def get_configuration(shop=None, category=None, force_category_override=False):
    default_configuration = configuration.get(
        shop, FACETED_DEFAULT_CONF_KEY, settings.E-Commerce_FRONT_DEFAULT_SORT_CONFIGURATION)

    category_config = configuration.get(None, _get_category_configuration_key(category))
    # when override_default_configuration is True, we override the default configuration
    if category_config and (category_config.get("override_default_configuration") or force_category_override):
        return category_config

    return default_configuration
Exemple #8
0
 def __init__(self, value, adjacencies=None):
     '''Internalizes parameters'''
     self.value = value
     self.adjacencies = [] if adjacencies is None else adjacencies
     color = config.get('WORLD_COLORS')[self.value.world]
     if self.value.elevator:
         color = config.get('WORLD_COLORS')['Elevator']
     self.node = pydot.Node(str((self.value.world, self.value.name)),
                            label=self.value.name,
                            style='filled',
                            fillcolor=color)
Exemple #9
0
 def __init__(self, config_file):
     '''Load configuration and load game data as graph'''
     config.loadConfiguration(config_file)
     worlds = parsing.DataParser(config.get('GAME_DATA')).parse()
     self.graph = graph.Graph.fromWorlds(worlds)
     if not os.path.exists(config.get('DATABASE')):
         self.database = Database.fromWorlds(worlds)
         self.database.write(config.get('DATABASE'))
     else:
         self.database = Database()
         self.database.read(config.get('DATABASE'))
Exemple #10
0
def green_screen_y_cb_cr(filename, image_type, background, path="", rgb_key=(80,200,100), outbox=configuration.get("outbox", "outbox1")):
    # Start the internal function timer
    start = timeit.default_timer()
    configuration.logging.debug("Opening {0} in green_screen_y_cb_cr".format(filename))

    # Open the image and background image and load the pixel data
    img = Image.open(path + filename)
    img = img.convert("RGB")
    bg_img = Image.open(background)
    bg_img = bg_img.convert("RGB")
    pixdata = img.load()
    bg_pixdata = bg_img.load()

    # Get the YCbCr values from the RGB key and set the tolerance
    # y_key, cb_key, cr_key = _ycc(0, 255, 0)
    r_key = rgb_key[0]
    g_key = rgb_key[1]
    b_key = rgb_key[2]
    cb_key = _ycc(r_key, g_key, b_key)[1]
    cr_key = _ycc(r_key, g_key, b_key)[2]
    tola, tolb = configuration.get("green_screen", "tolerance_high"), configuration.get("green_screen", "tolerance_low")

    # Replace all known green screen values
    for y in xrange(img.size[1]):
        for x in xrange(img.size[0]):
            # Get the RGB value and convert to YCbCr
            r, g, b = pixdata[x, y]
            y_p, cb_p, cr_p = _ycc(r, g, b)

            # Calculate the mask based on the key color differences and tolerances
            mask = colorclose(Cb_p=cb_p, Cr_p=cr_p, Cb_key=cb_key, Cr_key=cr_key, tola=tola, tolb=tolb)
            mask = 1.0 - mask

            # Get the background RGB value
            r_bg, g_bg, b_bg = bg_pixdata[x, y]

            # Calculate the portion of the background image that we will take based on the mask created earlier
            r = int(max(r - mask * r_key, 0) + mask * r_bg)
            g = int(max(g - mask * g_key, 0) + mask * g_bg)
            b = int(max(b - mask * b_key, 0) + mask * b_bg)

            # Set the pixel data to this calculation
            pixdata[x, y] = (r, g, b)

    # Save the image
    saved_path = Utilities.save_image(filename=filename, img=img, outbox=outbox, image_type=image_type)

    # Stop the internal function timer and log it
    stop = timeit.default_timer()

    configuration.logging.debug("It took {0} seconds to remove greenscreen with y/cb/cr".format(stop - start))
    return saved_path
Exemple #11
0
def get_running_reference_number(order):
    from E-Commerce import configuration
    from E-Commerce.admin.modules.settings.consts import (ORDER_REFERENCE_NUMBER_PREFIX_FIELD,
                                                     ORDER_REFERENCE_NUMBER_LENGTH_FIELD)
    value = Counter.get_and_increment(CounterType.ORDER_REFERENCE)
    prefix = "%s" % configuration.get(
        order.shop, ORDER_REFERENCE_NUMBER_PREFIX_FIELD, settings.E-Commerce_REFERENCE_NUMBER_PREFIX)
    ref_length = configuration.get(
        order.shop, ORDER_REFERENCE_NUMBER_LENGTH_FIELD, settings.E-Commerce_REFERENCE_NUMBER_LENGTH)

    padded_value = force_text(value).rjust(ref_length - len(prefix), "0")
    reference_no = "%s%s" % (prefix, padded_value)
    return reference_no + calc_reference_number_checksum(reference_no)
Exemple #12
0
 def write_png(self, filename):
     '''Create a png of the graph and write it to file '''
     graph = pydot.Dot(graph_type='digraph',
                       bgcolor=config.get('BACKGROUND'))
     for node in self.nodes:
         graph.add_node(node.node)
     for node in self.nodes:
         for adj in node.adjacencies:
             color = config.get('DOOR_COLORS')['default']
             if adj[1] is not None and adj[1] in config.get('DOOR_COLORS'):
                 color = config.get('DOOR_COLORS')[adj[1]]
             graph.add_edge(pydot.Edge(node.node, adj[0].node, color=color))
     graph.write_png(filename)
Exemple #13
0
 def get_form_defs(self):
     if not self.object.pk:
         return
     initial = {
         "shipping_method_required": configuration.get(self.object, SHIPPING_METHOD_REQUIRED_CONFIG_KEY, True),
         "payment_method_required": configuration.get(self.object, PAYMENT_METHOD_REQUIRED_CONFIG_KEY, True)
     }
     yield TemplatedFormDef(
         name=self.name,
         form_class=self.form,
         template_name="E-Commerce/front/admin/checkout.jinja",
         required=True,
         kwargs={"initial": initial}
     )
Exemple #14
0
def toggle_all_seeing_for_user(user):
    if not getattr(user, "is_superuser", False):
        return

    all_seeing_key = ALL_SEEING_FORMAT % {"user_id": user.pk}
    is_all_seeing = configuration.get(None, all_seeing_key, False)
    configuration.set(None, all_seeing_key, not is_all_seeing)
Exemple #15
0
    def get_methods_validation_errors(self):
        shipping_methods = self.get_available_shipping_methods()
        payment_methods = self.get_available_payment_methods()

        advice = _(
            "Try to remove some products from the basket "
            "and order them separately.")

        if (self.has_shippable_lines() and not shipping_methods and
                configuration.get(self.shop, SHIPPING_METHOD_REQUIRED_CONFIG_KEY, True)):
            msg = _("Products in basket cannot be shipped together. %s")
            yield ValidationError(msg % advice, code="no_common_shipping")

        if not payment_methods and configuration.get(self.shop, PAYMENT_METHOD_REQUIRED_CONFIG_KEY, True):
            msg = _("Products in basket have no common payment method. %s")
            yield ValidationError(msg % advice, code="no_common_payment")
Exemple #16
0
 def ignoreextensions(repositoryfiles):
     """
     add files with extensions to be ignored to the global .gitignore
     """
     ignorefileextensions = configuration.get().ignorefileextensions
     if len(ignorefileextensions) > 0:
         Commiter.ignore(ExtensionFilter.match(repositoryfiles, ignorefileextensions))
Exemple #17
0
def test_consolidate_objects(rf):
    get_default_shop()

    # just visit to make sure GET is ok
    request = apply_request_middleware(rf.get("/"))
    response = APIPermissionView.as_view()(request)
    assert response.status_code == 200

    perm_key = make_permission_config_key(UserViewSet())
    assert configuration.get(None, perm_key) is None

    # now post the form to see what happens
    request = apply_request_middleware(rf.post("/", {perm_key: PermissionLevel.ADMIN}))
    response = APIPermissionView.as_view()(request)
    assert response.status_code == 302      # good
    assert int(configuration.get(None, perm_key)) == PermissionLevel.ADMIN
Exemple #18
0
async def filtersed(self, chan, src, msg):
    enabled = configuration.get(self.network, chan, "sed-pattern", cast=bool)
    if not enabled:
        return

    sections = IS_SED_comp.match(msg).groupdict()
    user = sections["user"] or src

    sedinput = None
    if chan in self.backlog and len(self.backlog[chan]):
        backlog = list(reversed(self.backlog[chan]))
        for back_msg in backlog:
            if back_msg[0] == user:
                if IS_SED_LIBERAL.match(back_msg[1]):
                    continue
                if _sed(sections["sed"], back_msg[1]) is sedinput:
                    continue
                sedinput = back_msg[1]
                break

    if not sedinput:
        return

    sedded = _sed(sections["sed"], sedinput)
    user_noping = fmt.zwnj(user)
    await self.message(chan, f"<{user}> {sedded}")
Exemple #19
0
def test_green_screen_removal2(img):
    # parse through file list in the current directory
    start = timeit.default_timer()
    img = img.convert("RGBA")
    pixdata = img.load()

    green_offset = 39

    # Replace all known green screen values
    for y in xrange(img.size[1]):
        for x in xrange(img.size[0]):
            r, g, b, a = img.getpixel((x, y))
            non_green_max = r if r > b else b
            green_threshold = (non_green_max + green_offset)

            # if ((r <= 110) and (g > 112) and (b < 120) and (b < g)) \
            #         or (g - b > 50 and r <= 110 and g >= 100):
            if g > green_threshold:
                pixdata[x, y] = (255, 255, 255, 0)
                # Remove anti-aliasing outline of body.
            elif r == 0 and g == 0 and b == 0:
                pixdata[x, y] = (255, 255, 255, 0)

    img2 = img.filter(ImageFilter.GaussianBlur(radius=1))
    img2.save(configuration.get("outbox", "test_outbox"), "PNG")
    stop = timeit.default_timer()

    configuration.log_debug_out(configuration.inspect.stack()[0][3], "It took {0} seconds".format(stop - start))
Exemple #20
0
def get_unique_reference_number(shop, id):
    from E-Commerce import configuration
    from E-Commerce.admin.modules.settings.consts import ORDER_REFERENCE_NUMBER_LENGTH_FIELD
    now = datetime.datetime.now()
    ref_length = configuration.get(shop, ORDER_REFERENCE_NUMBER_LENGTH_FIELD, settings.E-Commerce_REFERENCE_NUMBER_LENGTH)
    dt = ("%06s%07d%04d" % (now.strftime("%y%m%d"), now.microsecond, id % 1000)).rjust(ref_length, "0")
    return dt + calc_reference_number_checksum(dt)
    def __init__(self, url_list, finished_queue):
        StoppableThread.__init__(self)
        self._url_list = url_list
        self._queue = finished_queue
        dirpath = configuration.get("video_download_dir")
        # youtube-dl templates are documented here:
        # https://github.com/rg3/youtube-dl/blob/master/README.md#output-template.
        ydl_options = {'outtmpl': dirpath + '/%(title)s.%(ext)s',
                       'format': 'mp4/flv/3gp',
                       'subtitleslang': ['en', 'ru'],
                       'subtitlesformat': 'srt',
                       'writesubtitles': True}

        self._ydl = youtube_dl.YoutubeDL(ydl_options)

        def _raise_hook(status):
            # Check for the stopped condition from the hook using the captured
            # method. Terminate the thread via raising an exception.
            if self.stopped():
                raise Exception("Downloader thread has been stopped.")
            if status['status'] == 'finished':
                convert_vtt_to_srt(dirpath)
                self._queue.put(self._url_list[0])

        self._ydl.add_progress_hook(_raise_hook)
Exemple #22
0
def summary(streamname):
    config = configuration.get()
    shouter.shout("\nAll changes accepted - Migration of stream '%s' is completed."
                  "\nYou can distribute the git-repo '%s'." % (streamname, config.gitRepoName))
    if len(config.ignorefileextensions) > 0:
        # determine and log the ignored but still present files
        os.chdir(config.workDirectory)
        os.chdir(config.clonedGitRepoName)
        pathtoclonedgitrepo = config.workDirectory + os.sep + config.clonedGitRepoName
        if pathtoclonedgitrepo[-1:] != os.sep:
            pathtoclonedgitrepo += os.sep
        ignoredbutexist = []
        with open('.gitignore', 'r') as gitignore:
            for line in gitignore.readlines():
                line = line.strip()
                if line != ".jazz5" and line != ".metadata" and line != ".jazzShed":
                    pathtoignored = pathtoclonedgitrepo + line
                    if os.path.exists(pathtoignored):
                        ignoredbutexist.append(line)
        if len(ignoredbutexist) > 0:
            shouter.shout("\nThe following files have been ignored in the new git repository, " +
                          "but still exist in the actual RTC workspace:")
            ignoredbutexist.sort()
            for ignored in ignoredbutexist:
                shouter.shout("\t" + ignored)
    def __init__(self, url_list, finished_queue):
        StoppableThread.__init__(self)
        self._url_list = url_list
        self._queue = finished_queue
        dirpath = configuration.get("video_download_dir")
        # youtube-dl templates are documented here:
        # https://github.com/rg3/youtube-dl/blob/master/README.md#output-template.
        ydl_options = {'outtmpl': dirpath + '/%(title)s.%(ext)s',
                       'format': 'mp4/flv/3gp',
                       'subtitleslang': ['en', 'ru'],
                       'subtitlesformat': 'srt',
                       'writesubtitles': True}

        self._ydl = youtube_dl.YoutubeDL(ydl_options)

        def _raise_hook(status):
            # Check for the stopped condition from the hook using the captured
            # method. Terminate the thread via raising an exception.
            if self.stopped():
                raise Exception("Downloader thread has been stopped.")
            if status['status'] == 'finished':
                convert_vtt_to_srt(dirpath)
                self._queue.put(self._url_list[0])

        self._ydl.add_progress_hook(_raise_hook)
Exemple #24
0
def test_configuration_gets_saved():
    with override_settings(CACHES={
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'test_configuration_gets_saved',
        }
    }):
        cache.init_cache()
        configuration.set(None, "x", 1)
        assert configuration.get(None, "x") == 1
        configuration.set(None, "x", 2)
        assert configuration.get(None, "x") == 2
        configuration.set(None, "x", 3)
        assert configuration.get(None, "x") == 3
        conf_item = ConfigurationItem.objects.get(shop=None, key="x")
        assert conf_item.value == 3
Exemple #25
0
async def birthday(self, chan, nick, msg):
    user = self.users[nick]["account"]

    args = msg.split()
    if len(args) > 0:
        if args[0] in self.users:
            user = self.users[args[0]]["account"]
        else:
            await self.msg(modname, chan, [f"I don't know who {args[0]} is."])
            return

    birthday_str = configuration.get(self.network, user, "birthday")
    today = datetime.datetime.today()

    if not birthday_str:
        await self.msg(modname, chan, [f"no birthday set for {user}"])
        return

    try:
        birthday = dateutil.parser.parse(birthday_str)
    except:
        await self.msg(modname, chan,
                       [f"invalid birthday '{birthday}' set for {user}"])
        return

    birthday_year = birthday.year
    birthday_date = birthday.replace(year=(today.year + 1))

    years = today.year - birthday_year
    days = birthday_date - today
    await self.msg(modname, chan,
                   [f"{user} is {years + 1} in {days.days + 1} days"])
Exemple #26
0
 def discard(*changeentries):
     config = configuration.get()
     idstodiscard = Changes._collectids(changeentries)
     exitcode = shell.execute(config.scmcommand + " discard -w " + config.workspace + " -r " + config.repo + " -o" + idstodiscard)
     if exitcode is 0:
         for changeEntry in changeentries:
             changeEntry.setUnaccepted()
Exemple #27
0
    def handle_captitalization_filename_changes():
        sandbox = os.path.join(configuration.get().workDirectory, configuration.get().clonedGitRepoName)
        lines = shell.getoutput("git status -z", stripped=False)
        for newfilerelativepath in Commiter.splitoutputofgitstatusz(lines, "A  "):
            directoryofnewfile = os.path.dirname(os.path.join(sandbox, newfilerelativepath))
            newfilename = os.path.basename(newfilerelativepath)
            cwd = os.getcwd()
            os.chdir(directoryofnewfile)
            files = shell.getoutput("git ls-files")
            for previousFileName in files:
                was_same_file_name = newfilename.lower() == previousFileName.lower()
                file_was_renamed = newfilename != previousFileName

                if was_same_file_name and file_was_renamed:
                    shell.execute("git rm --cached %s" % previousFileName)
            os.chdir(cwd)
Exemple #28
0
def get_language_choices(shop=None):
    """
    Returns a list of the available language choices, e.g.:
        [("en", "English", "English"])

    If shot is passed, the languages will be filtered by those
    enabled for the shop.

    :rtype iterable[(str, str, str)]
    """
    available_languages = []
    languages = []

    if shop:
        available_languages = configuration.get(shop, FRONT_AVAILABLE_LANGUAGES_CONFIG_KEY)
        if available_languages:
            available_languages = available_languages.split(",")

    for code, name in settings.LANGUAGES:
        if available_languages and code not in available_languages:
            continue

        lang_info = get_language_info(code)
        name_in_current_lang = ugettext(name)
        local_name = lang_info["name_local"]
        languages.append((code, name_in_current_lang, local_name))
    return languages
Exemple #29
0
def test_variation_templates(browser, admin_user, live_server, settings):
    cache.clear()  # Avoid cache from past tests
    shop = get_default_shop()
    configuration_key = "saved_variation_templates"
    assert configuration.get(shop, configuration_key, None) is None
    product = create_product("test_sku", shop, default_price=10, mode=ProductMode.VARIABLE_VARIATION_PARENT)
    assert product.is_variation_parent()
    initialize_admin_browser_test(browser, live_server, settings)
    browser.driver.set_window_size(800, 1000)
    url = reverse("E-Commerce_admin:shop_product.edit_variation", kwargs={"pk": product.pk})
    browser.visit("%s%s" % (live_server, url + "#variables-section"))
    click_element(browser, '#variables-section > div:nth-child(1) > a:nth-child(2)')
    wait_until_condition(browser, lambda x: x.is_text_present("New template"))

    assert len(ProductVariationVariable.objects.filter(product=product)) == 0 # Size
    assert len(ProductVariationVariableValue.objects.all()) == 0  # Assert no variations are active
    click_element(browser, '.fa.fa-plus')

    wait_until_condition(browser, lambda x: x.is_text_present("New template"))
    browser.fill("variables-template_name", printable_gibberish())  # variables-template_name
    click_element(browser, '#save_template_name')
    wait_until_condition(browser, lambda x: not x.is_text_present("New template"))
    assert len(configuration.get(shop, configuration_key, [])) == 1
    click_element(browser, '#variables-section > div:nth-child(1) > a:nth-child(2)')
    click_element(browser, "#variation-variable-editor")
    browser.find_by_xpath('//*[@id="variation-variable-editor"]/div/div/select/option[2]').first.click()
    wait_until_condition(browser, lambda x: x.is_text_present("Add new variable"))
    click_element(browser, ".btn.btn-lg.btn-text")
    browser.find_by_xpath('//*[@id="product-variable-wrap"]/div/div[2]/div[1]/table/tbody[1]/tr/td[1]/input').first.fill("Size")
    click_element(browser, ".btn.btn-xs.btn-text")
    browser.find_by_xpath('//*[@id="product-variable-wrap"]/div/div[2]/div[1]/table/tbody[2]/tr/td[1]/input').first.fill("S")
    click_element(browser, "#id_variables-activate_template")  # Activate template
    click_element(browser, ".fa.fa-check-circle")  # Save

    assert len(ProductVariationVariable.objects.filter(product=product)) == 1 # Size
    assert len(ProductVariationVariableValue.objects.all()) == 1  # S

    click_element(browser, '#variables-section > div:nth-child(1) > a:nth-child(2)')
    click_element(browser, "#variation-variable-editor") # id_variables-data
    cache.clear()  # Avoid cache from past tests
    assert len(configuration.get(shop, configuration_key, [])) == 1

    browser.find_by_xpath('//*[@id="variation-variable-editor"]/div/div/select/option[2]').first.click()
    template_data = configuration.get(shop, configuration_key, [])[0].get('data')[0]
    browser_data = json.loads(browser.find_by_css("#id_variables-data").value).get('variable_values')[0]
    assert browser_data == template_data  # assert shown template data matches template data in the db
Exemple #30
0
def test_behavior_form():
    shop = get_default_shop()

    assert Script.objects.count() == 0
    assert configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) is None

    form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": True})
    assert form._get_saved_script() is None
    form.save()

    # check if the form creates a order notification correctely
    script = Script.objects.first()
    assert script.pk == configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY)
    assert form._get_saved_script().pk == script.pk
    assert len(script.get_steps()) == 1
    step = script.get_steps()[0]
    step_data = step.serialize()
    assert step_data["next"] == StepNext.STOP.value
    action = step._actions[0]
    assert isinstance(action, SendEmail)
    action_data = action.serialize()
    assert action_data["recipient"]["variable"] == "customer_email"
    assert action_data["language"]["variable"] == "language"
    lang = translation.get_language()
    assert action_data["fallback_language"]["constant"] == lang
    assert action_data["template_data"][lang]["content_type"] == "html"
    assert action_data["template_data"][lang]["subject"] == force_text(data.ORDER_CONFIRMATION["subject"])
    context = {"shop": shop}
    content = loader.render_to_string(data.ORDER_CONFIRMATION["body_template"], context).strip()
    assert action_data["template_data"][lang]["body"] == content

    # the widget must be disabled
    form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": True})
    assert form.fields["order_confirm_notification"].widget.attrs["disabled"] is True

    # clear scripts
    Script.objects.all().delete()
    configuration.set(shop, BEHAVIOR_ORDER_CONFIRM_KEY, None)

    # save the form but do not create the order confirmation notification
    form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": False})
    form.save()

    # nothing created
    assert Script.objects.count() == 0
    assert configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) is None
Exemple #31
0
 def ignoreextensions(repositoryfiles):
     """
     add files with extensions to be ignored to the global .gitignore
     """
     ignorefileextensions = configuration.get().ignorefileextensions
     if len(ignorefileextensions) > 0:
         Commiter.ignore(
             ExtensionFilter.match(repositoryfiles, ignorefileextensions))
Exemple #32
0
    def fetch_credentials(self):
        """
        Method to fetch credentails from .env/personal_credentials

        :param: None
        :return: creds (dict)
        """
        logging.info('fetching user credentials locally...')
        config = configparser.RawConfigParser()
        main_path = os.getcwd()
        path = f"{main_path}/.env/personal_credentials"
        logging.info(f"fetching from path: {path}")
        config.read(path)
        username = config.get('default', 'username')
        password = config.get('default', 'password')
        creds = {'username': username, 'password': password}
        return creds
Exemple #33
0
def reject_image(filename):
    # Get the rejection path from the configuration file
    rejection_path = configuration.get("image_rejection",
                                       "rejection_url") + filename

    # Move the file to the rejection path
    os.rename(filename, rejection_path)

    # If we could not move the file successfully send an email so that this gets taken care of
    # Ultimately the file should be removed from the queue so this will need to be manually checked
    if not os.path.exists(rejection_path):
        Utilities.send_email(
            email_from=configuration.get("image_rejection",
                                         "move_fail_email_from"),
            email_to=configuration.get("image_rejection",
                                       "move_fail_email_to"),
            email_subject=configuration.get("image_rejection",
                                            "move_fail_email_subject"),
            email_body="Failed to move {0} to {1}".format(
                filename, rejection_path))
    # Send an email about the failure - Currently this only applies to file extensions that we don't support
    Utilities.send_email(
        email_from=configuration.get("image_rejection",
                                     "type_reject_email_from"),
        email_to=configuration.get("image_rejection", "type_reject_email_to"),
        email_subject=configuration.get("image_rejection",
                                        "type_reject_email_subject"),
        email_body="Check file: {0}".format(filename))
Exemple #34
0
def test_configuration_cache():
    with override_settings(CACHES={
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'test_configuration_cache',
        }
    }):
        cache.init_cache()

        shop = get_default_shop()
        configuration.set(None, "key1", "test1")
        configuration.set(shop, "key2", "test2")

        # Shop configurations cache should be bumped
        assert cache.get(configuration._get_cache_key(shop)) is None
        configuration.get(shop, "key1")
        # Now shop configurations and key2 should found from cache
        assert cache.get(configuration._get_cache_key(shop)).get("key2") == "test2"
Exemple #35
0
def get_global_configuration(name, default=None):
    """
    Get global configuration variable value.

    :type name: str
    :type default: Any
    """
    from E-Commerce import configuration
    return configuration.get(None, name, default)
Exemple #36
0
 def initialize():
     RTCLogin.loginandcollectstreamuuid()
     workspace = WorkspaceHandler()
     config = configuration.get()
     if config.useexistingworkspace:
         shouter.shout("Use existing workspace to start migration")
         workspace.load()
     else:
         workspace.createandload(config.streamuuid, config.initialcomponentbaselines)
Exemple #37
0
def test_configuration_update():
    with override_settings(CACHES={
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'test_configuration_update',
        }
    }):
        cache.init_cache()
        shop = get_default_shop()
        configuration.set(shop, "key1", {"data": "test1"})
        configuration.set(shop, "key2", {"data": "test2"})
        configuration.set(shop, "key3", {"data": "test3"})
        assert configuration.get(shop, "key1").get("data") == "test1"
        assert configuration.get(shop, "key3").get("data") == "test3"

        # Update configuration
        configuration.set(shop, "key3", {"data": "test_bump"})
        assert configuration.get(shop, "key3").get("data") == "test_bump"
Exemple #38
0
def prepare():
    config = configuration.get()
    rtc = ImportHandler()
    rtcworkspace = WorkspaceHandler()
    # git checkout branchpoint
    Commiter.checkout(config.previousstreamname + "_branchpoint")
    # list baselines of current workspace
    componentbaselineentries = rtc.getcomponentbaselineentriesfromstream(config.previousstreamuuid)
    # set components to that baselines
    rtcworkspace.setcomponentstobaseline(componentbaselineentries, config.previousstreamuuid)
    rtcworkspace.load()
Exemple #39
0
 def __init__(self, kind, room, world,
              info=None, weight=None, deps=None):
     '''Internalizes parameters'''
     self.kind = kind
     self.info = info
     self.room = room
     self.world = world
     if weight is not None:
         self.weight = weight
     else:
         self.weight = config.get("WEIGHT_MAP")[self.kind]
     self.deps = [] if deps is None else deps
Exemple #40
0
def resume():
    shouter.shout("Found existing git repo in work directory, resuming migration...")
    config = configuration.get()
    os.chdir(config.workDirectory)
    os.chdir(config.clonedGitRepoName)
    if Differ.has_diff():
        sys.exit("Your git repo has some uncommited changes, please add/remove them manually")
    RTCLogin.loginandcollectstreamuuid()
    Initializer.preparerepo()
    if config.previousstreamname:
        prepare()
    else:
        WorkspaceHandler().load()
Exemple #41
0
def validate():
    config = configuration.get()
    streamname = config.streamname
    branchname = streamname + "_branchpoint"
    previousstreamname = config.previousstreamname
    offendingbranchname = None
    if not Commiter.checkbranchname(streamname):
        offendingbranchname = streamname
    elif not Commiter.checkbranchname(branchname):
        offendingbranchname = branchname
    elif not Commiter.checkbranchname(previousstreamname):
        offendingbranchname = previousstreamname
    if offendingbranchname:
        sys.exit(offendingbranchname + " is not a valid git branch name - consider renaming the stream")
Exemple #42
0
 def createattributes():
     """
     create a .gitattributes file (if so specified and not yet present)
     """
     config = configuration.get()
     if len(config.gitattributes) > 0:
         newline = os.linesep
         gitattribues = ".gitattributes"
         if not os.path.exists(gitattribues):
             with open(gitattribues, "w") as attributes:
                 for line in config.gitattributes:
                     attributes.write(line + newline)
             shell.execute("git add " + gitattribues)
             shell.execute("git commit -m %s -q" % shell.quote("Add .gitattributes"))
Exemple #43
0
 def accept(logpath, *changeentries):
     for changeEntry in changeentries:
         shouter.shout("Accepting: " + changeEntry.tostring())
     revisions = Changes._collectids(changeentries)
     config = configuration.get()
     Changes.latest_accept_command = config.scmcommand + " accept --verbose --overwrite-uncommitted --accept-missing-changesets --no-merge --repository-uri " + config.repo + " --target " + \
                                     config.workspace + " --changes" + revisions
     exitcode = shell.execute(Changes.latest_accept_command, logpath, "a")
     if exitcode is 0:
         for changeEntry in changeentries:
             changeEntry.setAccepted()
         return True
     else:
         return False
Exemple #44
0
def initialize():
    config = configuration.get()
    directory = config.workDirectory
    if os.path.exists(directory):
        sys.exit("Configured directory already exists, please make sure to use a non-existing directory")
    shouter.shout("Migration will take place in " + directory)
    os.makedirs(directory)
    os.chdir(directory)
    config.deletelogfolder()
    git = Initializer()
    git.initalize()
    RTCInitializer.initialize()
    if Differ.has_diff():
        git.initialcommit()
    Commiter.pushmaster()
Exemple #45
0
    def createignore():
        newline = os.linesep
        git_ignore = ".gitignore"

        if not os.path.exists(git_ignore):
            with open(git_ignore, "w") as ignore:
                ignore.write(".jazz5" + newline)
                ignore.write(".metadata" + newline)
                ignore.write(".jazzShed" + newline)
                config = configuration.get()
                if len(config.ignoredirectories) > 0:
                    ignore.write(newline + "# directories" + newline)
                    for directory in config.ignoredirectories:
                        ignore.write('/' + directory + newline)
                    ignore.write(newline)
            shell.execute("git add " + git_ignore)
            shell.execute("git commit -m %s -q" % shell.quote("Add .gitignore"))
Exemple #46
0
def handle(msg):
    global storage
    global bot
    global video_hostings
    global video_download_queue
    global video_downloader_thread
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type != 'text': return
    msg_lowercase = msg['text'].strip().lower()
    words = msg_lowercase.split()

    if msg_lowercase == '/digest':
        classes = storage.digest(chat_id, MessageClassifier())
        filename = configuration.get("digest_dir") + "/" \
          + "-".join(str(datetime.utcnow()).split()) + ".rst"
        write_rest(classes, filename)
        try:
            pdfname = filename[:-4] + ".pdf"
            write_pdf(filename, pdfname)
            filename = pdfname
        except:
            pass
        bot.sendChatAction(chat_id, 'upload_document')
        bot.sendDocument(chat_id, open(filename, 'rb'))
    elif msg_lowercase == '/pause':
        video_downloader_thread.pause()
    elif msg_lowercase == '/resume':
        video_downloader_thread.resume()
    elif msg_lowercase in ['/silence', '/s']:
        subprocess.call['./silence']
    elif len(words) > 0 and words[0] == "/meditate":
        try:
            meditation_manager.meditate(*words[1:2])
        except MeditationException as e:
            bot.sendMessage(chat_id, str(e))
        except Exception as e:
            print(str(e))
    elif urlparse(msg['text']).netloc.lower().replace("www.", "") in video_hostings:
        storage.store_url(msg)
        video_download_queue.put(msg['text'])
    else:
        storage.store_message(msg)
Exemple #47
0
def migrate():
    rtc = ImportHandler()
    rtcworkspace = WorkspaceHandler()
    git = Commiter

    if existsrepo():
        resume()
    else:
        initialize()

    config = configuration.get()
    streamuuid = config.streamuuid
    streamname = config.streamname
    branchname = streamname + "_branchpoint"

    componentbaselineentries = rtc.getcomponentbaselineentriesfromstream(streamuuid)
    rtcworkspace.setnewflowtargets(streamuuid)

    history = rtc.readhistory(componentbaselineentries, streamname)
    changeentries = rtc.getchangeentriesofstreamcomponents(componentbaselineentries)

    if len(changeentries) > 0:
        git.branch(branchname)
        rtc.acceptchangesintoworkspace(rtc.getchangeentriestoaccept(changeentries, history))
        shouter.shout("All changes until creation of stream '%s' accepted" % streamname)
        git.pushbranch(branchname)

        rtcworkspace.setcomponentstobaseline(componentbaselineentries, streamuuid)
        rtcworkspace.load()

    git.branch(streamname)
    changeentries = rtc.getchangeentriesofstream(streamuuid)
    amountofacceptedchanges = rtc.acceptchangesintoworkspace(rtc.getchangeentriestoaccept(changeentries, history))
    if amountofacceptedchanges > 0:
        git.pushbranch(streamname)
        git.promotebranchtomaster(streamname)

    RTCLogin.logout()
    summary(streamname)
Exemple #48
0
 def __init__(self):
     self.config = configuration.get()
     self.acceptlogpath = self.config.getlogpath("accept.txt")
Exemple #49
0
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import configuration


if __name__ == '__main__':
    configuration = configuration.load()

    mode = configuration.get('mode', '')

    if mode not in ['TCP_SLAVE', 'TCP_MASTER', 'RTU_SLAVE', 'RTU_MASTER']:
        sys.exit('Please set mode to either SLAVE or MASTER')

    if mode == 'TCP_SLAVE':
        from tcp_slave import main
    elif mode == 'TCP_MASTER':
        from tcp_master import main
    elif mode == 'RTU_SLAVE':
        from rtu_slave import main
    else:
        from rtu_master import main

    main()
Exemple #50
0
    def getcommentwithprefix(comment):
        prefix = configuration.get().commitmessageprefix

        if prefix and Commiter.isattachedtoaworkitemregex.match(comment):
            return prefix + comment
        return comment
Exemple #51
0
 def test_getSampleConfig_ExpectInitializedConfigWithDefaultValues(self):
     config = configuration.read(testhelper.getrelativefilename("../config.ini.sample"))
     self.assertEqual("lscm", config.scmcommand)
     self.assertEqual(config, configuration.get())
Exemple #52
0
 def __init__(self):
     config = configuration.get()
     self.repoName = config.gitRepoName
     self.clonedRepoName = config.clonedGitRepoName
     self.author = config.user
Exemple #53
0
        storage.store_message(msg)

storage = storage.Storage("messages.sqlite")
video_hostings = [line[:-1] for line in open("./video-hostings.config")]
video_download_queue = queue.Queue()
video_finished_queue = queue.Queue()
video_downloader_thread = VideoDownloader(video_download_queue, video_finished_queue)
video_downloader_thread.start()

meditation_manager = MeditationManager()

if len(sys.argv) > 1:
    configuration.add_file(sys.argv[1])


digest_dir = configuration.get("digest_dir")
if not os.path.exists(digest_dir):
    os.mkdir(digest_dir)
else:
    if not os.path.isdir(digest_dir):
        raise DigestDirNotWritable(digest_dir)

token = configuration.get("token")
bot = telepot.Bot(token)
bot.message_loop(handle)

print('Listening ...')

# Keep the program running.
while 1:
    time.sleep(10)
Exemple #54
0
 def __init__(self):
     self.config = configuration.get()
     self.workspace = self.config.workspace
     self.repo = self.config.repo
     self.scmcommand = self.config.scmcommand
Exemple #55
0
 def logout():
     config = configuration.get()
     shell.execute("%s logout -r %s" % (config.scmcommand, config.repo))
Exemple #56
0
 def loginandcollectstreamuuid():
     config = configuration.get()
     shell.execute("%s login -r %s -u '%s' -P '%s'" % (config.scmcommand, config.repo, config.user, config.password))
     config.collectstreamuuids()
Exemple #57
0
 def start(self):
     '''Return GraphNode representing room player starts in'''
     return self.graph.map[(config.get('START_WORLD'),
                            config.get('START_ROOM'))]
Exemple #58
0
def existsrepo():
    config = configuration.get()
    repodirectory = os.path.join(config.workDirectory, config.gitRepoName)
    return os.path.exists(repodirectory)