text:
Q: django-imagekit throwing AttributeError exception in ImageCacheFile default ctor function I am working on a project, using the following components:

django: v2.2.10
django-podcasting: 1.3.2
django-imagekit: 4.0.2
django-photologue: 3.11

When I try to add a new podcast show, I get the following error message:

AttributeError at /admin/podcasting/show/add/

Here is the full stack trace:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /admin/podcasting/show/add/
Traceback (most recent call last):
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/__init__.py", line 37, in __init__
    name = generator.cachefile_name
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 95, in cachefile_name
    return fn(self)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/namers.py", line 40, in source_name_as_path
    '%s%s' % (generator.get_hash(), ext)))
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 134, in get_hash
    self.source.name,
  File "/path/to/project/env/lib/python3.6/site-packages/photologue/models.py", line 345, in __getattr__
    raise AttributeError
AttributeError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/path/to/project/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 606, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner
    return view(request, *args, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1645, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "/path/to/project/env/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper
    return bound_method(*args, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1529, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
  File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1572, in _changeform_view
    self.save_model(request, new_object, form, not add)
  File "/path/to/project/env/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1088, in save_model
    obj.save()
  File "/path/to/project/env/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
    force_update=force_update, update_fields=update_fields)
  File "/path/to/project/env/lib/python3.6/site-packages/django/db/models/base.py", line 790, in save_base
    update_fields=update_fields, raw=raw, using=using,
  File "/path/to/project/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "/path/to/project/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/sourcegroups.py", line 33, in receiver
    fn(self, sender=sender, **kwargs)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/sourcegroups.py", line 102, in post_save_receiver
    attname)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/sourcegroups.py", line 124, in dispatch_signal
    signal.send(sender=source_group, source=file)
  File "/path/to/project/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in send
    for receiver in self._live_receivers(sender)
  File "/path/to/project/env/lib/python3.6/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
    for receiver in self._live_receivers(sender)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/registry.py", line 115, in source_group_receiver
    file = ImageCacheFile(spec)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/__init__.py", line 40, in __init__
    name = fn(generator)
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/cachefiles/namers.py", line 91, in hash
    '%s%s' % (generator.get_hash(), ext)))
  File "/path/to/project/env/lib/python3.6/site-packages/imagekit/specs/__init__.py", line 134, in get_hash
    self.source.name,
  File "/path/to/project/env/lib/python3.6/site-packages/photologue/models.py", line 345, in __getattr__
    raise AttributeError
AttributeError
[16/Mar/2020 22:47:47] "POST /admin/podcasting/show/add/ HTTP/1.1" 500 221587

imagekit/cachefiles/init.py
class ImageCacheFile(BaseIKFile, ImageFile):
    """
    A file that represents the result of a generator. Creating an instance of
    this class is not enough to trigger the generation of the file. In fact,
    one of the main points of this class is to allow the creation of the file
    to be deferred until the time that the cache file strategy requires it.

    """
    def __init__(self, generator, name=None, storage=None, cachefile_backend=None, cachefile_strategy=None):
        """
        :param generator: The object responsible for generating a new image.
        :param name: The filename
        :param storage: A Django storage object that will be used to save the
            file.
        :param cachefile_backend: The object responsible for managing the
            state of the file.
        :param cachefile_strategy: The object responsible for handling events
            for this file.

        """
        self.generator = generator

        if not name:
            try:
                name = generator.cachefile_name
            except AttributeError:
                fn = get_by_qname(settings.IMAGEKIT_CACHEFILE_NAMER, 'namer')
                name = fn(generator)
        self.name = name

        storage = storage or getattr(generator, 'cachefile_storage',
            None) or get_singleton(settings.IMAGEKIT_DEFAULT_FILE_STORAGE,
            'file storage backend')
        self.cachefile_backend = (
            cachefile_backend
            or getattr(generator, 'cachefile_backend', None)
            or get_singleton(settings.IMAGEKIT_DEFAULT_CACHEFILE_BACKEND,
                             'cache file backend'))
        self.cachefile_strategy = (
            cachefile_strategy
            or getattr(generator, 'cachefile_strategy', None)
            or get_singleton(settings.IMAGEKIT_DEFAULT_CACHEFILE_STRATEGY,
                             'cache file strategy')
        )

        super(ImageCacheFile, self).__init__(storage=storage)

photologue/models.py
class ImageModel(models.Model):
     # ...

    def __getattr__(self, name):
        global size_method_map
        if not size_method_map:
            init_size_method_map()
        di = size_method_map.get(name, None)
        if di is not None:
            result = partial(getattr(self, di['base_name']), di['size'])
            setattr(self, name, result)
            return result
        else:
            raise AttributeError

/path/to/django-podcasting/podcasting/models.py
@python_2_unicode_compatible
class Show(models.Model):
    """
    A podcast show, which has many episodes.
    """
    EXPLICIT_CHOICES = (
        (1, _("yes")),
        (2, _("no")),
        (3, _("clean")),
    )
    uuid = UUIDField(_("id"), unique=True)

    created = models.DateTimeField(_("created"), auto_now_add=True, editable=False)
    updated = models.DateTimeField(_("updated"), auto_now=True, editable=False)
    published = models.DateTimeField(_("published"), null=True, blank=True, editable=False)

    sites = models.ManyToManyField(Site, verbose_name=_('Sites'))

    ttl = models.PositiveIntegerField(
        _("ttl"), default=1440,
        help_text=_("""``Time to Live,`` the number of minutes a channel can be
        cached before refreshing."""))

    owner = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="podcast_shows",
        verbose_name=_("owner"),
        help_text=_("""Make certain the user account has a name and e-mail address."""))

    editor_email = models.EmailField(
        _("editor email"), blank=True,
        help_text=_("Email address of the person responsible for the feed's content."))
    webmaster_email = models.EmailField(
        _("webmaster email"), blank=True,
        help_text=_("Email address of the person responsible for channel publishing."))

    if 'licenses' in settings.INSTALLED_APPS:
        license = models.ForeignKey(License, on_delete=models.CASCADE, verbose_name=_("license"))
    else:
        license = models.CharField(
            _("license"), max_length=255,
            help_text=_("To publish a podcast to iTunes it is required to set a license type."))

    organization = models.CharField(
        _("organization"), max_length=255,
        help_text=_("Name of the organization, company or Web site producing the podcast."))
    link = models.URLField(_("link"), help_text=_("""URL of either the main website or the
        podcast section of the main website."""))

    enable_comments = models.BooleanField(default=True)

    author_text = models.CharField(
        _("author text"), max_length=255, help_text=_("""
            This tag contains the name of the person or company that is most
            widely attributed to publishing the Podcast and will be
            displayed immediately underneath the title of the Podcast.
            The suggested format is: 'email@example.com (Full Name)'
            but 'Full Name' only, is acceptable. Multiple authors
            should be comma separated."""))

    title = models.CharField(_("title"), max_length=255)
    slug = AutoSlugField(_("slug"), populate_from="title", unique="True")

    subtitle = models.CharField(
        _("subtitle"), max_length=255,
        help_text=_("Looks best if only a few words, like a tagline."))

    # If the show is not on iTunes, many fields may be ignored in your user forms
    on_itunes = models.BooleanField(
        _("iTunes"), default=True,
        help_text=_("Checked if the podcast is submitted to iTunes"))

    description_pretty = models.TextField(
        _("pretty description"), blank=True,
        help_text="May be longer than 4000 characters and contain HTML tags and styling.")

    description = models.TextField(
        _("description"), max_length=4000, help_text=_("""
            This is your chance to tell potential subscribers all about your
            podcast. Describe your subject matter, media format,
            episode schedule, and other relevant info so that they
            know what they'll be getting when they subscribe. In
            addition, make a list of the most relevant search terms
            that you want yourp podcast to match, then build them into
            your description. Note that iTunes removes podcasts that
            include lists of irrelevant words in the itunes:summary,
            description, or itunes:keywords tags. This field can be up
            to 4000 characters."""))

    if 'photologue' in settings.INSTALLED_APPS:
        original_image = models.ForeignKey(Photo, on_delete=models.CASCADE, verbose_name=_("image"), default=None, null=True, blank=True, help_text=_("""
                A podcast must have 1400 x 1400 pixel cover art in JPG or PNG
                format using RGB color space. See our technical spec for
                details. To be eligible for featuring on iTunes Stores,
                choose an attractive, original, and square JPEG (.jpg) or
                PNG (.png) image at a size of 1400x1400 pixels. The image
                will be scaled down to 50x50 pixels at smallest in iTunes.
                For reference see the iTunes
                Podcast specs.

 For episode artwork to
                display in iTunes, image must be
                saved to file's metadata before
                enclosure uploading!"""))
    else:
        original_image = ImageField(
            _("image"), upload_to=get_show_upload_folder, blank=True, help_text=_("""
                A podcast must have 1400 x 1400 pixel cover art in JPG or PNG
                format using RGB color space. See our technical spec for
                details. To be eligible for featuring on iTunes Stores,
                choose an attractive, original, and square JPEG (.jpg) or
                PNG (.png) image at a size of 1400x1400 pixels. The image
                will be scaled down to 50x50 pixels at smallest in iTunes.
                For reference see the iTunes
                Podcast specs.

 For episode artwork to
                display in iTunes, image must be
                saved to file's metadata before
                enclosure uploading!"""))

    if ResizeToFill:
        admin_thumb_sm = ImageSpecField(source="original_image",
                                        processors=[ResizeToFill(50, 50)],
                                        options={"quality": 100})
        admin_thumb_lg = ImageSpecField(source="original_image",
                                        processors=[ResizeToFill(450, 450)],
                                        options={"quality": 100})
        img_show_sm = ImageSpecField(source="original_image",
                                     processors=[ResizeToFill(120, 120)],
                                     options={"quality": 100})
        img_show_lg = ImageSpecField(source="original_image",
                                     processors=[ResizeToFill(550, 550)],
                                     options={"quality": 100})
        img_itunes_sm = ImageSpecField(source="original_image",
                                       processors=[ResizeToFill(144, 144)],
                                       options={"quality": 100})
        img_itunes_lg = ImageSpecField(source="original_image",
                                       processors=[ResizeToFill(1400, 1400)],
                                       options={"quality": 100})

    feedburner = models.URLField(
        _("feedburner url"), blank=True,
        help_text=_("""Fill this out after saving this show and at least one
            episode. URL should look like "http://feeds.feedburner.com/TitleOfShow".
            See documentation
            for more. Manually ping"""))

    # iTunes specific fields
    explicit = models.PositiveSmallIntegerField(
        _("explicit"), default=1, choices=EXPLICIT_CHOICES,
        help_text=_("``Clean`` will put the clean iTunes graphic by it."))
    redirect = models.URLField(
        _("redirect"), blank=True,
        help_text=_("""The show's new URL feed if changing
            the URL of the current show feed. Must continue old feed for at least
            two weeks and write a 301 redirect for old feed."""))
    keywords = models.CharField(
        _("keywords"), max_length=255, blank=True,
        help_text=_("""A comma-demlimitedlist of up to 12 words for iTunes
            searches. Perhaps include misspellings of the title."""))
    itunes = models.URLField(
        _("itunes store url"), blank=True,
        help_text=_("""Fill this out after saving this show and at least one
            episode. URL should look like:
            "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=000000000".
            See documentation for more."""))

    twitter_tweet_prefix = models.CharField(
        _("Twitter tweet prefix"), max_length=80,
        help_text=_("Enter a short ``tweet_text`` prefix for new episodes on this show."),
        blank=True)

    objects = ShowQuerySet.as_manager()
    tags = TaggableManager(blank=True)

    class Meta:
        verbose_name = _("Show")
        verbose_name_plural = _("Shows")
        ordering = ("organization", "slug")

    def __str__(self):
        return self.title

    def get_share_url(self):
        return "http://{0}{1}".format(Site.objects.get_current(), self.get_absolute_url())

    def get_absolute_url(self):
        return reverse("podcasting_show_detail", kwargs={"slug": self.slug})

    @property
    def current_episode(self):
        try:
            return self.episode_set.published().order_by("-published")[0]
        except IndexError:
            return None

I am able to perform CRUD functionality of the photologue app in the admin - so that fact (in conjunction with the stack trace - where the first exception is being thrown in imagekit app), leads me to believe that the error is solely due to the cache name generation code in imagekit.
However, I have spent more than a few hours trying to pinpoint what is causing the errror -but can't locate it. Is this a known bug with django-imagekit or am I missing something?
How do I fix this error?


text: Q: The openwrt router cannot be accessed by the Internet after the IPv6 address is updated My home has an openwrt router, which has the modem provided by the operator to assign IPv6 addresses. I also set up dynamic DNS for it to manage the devices at home at any time. Everything is normal, but my home operator will update the IPv6 address for me every week, and after each update, I can no longer access my router through IPv6, including ICMP and TCP. I checked the results of DDNS and found that the IP address is correct. It seems that when the IPv6 address is updated, my device can still access the Internet through IPv6, but it no longer accepts external access. Whenever I restart my openwrt router at this time, it will return to normal. Does anyone know what is going on?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is such a triangle possible? a triangle angle bac is 45 degrees .
side bc is 4 units .
altitude from point a is 4 units.
Apart from a right angle triangle where altitude becomes side ac is another such triangle possible??

A: An aspect of the "Inscribed Angle Theorem" indicates that all the points $A$ that make an angle of a given size with points $B$ and $C$ lie on an arc of a circle with $\overline{BC}$ as a chord. (The possible angles $\angle BAC$ are said to be "inscribed" in the circle; hence, the name of the theorem.) The $45^\circ$-angle case is shown here:

(BTW: I like to think of this diagram as the top view of a mouse poking its $45^\circ$ angle nose through a hole in the wall (represented by $\overline{BC}$ ... the rest of the mouse is on the other side of the "hole", where we don't see it). The arc gives the boundary of the area the mouse can reach in its quest for cheese. Obviously, mice with wider noses can't reach as far, and mice with narrower noses can poke-out further; but each mouse has its nosey adventures restricted by some circular arc.)

As the diagram indicates, there are exactly two locations for $A$ that are at distance $4$ from $\overline{BC}$, and each of these leads to a right triangle $\triangle ABC$.

Note also: There are at most two locations for $A$ at any distance you care to name, in general: two locations, if the distance is short enough; no locations, if the distance is too far; or precisely one location, if the distance is just right to graze the "top" of the circle.)

A: Let $d$ be the foot perpendicular drawn from vertex $a$ to the side $bc$ then
in right $\triangle adc$ $$\angle dac=\angle acd=45^\circ$$$$\iff ad=dc=4$$$$\color{red}{dc=4}\tag 1$$
since the foot of perpendicular $d$ lies between the points $b$ & $c$ on the side $bc$ hence, $$dc<bc=4$$ $\color{red}{dc<4}\tag 2$
from (1) & (2) there is contradiction.
hence such a triangle is not possible.
However, the given triangle is possible if either $bc>4$ or altitude to the side $bc$ is less than $4$ for given angle of $45^\circ$

A: If you can use trigonometry and the formula for the tangent of the sum then looking at two right  triangles ahc and ahb formed by the altitude ah and the base bc split by the point h  (with bh+hc=4). You have with bh=x:
1=tan(pi/4)= (tan(hac)+tan(hab))/1-tan(hac)tan(hab)=(x/4+(4-x)/4)(1-(x/4)(4-x)/4)=
16/(16-x(4-x))  thus x(4-x)=0 and either b=h or c=h, i.e the right triangle is the only answer.
A different approach is to see that the altitude and the base are the same, thus the area of the triangle is 8 (4*4/2) independent on the position of the base.
Move the little triangle ahc : flip it and glue it to the triangle
ahb, along the intervals ah from the triangle ahc to ab from the triangle ahb.
Comparing the angles the flipped image of the interval  ac will form 45 degree with the old altitude ah. The interval ah as altitude is shorter than ab, and the angle cha is smaller than the external angle b of the triangle ahb.
 So the flipped part will fit well inside the right isoceles triangle based on the original altitude ah and a 4 units extension of hb, in addition the flipped  interval ac is shorter than the hypotenuse of the isoceles as it sees the right angle cha from a shorter distance. But the triangle bac and the isoceles were supposed to be equal in area. Impossible unless there is nothing to flip or we flip the whole triangle.

A: Given any line segment, $bc$, and a point $a$ on one side of it.

*

*The locus of constant $\angle bac$ is a circular arc.

*The locus of constant altitude from $a$ to $bc$ is a line parallel to $bc$.

Since a circle arc intersect a line at at most 2 points, there are at most two solutions for $a$.
From your figure, it is clear there are two places for $a$ which fit your requirement. On one of them, $\angle acb = 90^\circ$ and on the other one,
$\angle abc = 90^\circ$.
This means all solutions are right angled triangles.


text:
Q: SVG in Keynote? I want to use line art in my Keynote presentations.  SVG is the Scalable Vector Graphics format, used natively by Inkscape.
Is there any way to use an SVG in Keynote, or do I need to convert to a PDF?

A: As of Keynote version 7.2 SVG is not supported without conversion using a third party app. (Would be nice though!)


text:
Q: Automatically cut the cord for migrated questions after enough time has passed? A link back to the source question is only minimally useful 35 months later (and 34 months after it was deleted on SO). Perhaps it should either be demoted to something very small and inconspicuous or removed altogether (without manual intervention) after a certain time has passed:

A: I totally agree with you. This information is just useful in the first days a post is migrated. After that it isn't useful any more to the general public.
The migration notice is already put in the revision history on both sites (sample here), so it is accessible to every user at any time. I would suggest to remove the notice from the question page after at most a month or so.

A: Its not necessary for the migration banner to take up so much room, however I'd be hesitant to remove it completely since it is part of the history of the question.
I think it would be useful to have a link somewhere on each question where you could look at meta info about the question itself.  This could include migration details, a time-line of voting, edits made to the post, etc.


text:
Q: CakePHP: Show value stored in another model based on primary key Getting started with CakePHP and loving it. However I'm stuck in this noob situation and I'm not sure which way to solve this.
Basically, I have two models, departures and ports. The tables look like this:
departures

*

*id

*port_from

*port_to

*time_arrival

*time_departure

ports

*

*id

*name

*location

*active

*note

Now I want to list all the departures, port_from and port_to contains ID from ports. Instead of showing just the port ID, I want to show the port name instead, but I have no idea how this could be done?
Using two sets of $this->set in my Departures controller, I have the possibility to show values from the Ports table. I have been looking for solutions but I don't think belongsTo or hasMany is the way to go here?
Thank you for any help.

A: You can set two belongsTo associations in Departure model.
$belongsTo = array(
    'PortForm' => array(
        'className' => 'Port',
        'foreignKey' => 'port_from'
    ),
    'PortTo' => array(
        'className' => 'Port',
        'foreignKey' => 'port_to'
    ),
);

Now when you do a find() on Departure model in the results array, for each Departure record you will have the corresponding PortFrom and PortTo records.

A: You have to set relationship in your model:
class Departure extends AppModel {
    public $belongsTo = array(
        'From' => array(
            'className' => 'Port',
            'foreignKey' => 'port_from'
        ),
        'To' => array(
            'className' => 'Port',
            'foreignKey' => 'port_to'
        )
    ) ;
} ;

Then you just use find or read to get your departure (in your controller):
$this->set('departure', $this->Departure->read(null, $id)) ;

And in view, you access ports name using:
$departure['From']['name'] ;
$departure['To']['name'] ;

And you access normal Departure info using:
$departure['Departure']['time_arrival'] ;


text:
Q: Sorting dict - different result using dict.keys() instead of dict.items() I am trying to sort a dictionary in python using sorted function, but my_dict.items() give me correct result and my_dict.keys() gives me incorrect
my_dict={"one":1, "two":2,"three":3, "four":4,"five":5}

sorted(my_dict.items(), key=lambda x:x[1], reverse=True)

Output:
[('five', 5), ('four', 4), ('three', 3), ('two', 2), ('one', 1)]

Above is correct, but I need only keys not the corresponding values, so I wrote:
sorted(my_dict.keys(), key=lambda x:x[1], reverse=True)

Output:
['two', 'four', 'one', 'five', 'three']

Above is incorrect result, what I am doing wrong? Please help me with the right solution.

A: In the first sort, you apply the function lambda x: x[1] to each element in my_dict.items(). my_dict.items() gives you (key, value) tuples, so you are sorting by value (integers in your case).
In the second sort, you are applying the function lambda x: x[1] to each element in my_dict.keys(). my_dict.keys() gives you strings, so you are sorting by the second character in each string.
Demo:
>>> my_dict = {"one":1, "two":2,"three":3, "four":4,"five":5}
>>> f = lambda x: x[1]
>>> my_dict.items()
dict_items([('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)])
>>> [f(x) for x in my_dict.items()]
[1, 2, 3, 4, 5]
>>> my_dict.keys()
dict_keys(['one', 'two', 'three', 'four', 'five'])
>>> [f(x) for x in my_dict.keys()]
['n', 'w', 'h', 'o', 'i']

A: You are throwing away the values too early - you need them for the sort. You can use your first solution and then select the first element in each tuple after sorting:
[key for key, value in sorted(my_dict.items(), key=lambda x:x[1], reverse=True)]


text:
Q: Scraping a list of urls using beautifulsoup and convert data to csv I am new to Python. Questions below:

*

*I have a list of urls I want to scrape data from. I don't know what is wrong with my code, I am unable to retrieve results from all urls. The code is only scraping the first url and not the rest. How can I successfully scrape data (title, info, description, application) in all urls in the list?

*If question 1 works, how can I convert the data into a CSV file?
Here is the code:
import requests
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import lxml
import pandas as pd
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError

urlList = ["url1","url2","url3"...lists of urls.......]

for url in urlList:
    try:
        html = urlopen(url)
    except HTTPError as e:
        print(e)
    except URLError:
        print("error")
    else:
        soup = BeautifulSoup(html.read(),"html5lib")
# Scraping
def getTitle():
    for title in soup.find('h2', class_="xx").text:
            print(title)

def getInfo():
   for info in soup.find('ul', class_="j-k-i").text:
        print(info)

def getDescription():
    for description in soup.find('div', class_="b-d").text:
        print(description)

def getApplication():
    for application in soup.find('div', class_="g-b bm-b-30").text:
       print(application)

for soups in soup():
    getTitle()
    getInfo()
    getDescription()
    getApplication()

A: Try the following kind of approach:
import requests
from bs4 import BeautifulSoup
from bs4 import BeautifulSoup
import lxml
import pandas as pd
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
import csv

def getTitle(soup):
    return soup.find('h2', class_="xx").text

def getInfo(soup):
    return soup.find('ul', class_="j-k-i").text

def getDescription(soup):
    return soup.find('div', class_="b-d").text

def getApplication(soup):
    return soup.find('div', class_="g-b bm-b-30").text

urlList = ["url1","url2","url3"...lists of urls.......]

with open('output.csv', 'w', newline='')  as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['Title', 'Info', 'Desc', 'Application'])

    for url in urlList:
        try:
            html = urlopen(url)
        except HTTPError as e:
            print(e)
        except URLError:
            print("error")
        else:
            soup = BeautifulSoup(html.read(),"html5lib")
            row = [getTitle(soup), getInfo(soup), getDescription(soup), getApplication(soup)]
            print(row)
            csv_output.writerow(row)

This passes the current soup to each function to use. Each function now returns the text that is found (previously the for loop was printing a character at a time).
Lastly, Python's csv library can be used to easily write a correctly formatted CSV file. It takes a list of values for each row and writes by default a comma separated row in output.csv.
Note: not tested as you have not provided any suitable URLs.


text:
Q: Wordpress Posts Shortcode I would like to display posts within other posts and pages in WordPress without the use of a plugin. I've searched this site (and others) but haven't found a definitive answer to what I am looking for.
I'd like to display a short-code within posts and pages in this fashion:
[insert_post id="99"]
where 99 is the ID of the post (or page, if possible).
I'd like to pull in the following:
title,
the content (first 30 words),
read more button,
featured image (thumb).
Any tips will be appreciated.

A: You need to create the shortcode first. This code goes in your functions.php. Here is a basic example to achieve what you are trying to achieve:
function insert_post_shortcode_function( $atts ) {
    $attributes = shortcode_atts( array(
        'id' => '' // attribute_name => default_value
    ), $atts );

    $return = '';

    $post = get_post($attributes['id']);

    $return .= get_the_post_thumbnail($post->ID);

    $return .= $post->post_title;

    $return .= $post->post_content;

    $return .= 'ID).'">Read more';

    return $return;
}
add_shortcode( 'insert_post', 'insert_post_shortcode_function' );

Now you can use [insert_post id="x"] in your post's content.
More on creating shortcodes - https://codex.wordpress.org/Shortcode_API


text:
Q: Who is he? Who he is? Can we say ...

"Do you know who is he?"

To me, it sounds very unnatural and grammatically incorrect.
Though, I think we can say ...

"Do you know? Who is he?"

in conversation.
Is that right?

A: You have it right. As a single question, we would write:

Do you know who he is? (not, Do you know who is he?)

However, the way you have punctuated these six words makes the wording acceptable in your second example. The first question ("Do you know?") is a lead-in to the second ("Who is he?").
When written that way, I imagine the speaker being rather excited. Perhaps there is a lot of buzz in the street as a celebrity is walking by. Someone might excitedly say to a friend, "Do you know? Who is he?"
I think in a more calm and collected state of mind, the question order is likely to be reversed:

Who is he? Do you know?

A: You might try thinking of the pattern you ask about as follows:

Do you know  {interrogative word} {assertion}?

The clause that states the {assertion} uses normal word-order, subject...verb.
Do you know who {he is} ?
Do you know when {the train arrives}?
Do you know why {the library is closed today}?
Do you know where {my car keys went}?
Do you know how {this knot is tied}?

A:
[1] Do you know [who is he]?
[2] Do you know [who he is]?

The subject-auxiliary inversion in [1] is wrong in most varieties of English, but [2] is fine.
The bracketed element is a subordinate interrogative clause (indirect question). Unlike main clause interrogatives, there is normally no inversion in subordinate interrogatives.
The meaning can be glossed as: "Do you know the answer to the question "Who is he?"'


text: Q: What do you do when someone (obviously) erroneously edits your answer? Today someone accidentally edited one of my answers (he thought he was editing his own).  He quickly noticed his error and reverted it, but it left me thinking:  What should I have done if he hadn't noticed his error?


text:
Q: API Key failure when running Google Map app on Android Phone I am trying to create a map app with the GOOGLE API, for use on android devices, but I'm fairly new to this so have been following tutorials to get me started. I fixed my initial problem, however another one has appeared and I can't find what's wrong / how to change it!
When running the app through a mobile, it loads onto the phone fine, a screen loads (the sort of beige colour you see when google maps is loading) as well as the logo and zoom controls. But stops after this and displays the following error in LogCat:
Authorization Failure. Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
Ensure that the following correspond to what is in the API Console: Package Name: com.example.myapp, API Key: [my api key], Certificate Fingerprint [my code]
Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).
I have completed the steps on the link and checked my code and made sure all those details match, but it's still not working.
This is probably a very basic error, but how would I go about resolving this / Am I looking in the correct place?
[Code no longer here; had to delete it]

A: If you run the app through Eclipse with a USB connected device, you need to use the MAPs debug key. If you export the app and load the .apk on a device, that app would have to be compiled with the production key.

A: Last resort: uninstall and re-install app. Clean and rebuild the project is also a good idea
Moreover, please make sure your API key was an Android key, not a browser or server key. Also check that the service is Google Maps API for Android V2, not Google Maps JavaScript API V2.
If you still get any problems, check your set-up against the top answer in this question: Google Maps API V2 - always get authentication error.


text:
Q: $\mathbb Q$ topological semantics for intuitionistic propositional logic I'm trying to prove that if for every valuation $V : F \to \mathcal O (\mathbb Q)$, we have $V, \Gamma \models A$, (defined by $V(\Gamma) \subseteq V(A)$), then $\Gamma \vdash A$ (completeness of topological semantics with respect to $\mathbb Q$). I'm assured this is true for propositional logic with $\mathbb Q$ or $\mathbb R$ or any product of them (Lectures on the Curry-Howard Isomorphism, theorem 2.4.11).
I tried induction on complexity of formulas, but I hit a problem with disjunction:
If $V(\Gamma) \subseteq V(A) \cup V(B)$, then $\Gamma \vdash A \vee B $. I'd want to use the inductive hypothesis to get either $\Gamma \vdash A$ or $\Gamma \vdash B$ and derive the disjunction, but you can't get either $V(\Gamma) \subseteq V(A)$ or $V(\Gamma) \subseteq V(B)$. If $\Gamma = \emptyset $, then we want $\mathbb Q \subset V(A)$ or $\mathbb Q \subset V(B)$, but both are false if $V(A) = (0, \infty)$ and $V(B) = (-\infty, 1)$.
EDIT: I'm now quite certain that this sort of proof won't work. I'm pretty sure the way other proofs go is by contrapositive, constructing a valuation $V$ such that if $\Gamma \not \vdash A$, then $V(\Gamma) \not \subseteq V(A)$, possibly depending on $\Gamma$ and $A$. I haven't yet attempted this proof but it looks difficult and a reference would still be useful.
Perhaps this proof on induction on complexity doesn't work. I'd like to know how to do a direct proof of this, or to have a reference for topological semantics. I don't like Lectures on the Curry-Howard Isomorphism because it's left as a rather long exercise which goes through Kripke semantics, and I want to do it directly. A proof for $\mathbb R$ would be fine too.


text:
Q: Combining Code Review with Trust Metrics I don't get the chance to partake of it at work. But I love the idea of code review.
Especially of online open source code review like Gerrit Code Review.
I love what Trust Metrics have done for forums and collective intelligences sites on the internet like stackexchange, reddit, and wikipedia.
Would it be possible to combine the two and come up with an open source project management system.
Something that ends up being mostly community driven.
Perhaps a kind of wikipedia of code for a project.
Where submitters become popular/trusted by having lots of patches reviewed favoriably by others, and accepted into the trunk.
And popular/trusted submitters get their patchs accepted faster/easier.
I'm looking for some opinions on the idea, or perhaps pointers to where its been done before, if thats the case.
This might leave the lead maintiner little more to do than:

*

*
wrangle the direction of the project by fast-tracking or vetoing specific patches.

*
settling disputes when the CI tests break, or fixing it himself.

Is design by community worse than design by committee?

A: I like your idea very much but i donot think that it will work :-(
community-sites are based on win-win-situations.

*

*The asker get an answer to an important question.

*the question-reader learns a lot about problems and their solutions.

*The answerer get reputation(-points).

Your idea adds additional winners

*

*(co-) authors have better open source code

*chances are higher that development of that project goes on.

In order to make it simple for all users
it should have a link to codeversioning system (svn, git, mercurial, ....) so there is no need to repost
sourcecode that goes out of sync with the current verion.
My current experience form http://codereview.stackexchange.com is that broad unspecific questions like
 What do you think of this code (followed by a few pages of sourcecode)

is not very attractive for

*

*question-readers because you can not selectivly search for interesting topics.

*for answers because there is a lot of code to read out of context of a complete open source project.

Narrow specific questions on http://codereview.stackexchange.com like ´How can i optimize ...´ are attractive
for ´question-readers´ and ´answerers´ but requires that the
author has the feeling that something has to change.
Codereviews i partcipated in always were combined with refactoring/pairprogramming.
Is this possible via internet where the pair is separated in space and time?
And just voting of "do you think it should be refactored this way" does not solve the problem if there is nobody who does the actual job.


text:
Q: Encryption and decryption of XML file I want to encrypt an XML file and decrypt the same in a different machine in c#. Please help......
I have already tried with RSA algorithm and RijndaelManaged key but not able to decrypt the file in different machine.

A: From the problem description, you're probably looking into symmetric encryption algorithm. This is something that should get you started:
public class Key {
  public string Password { get; set; }
  public byte[] Salt { get; set; }
  public string Vector { get; set; }
  public PaddingMode? Padding { get; set; }
}

public class AesCryptor {
  private const int HASH_SIZE = 32;
  private ICryptoTransform m_Decryptor;
  private ICryptoTransform m_Encryptor;
  private TimeSpan m_Validity;

  // Methods
  public AesCryptor(Key key, TimeSpan validity) {
    if (key == null) {
      throw new ArgumentNullException("key");
    }
    m_Validity = validity;
    using (AesManaged aes = new AesManaged()) {
      aes.Mode = CipherMode.CBC;
      aes.Key = new Rfc2898DeriveBytes(key.Password, key.Salt).GetBytes(aes.KeySize / 8);
      aes.IV = Encoding.ASCII.GetBytes(key.Vector);
      if (key.Padding.HasValue) {
        aes.Padding = key.Padding.Value;
      }
      m_Encryptor = aes.CreateEncryptor();
      m_Decryptor = aes.CreateDecryptor();
    }
  }

  private static bool CompareArray(byte[] first, byte[] second) {
    if (first.Length != second.Length) {
      return false;
    }
    for (int i = 0; i < first.Length; i++) {
      if (first[i] != second[i]) {
        return false;
      }
    }
    return true;
  }

  public byte[] Decrypt(byte[] encryptedData) {
    byte[] hash;
    if (encryptedData == null) {
      throw new ArgumentNullException("encryptedData");
    }
    byte[] buffer = m_Decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    using (SHA256 sha = SHA256.Create()) {
      hash = sha.ComputeHash(buffer, 0, buffer.Length - HASH_SIZE);
    }
    byte[] orginalHash = new byte[HASH_SIZE];
    Buffer.BlockCopy(buffer, buffer.Length - HASH_SIZE, orginalHash, 0, HASH_SIZE);
    if (!CompareArray(orginalHash, hash)) {
      throw new Exception("Hash match failure.");
    }
    if (m_Validity != TimeSpan.Zero) {
      DateTime timestamp = new DateTime(BitConverter.ToInt64(buffer, (buffer.Length - HASH_SIZE) - 8));
      TimeSpan delta = (TimeSpan)(DateTime.Now - timestamp);
      if (delta > m_Validity) {
        throw new Exception("Timestamp too old.");
      }
    }
    byte[] result = new byte[(buffer.Length - HASH_SIZE) - 8];
    Buffer.BlockCopy(buffer, 0, result, 0, (buffer.Length - HASH_SIZE) - 8);
    return result;
  }

  public byte[] Encrypt(byte[] data) {
    byte[] hash;
    if (data == null) {
      throw new ArgumentNullException("data");
    }
    byte[] buffer = new byte[(data.Length + 8) + HASH_SIZE];
    Buffer.BlockCopy(data, 0, buffer, 0, data.Length);
    Buffer.BlockCopy(BitConverter.GetBytes(DateTime.Now.Ticks), 0, buffer, data.Length, 8);
    using (SHA256 sha = SHA256.Create()) {
      hash = sha.ComputeHash(buffer, 0, buffer.Length - HASH_SIZE);
    }
    Buffer.BlockCopy(hash, 0, buffer, buffer.Length - HASH_SIZE, HASH_SIZE);
    return m_Encryptor.TransformFinalBlock(buffer, 0, buffer.Length);
  }
}

Usage:
  var myKey = new Key {
    Password = "whatever,nevermind@$",
    Vector = "Q^!#g1353hdhjs*-",
    Salt = new byte[] { 0x33, 0x4d, 0x56, 0x4f, 1, 0x22, 15, 0x7f }
  };
  var cryptor = new AesCryptor(myKey, TimeSpan.Zero);
  // this will encrypt c:\test.xml into byte array
  byte[] encrypted = cryptor.Encrypt(File.ReadAllBytes(@"c:\test.xml"));
  // this will persist encrypted byte array into file c:\test-encrypted.bin
  File.WriteAllBytes(@"c:\test-encrypted.bin", encrypted);
  // this will load & decrypt bytes from file c:\test-encrypted.bin
  byte[] decrypted = cryptor.Decrypt(File.ReadAllBytes(@"c:\test-encrypted.bin"));
  // this will write decrypted bytes into c:\test-decrypted.xml
  File.WriteAllBytes(@"c:\test-decrypted.xml", decrypted);


text:
Q: Unserialize PHP using Microsoft SQL Query I am trying to import data from a mySQL database into Microsoft SQL because our company uses a mySQL website and MS-SQL Accounting/ERP system.
Anyways... Some of the fields in mySQL are "serialized". I am trying to determine how using sure SQL code I could unserialize and read the data into MS SQL. Is this possible, how?
One of the fields looks like this:
a: 9: {
    s: 15: "product_options";
    a: 2: {
        i: 719;
        s: 4: "2979";
        i: 718;
        s: 4: "2975";
    }
    s: 18: "unlimited_download";
    s: 1: "N";
    s: 7: "product";
    s: 37: "Champion Tagless Ringer Tee - T-Shirt";
    s: 10: "company_id";
    i: 0;
    s: 6: "is_edp";
    s: 1: "N";
    s: 12: "edp_shipping";
    s: 1: "N";
    s: 10: "base_price";
    d: 9.9900000000000002131628207280300557613372802734375;
    s: 12: "stored_price";
    s: 1: "N";
    s: 21: "product_options_value";
    a: 2: {
        i: 0;
        a: 13: {
            s: 9: "option_id";
            s: 3: "719";
            s: 11: "option_type";
            s: 1: "S";
            s: 9: "inventory";
            s: 1: "Y";
            s: 11: "option_name";
            s: 5: "Color";
            s: 11: "option_text";
            s: 0: "";
            s: 11: "description";
            s: 0: "";
            s: 10: "inner_hint";
            s: 0: "";
            s: 17: "incorrect_message";
            s: 0: "";
            s: 8: "modifier";
            s: 5: "0.000";
            s: 13: "modifier_type";
            s: 1: "A";
            s: 8: "position";
            s: 2: "30";
            s: 12: "variant_name";
            s: 13: "White/Scarlet";
            s: 5: "value";
            s: 4: "2979";
        }
        i: 1;
        a: 13: {
            s: 9: "option_id";
            s: 3: "718";
            s: 11: "option_type";
            s: 1: "S";
            s: 9: "inventory";
            s: 1: "Y";
            s: 11: "option_name";
            s: 13: "Clothing Size";
            s: 11: "option_text";
            s: 0: "";
            s: 11: "description";
            s: 0: "";
            s: 10: "inner_hint";
            s: 0: "";
            s: 17: "incorrect_message";
            s: 0: "";
            s: 8: "modifier";
            s: 5: "0.000";
            s: 13: "modifier_type";
            s: 1: "A";
            s: 8: "position";
            s: 2: "20";
            s: 12: "variant_name";
            s: 6: "Medium";
            s: 5: "value";
            s: 4: "2975";
        }
    }
}

Thank you in advance for any assistance anyone can provide on this.

A:
I know this but what to use in just Microsoft SQL code is there a serial and unserialize?

I'm fairly sure there is no direct equivalent to PHP's unserialize() in MS SQL.
You would have to build it yourself - it would be far better to try let PHP handle it.

A: I ran into a similar situation and decided to build my own T-SQL parser function... even though I consider it like beating a nail into a board with a screwdriver. I would recommend finding a different approach, but if this helps someone save time for something quick and dirty, I figure it could be useful.
Unserialize PHP serialized data in T-SQL


text:
Q: hide private symbols automatically I have a C++ project with public and private header files.
To increase encapsulation and decrease symbol clashes in a larger project I would like to export only the minimal set of symbols.
Although we could manually annotate each function with visibility attributes, I'd prefer an approach that does not require changing the source code.
Given the following project structure:
LibA
  include
    *.h
  src
    *.h
    *.cpp

Is there a way to automatically hide all the symbols that don't appear in include/*.h ?
Is there an elegant way of instrumenting the compiler/linker?
Could we automatically generate a version-script ?

A: With gcc and clang, this is as simple as building with -fvisibility=hidden. Then you only have to explicitly export the few public symbols you want exposed.
For more details, there's a gcc article on symbol visibility that you may want to read.

A:
Could we automatically generate a version-script?

You sure could: run nm -C *.o | egrep ' [TDBW] ' to get the list of global symbols, then look in include/*.h to see which ones should be exported. This will likely be fragile: if you e.g. use macros to generate symbol names, this will probablynot work at all.
It may be worth it to generate the list once, hand-curate it, and then maintain it together with the sources by hand in the revision control system.
If the number of symbols to be exported is relatively small, compiling with -fvisibility-hidden and annotating just the public symbols is a much more robust solution.


text:
Q: List of whole pandas values referenced by column and index I have a pandas dataframe and I want to get a list or array of values and their relative positions in the dataframe. So I have:

index
A
B

0
2
5

1
1
4

2
6
3

I want to get
[1,1,A][2,0,A][3,2,B][4,1,B][5,0,B][6,2,A]
Any help?
Thank you very much

A: You can do reset_index then melt
out = df.reset_index().melt('index')[['value','index','variable']].to_numpy().tolist()
Out[533]: [[2, 0, 'A'], [1, 1, 'A'], [6, 2, 'A'], [5, 0, 'B'], [4, 1, 'B'], [3, 2, 'B']]

A: data = {'A': [2, 1, 6], 'B': [5, 4, 3]}
df = pd.DataFrame(data)

list_ = []

for i in range(len(df)):
    for j in range(len(df.columns)):
        value = df.loc[i][j]
        index_ = i
        column_name = df.columns.values.tolist()[j]

        list_.append([value, index_, column_name])

print(list_)

Result:
[[2, 0, 'A'], [5, 0, 'B'], [1, 1, 'A'], [4, 1, 'B'], [6, 2, 'A'], [3, 2, 'B']]

A: Another option:
df.set_index('index').stack().sort_values().reset_index().iloc[:, [2,0,1]].values.tolist()

NB. if "index" is not a column but the index, remove the .set_index('index')
df.stack().sort_values().reset_index().iloc[:, [2,0,1]].values.tolist()

output:
[[1, 1, 'A'], [2, 0, 'A'], [3, 2, 'B'], [4, 1, 'B'], [5, 0, 'B'], [6, 2, 'A']]


text:
Q: Random positioning of child div sometimes overflows parent div. How do I stop/prevent this? Every time I refresh the page, the positioning of the child div sometimes overflow or position itself outside the parent div. Any ideas of how to prevent this? I tried playing around with size of the child div as well as its "top" and "left" values without any luck.
Here is the code:
#box {
            width: 1000px;
            height: 400px;
            background-color: grey;
            margin: 0;
            padding: 0;
        }

        #shape {
            display: none;
            position: relative;
        }

    </style>

Thank you in advance.

A: The reason this occurs is because you do not take into account the random size of the child.
var size = Math.floor(Math.random() * 101) + 50;

That line can produce a size up to 150.
var top = Math.floor(Math.random() * 301);

That line can set the top at a maximum of 300.
The parent div is only 400px tall, so if the size gets computed at 150 and the top at 300 the child will overflow the parent on the bottom by 50px. A similar situation occurs when setting left that will cause the child to overflow on the right of the parent. You need to constrain top and left. Example below.

function makeShapeAppear() {
    var size = Math.floor(Math.random() * 101) + 50;
    var top = Math.min(Math.floor(Math.random() * 101), 180 - size);
    var left = Math.min(Math.floor(Math.random() * 301), 400 - size);

    document.getElementById("shape").style.display = "block"
    document.getElementById("shape").style.top = top + "px";
    document.getElementById("shape").style.left = left + "px";
    document.getElementById("shape").style.width = size + "px";
    document.getElementById("shape").style.height = size + "px";
    document.getElementById("shape").style.backgroundColor = "red";

    setTimeout(function() { makeShapeAppear(); }, 1000);
}

makeShapeAppear();
#box {
    width: 400px;
    height: 180px;
    background-color: grey;
    margin: 0;
    padding: 0;
}

#shape {
    display: none;
    position: relative;
}


text: Q: How to avoid memory problems when realizing a multiple PDF JAX-RS generation service? My Jersey based JAX-RS 1.0 service generates multiple PDFs in the background per request which leads to a memory exception when this service is called in parallel by many clients. My idea was to queue the requests in some kind of batch which are then processed sequentially avoiding the memory exception. Looking for a solution I stumbled upon JMS, and Java EE 7's batch mechanism. Also log systems such as BookKeeper and Kafka seem to be candidates. But I'm wondering if there is a more lightweight solution? Is the event model from Java EE's DI standard suitable? Any experiences with a similar problem?


text:
Q: Display loading image while post with ajax is NOT Working Here is a div which contains a GIF animation:

    Loading... Please Wait...

and Here is a Function which contains AJAX POST Method:
    function Handler(datas, ele) {
        $('#busy').show();
        $.ajax({
            url: "FileUploadHandler.ashx",
            type: "POST",
            data: datas,
            contentType: false,
            processData: false,
            success: function () {
                    ele.width = 100;
                    $('#busy').hide();
            }
        });
    }

as you can see I have used show and hide on that target div. But it is not working at all and I do not know where is the problem?

A: You need to setup beforeSend method in order to show loading progress and on complete hide it. Only in this case, you guarantee that on success/failure animation will be hidden.
 function Handler(datas, ele) {
        $.ajax({
            url: "FileUploadHandler.ashx",
            type: "POST",
            data: datas,
            contentType: false,
            processData: false,
            beforeSend  : function() {
                  $("#busy").show();
            },
            success: function () {
               ele.width = 100;

            },
            complete: function() {
                $("#busy").hide();
            }

        });
    }

function showHide(){
  if($('#busy').css("display") == "none"){
      $('#busy').show();
  } else {

       $('#busy').hide();
  }

}

<input type="button" value="click" onclick="showHide()" />


text:
Q: Does Azure Pack support auto scaling Web and Worker roles with WASABi? WASABi seems to support autoscaling of Web and Worker roles in Azure public cloud, however it's not clear if the same behavior can be applied to on site Azure Pack (private cloud) instances. Anyone know?

A: Auto Scaling is not supported on Azure Pack. Auto scaling is actually an azure wide feature that is not in Azure Pack yet.
I don't have a timeline for your request for the feature yet. (Yes sadly even after an year)
Try Azure Service Fabric they have a lot of cool feature to scale your site up and down and they are connected to both on-premise and on azure. It is worth a look for your scenario.
Happy to help, -CB


text:
Q: Styling lost when placing a  inside a  tag Currently, I have a box which has some text inside it. Currently, the link is only applied to some text as below:

Free delivery worldwide*

     *More info here

This is how it appears on the site:
https://snag.gy/sbC421.jpg
However, I want the whole link placed in the whole box and as with HTML I just place the  tag inside the  tag but I seem to lose all the styling and the padding goes I think? Code:

Free delivery worldwide*

     *More info here

This is how it looks after:
https://snag.gy/KZzSUv.jpg
Any help is greatly appreciated!

A: I think you are referencing the .box div using a css selector that requires the parent element to be a div
so you might have to change the css for the box element to something like
a > .box {
   /* styles */
}

check this image for more info

A: Decided to do it with JavaScript inside using the below for the parameters of the div tag:
onclick="document.location='#'"

This solution is neater for what I am after and as I am using several style sheets it was difficult to spot the culprit.


text:
Q: Tell Selenium web driver to keep clicking "next" button until it can't Here is my code:
for i in range(1,20):
    driver.find_element_by_link_text('Next').click()
    time.sleep(5)
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    token_holders = token_holders + soup.find_all('tr')
    del token_holders[50*i]
    time.sleep(5)

I want the webdriver to keep clicking "Next" until it can't rather than me entering the amount of times it should be clicked in the for loop, but I'm not sure how I can do that

A: Just replace for loop with while loop as follows:
from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        driver.find_element_by_link_text('Next').click()
    except NoSuchElementException:
        break
    time.sleep(5)
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    token_holders = token_holders + soup.find_all('tr')
    del token_holders[50*i]
    time.sleep(5)

This should allow you click "Next" button while it's possible or stop in case no button found on page


text:
Q: Is there a SequenceMatcher in R? I found Python's difflib really useful and I was wondering if there is something similar to SequenceMatcher in R.
Here, there is a Python example of what I would like to get in R:
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0


text:
Q: VB6 IDE is changing the case of my enumeration names I'm required to maintain a few VB6 apps, and I have run into a weird problem when it comes to enumeration names.  The way Intellisense in VB6 is supposed to work is that if my variable name is defined as, say, Dim Abraxis as String, and I type abraxis while coding, the IDE changes it to Abraxis on the fly as I leave the word.  However, I have found that if I have an enumeration set up like this, for example:
Public Enum tiErrorEnum
  tiNone = 0
  tiWarning
  tiError
  tiDupDoc
End Enum

and I use one of the enums in a statement, such as
ErrorNum = tinone

expecting the casing to be fixed by the IDE, it doesn't change tinone to tiNone, but it does change the def of the enum member to tinone!  Exactly backwards!
Is there a workaround?

A: Yes, there is.  It's kind of odd-looking, and you probably want to comment on why you're doing it in your code so future devs don't get perplexed about it, but here's what you want to do.  Add the enumerations as Public items inside a compiler directive code block (so the compiler can't see it, of course).  You should do this preferably right below the enumeration declaration, like this:
Public Enum tiErrorEnum
  tiNone = 0
  tiWarning
  tiError
  tiDupDoc
End Enum
#If False Then
  Public tiNone
  Public tiWarning
  Public tiError
  Public tiDupDoc
#End If

Simple.  The IDE will recognize and hold the enumeration names correctly, and the compiler will ignore the block.

A: This is a bug in the editor. I seem to remember that if you type the name of an enum rather than use the intellisense it changes the case of the enum value name in the declaration.

A: The trick is to always qualify your enumerations:
tiErrorEnum.tiDupDoc

Intellisense will then correctly list the enumeration after pressing dot.  I think this will also aid code readability if you enumeration is well named.


text:
Q: sql resultset order defined? Say I've employee table where any employee can be related to any other employee (many to many). Each employee has many characteristics that are stored separately.
emp: id,name
related: name,emp1role,emp1id,emp2role,emp2id
chars: empid,name,value

I want to get all the characteristics of employees who are related via 'xxx' along with the relation. I am currently using this query:
SELECT c.empid, c.Name, c.Value
FROM chars as c, related as r
WHERE r.name='xxx' AND (r.emp1id=c.empid OR r.emp2id=c.empid)

This works and it gives related employees one after another i.e. if emp22 & emp43 are related via 'xxx' then I am getting chars of emp43 followed by emp22 and so on. This way I am able to know which two employees are related (which is needed). However, I want to know if this order is mere luck or is it well-defined. This is in SQLite.
If it is not defined way, how else can I do it? Also, I need to know their respective roles. I want to preferably do it in one query. Can you think of some other query?
Thanks in advance,
Manish
PS: These are not actual tables. They are here for simplicity of asking question.

A: In SQL, ordering of the result is undefined unless you have an explicit ORDER BY clause in your query. So I believe you want:
SELECT c.empid, c.Name, c.Value
FROM chars as c, related as r
WHERE r.name='xxx' AND (r.emp1id=c.empid OR r.emp2id=c.empid)
ORDER BY c.empid ASC

I tend to add a unique field (such as a primary key) at the end, to if not get an obvious ordering when there are multiple records matching in all other order fields, at least get deterministic ordering. But that's largely a matter of style and choice; it's by no means required.


text:
Q: SCRIPT5007: Unable to get property 'innerText' of undefined or null reference but works when run through debugger I'm not an experienced javascript programmer so apologies in advance for what is probably a very simple problem.
In the following code I call the akpOpen function to open 2 pop-up windows (IE10), compare the contents of table cells and highlights differences by changing the background color.
<script language="javascript">
var nw;
var ow;
function genericOpen(k,n,w,h,t,l) {
 var w = window.open(k, n,
             'width=' + w + ',height=' + h + ',resizable=yes,menubar=0' +
             ',top=' + t + ',left=' + l + ',location=0,toolbar=0' +
             ',scrollbars=1');
 return(w);
}
function checkValues() {
   for (r = 0; r<999; r++) {
      var id = 'r' + r + 'c1';
      if (ow.document.getElementById(id).innerText !=
          nw.document.getElementById(id).innerText) {
          nw.document.getElementById(id).bgColor = 'red';
          ow.document.getElementById(id).bgColor = 'red';
      }
   }
}
function akpOpen(nkey,okey) {
 nw = genericOpen('CNCM0012?KEY=' + nkey, 'w1', 500, 150, 100,80);
 ow = genericOpen('CNCM0012?KEY=' + okey, 'w2', 500, 150, 100,600);
 checkValues();
}
</script>

The code works fine if I am loading the pages as static content from my hard drive. If I load the pages from the server which involves a database query and dynamic content I get the following error:
SCRIPT5007: Unable to get property 'innerText' of undefined or null reference
If I debug the dynamic pages using F12, the code works perfectly.
If I allow the debugger to intercept the error and I view the locals, I can see the 'nw' and 'ow' window handle globals plus their associated elements, and I can find the elements that the getElementById refers to. It seems like a timing issue but I have no experience in this area. Any help would be appreciated.
Thanks

A: You're trying to access the content of the windows you're opening dynamically before the windows have had a chance to load. You need to either poll or wait for the window's load event to occur.
Using the load event is trivial. If you want to poll, the easiest way would be to put an element with a specific id value at the end of the response you're generating, then:
function checkValues() {
   if (!ow.document.getElementById("marker") ||
       !nw.document.getElementById("marker")) {
       // One or the other is still loading, wait
       setTimeout(checkValues, 100); // Milliseconds
   }
   else {
      for (r = 0; r<999; r++) {
         var id = 'r' + r + 'c1';
         // You might also want to put a guard here in case some of these 'r' elements don't exist
         if (ow.document.getElementById(id).innerText !=
             nw.document.getElementById(id).innerText) {
             nw.document.getElementById(id).bgColor = 'red';
             ow.document.getElementById(id).bgColor = 'red';
         }
      }
   }
}


text:
Q: SessionAsSigner & restoreWrappedDocument() Faced with the following issue: I am actively use DominoDocument class (wrapped Document) in my projects, particularly as basis for my business model objects.
Very often I have a need to access / iterate my business model objects as Anonymous user thus underlying lotus.domino.Document retrieved based on SessionAsSigner session object (for example in case of some REST Services, or in case of xAgent, etc).
The behavior of restoreWrappedDocument() method in such cases really breaks all flexibility of using such architecture: this method tries to restore wrapped document based on current execution environment access rights, and of course that causes errors with ACL.
Let's consider the following code snippet as example:
public void test3() {
    try {

        System.out.println(">>>>>");
        System.out.println(">>>>> START");

        lotus.domino.Database db = AppBean.getSessionAsSigner().getDatabase(AppBean.getInstance().getContactsDBserverName(), AppBean.getInstance().getContactsDBname(), false);

        Document notesDoc = db.getAllDocuments().getFirstDocument();
        String dbName = notesDoc.getParentDatabase().getServer() + "!!" + notesDoc.getParentDatabase().getFilePath();
        DominoDocument ds = DominoDocument.wrap(dbName, notesDoc, null, "exception", false, "UseWeb", null);

        System.out.println(">> 1 >> " + ds.getValue("form"));

        ds.getDocument().recycle();

        try {
            ds.restoreWrappedDocument();
        }catch(Throwable e2){
            System.out.println(">> 2 - exception - >> " + e2.toString());
            e2.printStackTrace();
        }

        try {
            System.out.println(">> 3 >> " + ds.getValue("form"));
        }catch(Throwable e3){
            System.out.println(">> 3 - exception - >> " + e3.toString());
        }

        System.out.println(">>>>> END");
        System.out.println(">>>>>");

    }catch(Exception e){
        e.printStackTrace();
    }
}

1) Scenario 1: executing this code by authenticated user that has access to target DB gives the following result:

So method works as expected and everything perfect.
2) Scenario 2: executing this code by Anonymous user causes Exception (generally, what is expected):

You can clearly see that restoreWrappedDocument() executes some helper methods in order to get DB, and of course that is done with current user access level (Anonymous).
Possible solutions:

*

*The obvious solution is to add custom logic to my business object model, which will perform custom restore (basically based on Server&DB names and document UNID or NoteID).

*What I am very curious whether there is any more smart or built-in method exist for restoring wrapped documents with SessionAsSigner rights?
Thanks!

A: I don't think there's a proper way to do this, other than your option 1, for better or for worse.
However, and I'm not saying this is a good idea, it seems like DominoDocument likely gets to its session through the current request map. If you want to be tricky, you could try temporarily swapping session out for sessionAsSigner in the request scope, calling restoreWrappedDocument, and then swapping it back.

A: A solution with a Helper class using Java Reflection:
(Incomplete, missing some parts)
package ch.hasselba.xpages;

import java.lang.reflect.Field;

import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.NotesException;

import com.ibm.xsp.FacesExceptionEx;
import com.ibm.xsp.model.domino.DominoUtils;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;

public class DominoDocumentUtil {

    private static final long serialVersionUID = 1L;
    private transient final Field wrappedObj;
    private transient final DominoDocument dominoDoc;

    public DominoDocumentUtil(DominoDocument doc) throws SecurityException,
            NoSuchFieldException {
        dominoDoc = doc;
        wrappedObj= doc.getClass().getDeclaredField("_wrappedObject");
        wrappedObj.setAccessible(true);
    }

    public void restoreWrappedDocument(Database db)
            throws IllegalArgumentException, IllegalAccessException {
        try {
            Document doc = DominoUtils.getDocumentById(db, dominoDoc
                .getDocumentId(), dominoDoc.isAllowDeletedDocs());
            this.wrappedObj.set(dominoDoc, doc);
        } catch (NotesException ne) {
            throw new FacesExceptionEx(ne.getMessage());
        }
    }
}

To use the class you can call the restoreWrappedDocument method with a database opened with sessionAsSigner:
DominoDocumentUtil util = new DominoDocumentUtil(ds);
util.restoreWrappedDocument(db);


text:
Q: Catch "Try Again" with ionic speech recognition I am using Ionic Native speech recognition as outlined in the docs: https://ionicframework.com/docs/native/speech-recognition:
startListening() {
    this.speechRecognition.startListening()
      .subscribe(
        (matches: Array<string>) => {
          console.log(matches)
        },
        (onerror) => {
          console.log('error:', onerror)
        }
     )
}

However, this only listens for a certain amount of time. If nothing has been said, or the speech was unable to hear it, I receive the message "Tap to speak. Try again". However, for this the user needs to press a button to be able to speak again. Is there therefore a way to catch when this happens such that I can trigger this.startListening() again?

A: I find in the doc, the speech recognition only 5 times and after that it stop.
https://github.com/pbakondy/cordova-plugin-speechrecognition.
You can start listening with options :

let options = {
  String language,
  Number matches, // increase this number if don't want  to stop listening
  String prompt,      // Android only
  Boolean showPopup,  // Android only
  Boolean showPartial
}

this.speechRecognition.startListening(options)
  .subscribe(
    (matches: Array<string>) => console.log(matches),
    (onerror) => console.log('error:', onerror)
  )


text:
Q: Urn with black & white balls. Draw one ball then place it back. Repeat until 2 balls with different colors. Probability the last draw was white? So I'm having problems with this one. It says:
We draw with replacement two balls from an urn containing k black balls and l white balls where $k\ne l$ (with replacement the question means: draw one ball put it back in the urn, draw another ball put it back in the urn. So the experiment we are working here consists in drawing these 2 balls and comparing them, if they have the same color we start over with another experiment). This process is repeated until, for the first time, we draw two balls with different colors. Calculate the probability that the last ball you draw from this pair is white.
And the possible answers are: a) l/(k+l), b) k/(k+l), c) 1/2, d) 3/4, e) l(1-l)/(l(1-l)+k(1-k))
Should I use Bayes? I'm having problems modeling this problem.

A: You can disregard all instances where both balls have the same color. Just condition on the event that you have drawn two different balls. The answer then is obvious.

A: Well I'm bad at math and I have issues to understand the questions.
So indeed as N. F. Taussig said what the problem means with the reposition part is that you look at one ball then place it back in the urn, look at another ball place it back, do this until you draw 2 balls with different colors.
So the asnwer should be obvious but i need to prove it somehow, my teacher wants some logic in the answer so I tried to solve this using Bayes.
Let P(B) and P(W) be the probability of drawing a black and a white ball respectively and, for example, inside the experiment of drawing 2 balls, P(W1) is the probability of drawing a white ball in the first draw. Let A be the event where we draw 2 balls with different colors. So we want:
$$P(W2|A) = \frac{P(A|W2)*P(W2)}{P(A)}$$
Now $P(A) = P(W1)*P(B2) + P(B1)*P(W2)$
And $P(A|W2) = P(B1W2 + W1B2|W2) = P(B1)$
Which leave us with:
$$P(W2|A)=\frac{P(B1)*P(W2)}{P(B1)*P(W2)+P(W1)*P(B2)} = \frac12$$


text:
Q: PyQT4 TextBrowser Set Text Alighment I am doing some random choice picker where there's a place to display info user keyed in. (which I used text browser), How do I set the text to be always align center?
    self.textBrowser.setText(newList + "\n\nanalyzing in ...")

    QtTest.QTest.qWait(1000)

    self.textBrowser.setText(newList + "\n\nanalyzing in ..." + "\n\n       3")

A: QTextBrowser Class  Inherits: QTextEdit

QTextEdit::setAlignment(Qt::Alignment)
Sets the alignment of the current paragraph to a. Valid alignments are Qt::AlignLeft, Qt::AlignRight, Qt::AlignJustify and Qt::AlignCenter (which centers horizontally).

Sorry, I have PyQt5:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Win(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.i = 5

        self.textBrowser = QtWidgets.QTextBrowser()

        self.textBrowser.setAlignment(QtCore.Qt.AlignCenter)  # <-------------

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.textBrowser)
        self.setLayout(layout)

        timer = QtCore.QTimer(self, interval=1000, timeout=self.print_out)
        timer.start()

    def print_out(self, string="Hello world!"):
        self.textBrowser.append(string + "\n\nanalyzing in ...\n {}".format('----' * self.i))
        self.i += 1

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myWin = Win()
    myWin.show()
    sys.exit(app.exec_())


text:
Q: Nesting razor C# in JavaScript I'm nesting razor C# in JavaScript and I'm calling this function inside a button but when I press the button nothing happens. What am I doing wrong?
<script>
    @functions{
        public void Validation()
        {
            StudentTable sTable = new StudentTable();
            var username = Request["username"];
            var password = Request["password"];
            var error = "";
        if(sTable.Login(username, password) != null)
        {
            Response.Redirect("Success.html");
        }
        else
        {
            error = "Username/password entered is incorrect";
        }
</script>
}
}
<p>@error</p>
<button class="btn btn-default btn-primary" id="signin" type="submit" value="Signin" onclick="@functions" formmethod="post">Sign in</button>

A: You are mixing and matching javascript (which runs on the client) and C# (which runs on the server).  You will have to make an ajax request do do this validation or do this on a post back.


text:
Q: Any system tables/views to determine query volume per table I was digging through the SQL Server system views and Windows performance counters and can't find any metrics regarding query volume PER TABLE in a given database. I am looking for any type of information to gauge the usefulness of each table in a given database. Query count/row count/data size of query results, or anything along those lines would be great. Does anyone have suggestions for how to see this data per table? I could do a Profiler trace or XE session over time, and then query those results to do some grouping, but don't want the added overhead if the data is already there somewhere.

A: You can use statistics data by tracking the most modified ones
   SELECT
   --into ##SQL_STATS_INFO
   --comment out h. columns for non-sql 2016 servers
  distinct
    (select db_name()) as Database_name
    ,o.name as Table_name
    ,c.name AS column_name
    ,s.name AS statistics_name

    ,p.last_updated
    ,p.rows
    ,p.rows_sampled
    ,h.range_high_key
  ,h.range_rows
  ,h.equal_rows
  ,h.distinct_range_rows
  ,h.average_range_rows
,p.modification_counter
  ,h.step_number
   --,sc.stats_column_id
  FROM sys.stats AS s
cross apply sys.dm_db_stats_properties(s.object_id, s.stats_id) p
cross apply sys.dm_db_stats_histogram(s.object_id, s.stats_id) h
INNER JOIN sys.stats_columns AS sc
ON s.object_id = sc.object_id AND s.stats_id = sc.stats_id
INNER JOIN sys.columns AS c
ON sc.object_id = c.object_id AND c.column_id = sc.column_id
inner join sys.objects o
on o.object_id = s.object_id
WHERE o.object_id > 100
and p.rows > 1000
and p.modification_counter > 100
order by o.name


text:
Q: Make GameObject "attach" properly? This script makes a cube "stick" to whatever it collided with. The problem is that when it's going at relatively high or medium speeds (or when the device itself is slow), the cube tends to "get a bit inside" what it collided with and then stick to it. What changes do I have to make to fix this?
In order for this script to work, one GameObject must have bool _sticksToObjects = true; and the other bool _sticksToObjects = false;
I have tried turning the Rigidbody's Collision Detection mode to either Continuous or Continuous Dynamic
I think my script depends on frame rate. That may be where the problem lies.
Normal "Attach":

Abnormal "Attach":

Rigidbody _rigidBody;
Transform _meshTransform;
bool _sticksToObjects = true;

public Transform _stuckTo = null;
protected Vector3 _offset = Vector3.zero;

void Awake()
{
    GameObject CubeMesh = GameObject.FindWithTag ("CubeMesh");
    GameObject Cube = GameObject.FindWithTag ("Cube");

    _rigidBody = Cube.GetComponent<Rigidbody> ();
    _meshTransform = CubeMesh.GetComponent<Transform> ();
}

void Update()
{
    if (_stuckTo != null)
    {
        transform.position = _stuckTo.position - _offset;
    }
}

void OnCollisionEnter(Collision collision)
{
        if (!_sticksToObjects) {
            return;
        }

        _rigidBody.isKinematic = true;

        // Get the approximate collision point and normal, as there
        // may be multipled collision points
        Vector3 contactPoint = Vector3.zero;
        Vector3 contactNormal = Vector3.zero;
        for (int i = 0; i < collision.contacts.Length; i++) {
            contactPoint += collision.contacts [i].point;
            contactNormal += collision.contacts [i].normal;
        }

        // Get the final, approximate, point and normal of collision
        contactPoint /= collision.contacts.Length;
        contactNormal /= collision.contacts.Length;

        // Move object to the collision point
        // This acts as setting the pivot point of the cube mesh to the collision point
        transform.position = contactPoint;

        // Adjust the local position of the cube so it is flush with the pivot point
        Vector3 meshLocalPosition = Vector3.zero;

        // Move the child so the side is at the collision point.
        // A x local position of 0 means the child is centered on the parent,
        // a value of 0.5 means it's to the right, and a value of -0.5 means it to the left
        meshLocalPosition.x = (0.5f * contactNormal.x);
        _meshTransform.localPosition = meshLocalPosition;

        if (_stuckTo == null || _stuckTo != collision.gameObject.transform) {
            _offset = collision.gameObject.transform.position - transform.position;
        }

        _stuckTo = collision.gameObject.transform;
    }

Here are some screenshots of the Unity editor:

A: This is a well-known category of problem in game engineering and you'll be pleased to know the solution is relatively simple. You'll be pleased to hear there are similar, but much more complicated, problems that are actually solved in the same way. I'll try to explain.
Now here's the thing. It's quite often that the following question comes up...

So I'm working on GTA. I have a humanoid, H, running around. She approaches vehicle V.  She opens the door and gets in and drives off. After that everything goes to hell in Mecanim and all the code stops working. What to do?

Surprisingly, the way that is done in games is:
Surprisingly: you actually swap to totally different models at that point!!!!!
You have H and V in the game. But then you have an animation (say) for H climbing in to V.  But then, you literally destroy the game objects of H and V, and you Instantiate (or just awake) a new, totally different, game object, which is D ("a car being driven around by a lady").
(If you think about it, you can see that when you do this, you carefully adjust all the stuff in D, so that it matches what was "just then happening" in the frame, in relation to both H and V.  So for example, literally, you copy the transform, twist etc of the car V, to the new car-inside-D, if lady H has the SmearedMakeupEffect, you put the same SmearedMakeupEffect on the lady-within-D, you position all the bones identically, and so on.)
Another simple example of this is, you often get people asking, "my character C gets killed and I want it to become a ragdoll, how to?" In fact you just swap to a totally new game object you have all set up for that passage of the game. Indeed, if you have a character A ("Arnie") in a game, it's normal that you have 4 or 5 "different As" sitting offside the stage, so, there's "ragdoll A", "A who can dance" "A with weapon".  And indeed many of these are combos, you know "A on the horse" "A in the car" and so on.
So interestingly, the "real" solution here is,
once they become a new connected thing, destroy them both and swap to a new game object altogether!
if you have made games "until you are blue in the face" from making games, this is just what you would do as a matter of course. Even though its' a simple situation, it's just easier in the long run.  After all, consider all the stuff you have to do when this happens:

*

*make hitting object child of the other

*turn off physics on the child

*change the way your physics works for the whole thing

*turn off or change the collider on the hitting object, perhaps making it part of the overall object

*you'll likely have some sort of new "separation" physics where it can be knocked-off - you'd have to turn all that on

*likely change minor issues like sound effects, colors etc
As you can see it's a huge chore doing all this stuff, and indeed it's one of those things it's just "easier to do properly" and change to a new model.

All that being said, I know you want a Quick Script Solution you can Paste In :)  Here it is...
Step 0, You'll create "YourScript" which goes on the "main" cube.  it will "catch" another cube moving around.
YourScript will look basically like this ...
   [System.NonSerialized] public bool isConnectedNow;
   void OnCollisionEnter(Collision collision)
      GameObject theThingWeCaught = collision.gameObject
      Debug.Log("We caught this thing .. " + theThingWeCaught.name)
      // make it a child of us......
      theThingWeCaught.transform.parent = transform
      theThingWeCaught ... set kinematic
      theThingWeCaught ... probably disable the rigidbody
      theThingWeCaught ... probably disable the collider
      isConnectedNow = true;

That's really all you have to do.
Step 1, YOUR script must have a public bool like this
 [System.NonSerialized] public bool isConnectedNow;

Step 2, Here's MyScript which goes on the hitting cube, first we'll unit-test that your isConnectedNow bool is working
public Class MyScript:MonoBehaviour // attach to the "child" cube
 {
 public float correctXDistance;
 public float correctYDistance;
 public Transform bigCube;
 public YourScript yourScript;

 void Update()
  {
  string message = yourScript.isConnectedNow ? "free" : "stuck";
  Debug.Log("I am " + message);
  }
 }

attach, debug, and run.   Make the little cube stick and unstick from the big cube .. Watch the console.  it works?  So add this to MyScript
private void DistanceCorrectionX()
 {
 float xDistance = bigCube.position.x - transform.position.x;
 float xSign = Mathf.Sign(xDistance);
 float xDelta = Mathf.Abs(xDistance);
 float closenessPercentage = (xDelta/correctXDistance)*100f;
 if ( closenessPercentage<90f || closenessPercentage>110f)
    {
    // they are not close enough to quantize on this axis
    // this comes in to play when you have multiple axes
    return;  // do nothing.
    }
 float xShouldBe = bigCube.position.x + xSign * correctXDistance;
 Vector3 p = transform;
 p.x = xShouldBe; // be careful it's .y, .z etc for other axes
 transform.position = p;
 }

for now call that in Update() in MyScript like this
 void Update()
  {
  Debug.Log("I am " yourScript.isConnectedNow ? "free" : "stuck");
  if (yourScript.isConnectedNow) DistanceCorrectionX();
  }

Now actually Play and make it stick.  Now, since it's running in Update simply while Play look at the Inspector for MyScript and adjust the value of correctXDistance to get the exact look you want. When yo have decided on a value, unPlay and put that in as the final value you wish.
Next, in DistanceCorrectionX simply duplicate all the code and do it again for the Y axis DistanceCorrectionX.  If you also do Z, do that.
Finally. Note you will have a lot of messy code, like this...
 void Update()
  {
  // handle all the DistanceCorrectionX etc as seen above.

  if (yourScript.isConnectedNow)
      {
      .. turn off the collider on me
      }
  else
      {
      .. turn on the collider on me
      }
  }

and so on, there's "many little things" you'll need to do.
Don't forget also, overwhelmingly you may want to make the hitting object a child of the big object, depending on your situation.  (Then of course they would move around together as a unit.)
Note that in the positioning code above I just showed it as position, not local position, for pedagogic clarity.  If you want to do them flinging around, and spinning and so on, you'd make the hitting object a child of the other and you would use localPosition in the same way.  Enjoy.

A: One possible way that comes to my mind is:
Inside of the "collision enter" check the distance between these objects and move the one that should stick to the other one a bit away.
As you see in the picture the distance between A and B should be equal to the sum of the widths divided by 2 (with a small threshold of course).
If the distance is less than the sum of the widths / 2 then you have an abnormal "attach" and you have to move one of the objects away. Its not really difficult to accomplish that.


text:
Q: How do I get the Android Icons in Android Studio? I'm using Android Studio, and I always see people's drawable calls to things like ic_launcher. I don't have any of these files - hell, where are they even stored? All of my few files begin with abc_ic. How would I go about getting the icons, and where would I put them?

A: You can get the system's drawables by
android:drawable/the_drawable_here on XML and
getResources().getDrawable(android.R.drawable.one_random_drawable,null);

programmatically.

A: abc_ are ActionBarCompat stuff. It's used by ActionBarCompat. For instance, you'll find the overflow icon there (the vertical dots indicating the menu).
Then there is android:drawable/ that contains the system stuff, not always convenient because it varies a lot from a version to another.
Finally, there is https://github.com/google/material-design-icons/ Pretty much all icons ever mentioned in material design are there, in black and white, in all sort of size, and for all densities.

A: The Android asset studio is a great tool for things like this. It will generate icons for all the main DPIs. It can be found here:
https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html


text:
Q: Criteria for a language to be considered "object oriented" I had a discussion about OO programming today and by browsing the internet I found a lot of different specifications for object oriented languages.

*

*What are the requirements for a language to be object oriented? For myself an object oriented language must have classes, inheritance and encapsulation.

*Is C an object oriented language just because you can use structs and program with an object oriented design? Why/ why not?

Are there any good sites/articles about this? And please, no Wikipedia links because I've already been there.

A: OO is usually "defined" in terms of four basic requirements:

*

*Abstraction means you're able to separate an objects externally visible behavior from its implementation.

*Encapsulation means being able to hide the details of the implementation of an object (so closely related to abstraction that some authors treat them as one, leaving only three major requirements).

*Modularity means being able to package abstractions into discrete units.

*Hierarchy is a ranking or ordering of abstractions -- an ability to define the relationship between one abstraction and another.

I, for one, would consider a language object oriented if it supports these four major requirements. Supports, however, goes a bit beyond "allows" or "tolerates".
C, for example, provides enough flexibility that you can simulate each of these reasonably well. C, however, provides only a little support for abstraction or modularity, and none at all for encapsulation or hierarchy -- you can do these things if you want to badly enough, but the language doesn't really provide any direct support for them.
C++, for an obvious comparison does provide direct support for each of these requirements. Just for example, encapsulation is directly supported by making class members private and/or protected and hierarchies are supported via class inheritance.
That's still not what would normally be called a "pure" object oriented language though. In a pure OO language (e.g., Smalltalk), you not only get support for hierarchy, but you get a pre-defined hierarchy of types, and you have to define the relationship of any new type to some existing type in that hierarchy (i.e., all your code most be in classes, and each class must derive from some existing one).
Although classes and inheritance are both common to many implementations of object orientation, neither is really necessary to it. Just for example, Self and JavaScript both use exemplar-based hierarchies. Instead of a hierarchy of classes, with each object an instance of a class, these just use a hierarchy of objects, with each based on some other object, but modified to some arbitrary degree.

A: According to Rumbaugh et al., "Object-Oriented Modelling and Design", objects
are characterized by the following features:

*

*Identity: data is quantized into discrete, distinguishable entities, called objects.

*Classification: objects with the same structure and behaviour are grouped together to form classes.

*Polymorphism: the same operation (an operation with the same name) may behave differently on different classes.

*Inheritance: sharing of attributes and operations among classes based on a hierarchical relationship.

According to this definition, an OO-language should support these concepts natively. In C you can define struct's which share structure, but not behaviour (structure classification without behaviour classification). You can define identity by means of handles to data objects (pointers). Polymorphism and inheritance are missing altogether and must be implemented through ad-hoc techniques.
So, according to these criteria, C is not an object-oriented language. Using some ad-hoc techniques you can implemented and object-oriented design in C, but C does not have enough concepts to support it directly.

A: The only realistic requirement for a language to be OOP is that it's possible to expend at least a good proportion of the time actually dealing with OOP instead of hacking around it's deficiencies. Something like  e.g. C is hardly great, but it's usable. If you're desperate.
Which programming languages are purest OOP? Which denominations are the purest Christians? There's no way you could possibly get a correct or objective answer to that question- there's not even any useful definition of "pure". And secondly, even if you could pick the language which had no other non-OOP features and was "pure" in the scientific definition, i.e., only of one thing, then it would be a terrible language. OOP is not some wonder-child, it's not good for everything by miles, and only offering OOP sends a language right down the pile of awful.

A: Liskov substitution principle is pretty much the defn of Object Orientated.
Although in practice encapsulation and data hiding are probably more useful

A: It's hard to tell what it means for a language to be object-oriented. Actually, it's hard to tell what it means for a language to be X, where X can be OO, FP, anything.
The official definition of Object-Orientation is

*

*messaging,

*local retention and protection and hiding of state-process, and

*extreme late-binding of all things

But note that this describes properties of a program, not a language.
Personally, I would say that a language is object-oriented if it facilitates and encourages building programs that satisfy the above definition. Saying that a language is OO if it allows that, is pointless: every Turing-complete language allows everything. The question is: how easy is it to use?
C certainly allows functional programming. And object oriented programming. And logic programming. But none of these is easy in C, nor does C facilitate or encourage programming in those styles.
Also, note that the above definition doesn't mention anything about classes. Why would it? After all, it's called OOP, not COP. In fact, it doesn't even mention objects! Alan Kay himself says that he regrets calling it object-oriented, and that he should rather have called it message-oriented instead, since the important thing are messages, not objects (and certainly not classes).

A: Many years ago I read about this topic in a JavaScript book, I cannot remember which one it is. But I can still remember the discussion about whether JavaScript should be considered as an OOP language, the author's answer is yes, coz it meets the four criteria for a language to be object oriented:

*

*Encapsulation, which allows you to combine data and procedures that
operates the data together.

*Inheritance (pretty simple, someone has explained above)

*Polymorphism (someone has explained above)

*Composition, which allows you to define an object of a class as another
class's member data.


text:
Q: SQLException deleting row from JTable and database I want to delete selcetd row in a JTable from both the table itself and the database.
That is my code:
Object number =  jTable1.getValueAt(selectedRow-1, 0);
                String sql = "delete  from orders where number ="+number;
                Statement st = conn.createStatement();
                rs = null;
                rs = st.executeQuery(sql);

When the excuteQuery() runs I get the following exception:
(java.sql.SQLException) java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

What am I doing wrong?

A: It is not an Abnormal Exception.
You need to call executeUpdate instead of executeQuery. You cannot update database by calling executeQuery method. To update something in database (insert, update, delete) you need to call executeUpdate method and it will not return the ResultSet and instead return you an int value.
int result = st.executeUpdate(sql);
More Info


text:
Q: what's the meaning of "entwining" in this sentence? The entwining of advocacy for services combined with the high levels of emotional support required for women to embark on the difficult pathway to recovery is changing – and not always for the best.

A: entwine - tie or link together


text:
Q: How to export question- answers to PDF/DOC There are many questions which have replies running to more than 1 page
is it possible to export all the answers to PDF?

A: I guess it's true that we don't provide any view of a question that actually shows more than 30 answers, is it?
Even the RSS feed for a question is limited to 30 answers.


text:
Q: Sorting arrays of intervals in perl? I have an array in perl with some intervals like:

@array = qw(1-5 7-9 10-15 20-58 123-192 234-256)

I am trying to order it using sort but this is what I obtain:

1-5  ,  10-15 , 123-192 , 20-58 , 234-256 , 7-9

It is sorted by the first character of the first number... How can be ordered by the whole first number in order to obtain the next array?

1-5 , 7-9 , 10-15 , 20-58 , 123-192  , 234-256

Thank you very much!
P.S.
I have no code for this, I am trying the command
my @sorted = sort @array;

A: What you want to do is sort numerically. To do that, you need to override the default sort method by supplying your own method. This code:
my @sorted = sort @array;

really means this:
my @sorted = sort { $a cmp $b } @array;

Where cmp is the lexicographical comparison operator (sorts in alphabetic order, more or less). You want to use the <=>, often called "the spaceship operator".
my @sorted = sort { $a <=> $b } @array;

But this operator can only be used with numbers, and a string such as 7-9 is not really a number (although in this case it will work, albeit with warnings issued Argument "7-9" isn't numeric in sort).
To overcome this warning, and possible bug, we need to extract the numbers from the strings we want to sort. We do this with a regex match: /\d+/g. This will match and return all consecutive numbers in the string.
my @sorted = sort {
                     my ($a1, $a2) = $a =~ /\d+/g;
                     my ($b1, $b2) = $b =~ /\d+/g;
                     $a1 <=> $b1 || $a2 <=> $b2;
} @array;

We capture and use both low and high range, and at the end we perform both checks. This means that in the case that $a1 and $b1 are equal, <=> returns 0, and the || operator executes the alternate comparison, $a2 <=> $b2.
In some cases, this operation is expensive, it takes time, and with a large data set it will cause the sort to become very slow. In this case, we can cache the data using what is known as a Schwartzian transform. In this method, we simply store the value of our regex match and use the stored value when sorting. To do this, we use a anonymous array ref [ ... ]. At the end we restore the original value and discard the cache:
my @sorted = map  { $_->[0] }                # restore original
             sort { $a->[1] <=> $b->[1] }    # sort compares stored nums
             map  { [ $_, /\d+/g ] }         # store original, and nums
             @array;

If you want more than one sort level, you just add $a->[2] <=> $b->[2] and so on.

A: You need to extract first number for every element, and do numerical comparison using <=> operator,
my @array = qw(1-5 7-9 10-15 20-58 123-192 234-256);
my @sorted = sort {
  my ($aa,$bb) = map /^([0-9]+)/, $a,$b;

  $aa <=> $bb;
} @array;


text:
Q: Why the keyCode event for escape alone not working? $(document).keypress(function(e)
{
  alert(e.keyCode);
  if(e.keyCode==27)
  {
    hide_menu();
  }
});

I get the alert for all keys except the escape key and the success part of the if is never getting called. Why this happens?

A: use $(document).keyup instead of $(document).keypress
the following code works fine:
$(document).keyup(function(e)
{
  alert(e.keyCode);

  if(e.keyCode==27)
  {
      alert ("Esc key");
      hide_menu();
  }
});

A: You can change the keypress to keyup(better to use keyup) or keydown:
$(document).keyup(function(e){
    alert(e.keyCode);
    if(e.keyCode==27){
       hide_menu();
    }
});