text:
Q: Cant Load JavaScript Files Into Django App I have a Django app that uses both JavaScript Files + CSS.
While the css files perfectly loads, all of the the Java Script don't.
CSS file Location:
 C:\Users\user\Desktop\Django project\general\adray\static\adray\assets

JavaScript files location (Yes i checked, java script files are really there):
 C:\Users\user\Desktop\Django project\general\adray\static\adray\js

Here is base.html load stuff:
{% load staticfiles %}

<link rel="stylesheet" type="text/css" href="{% static 'adray/assets/custom.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'adray/assets/bootstrap.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'adray/assets/font-awesome.css' %}" />

  <script type="text/javascript" src=" {% static 'static/adray/js/jquery-1.10.2.js' %}"></script>
 <script type="text/javascript" src=" {% static 'adray/js/bootstrap.min.js' %}"></script>
  <script type="text/javascript" src=" {% static 'adray/morris/raphael-2.1.0.min.js' %}"></script>
   <script type="text/javascript" src=" {% static 'adray/js/custom.js' %}"></script>
   <script type="text/javascript" src=" {% static 'adray/js/jquery.metisMenu.js' %}"></script>

<!DOCTYPE html> ......

And Server Log (all JavaScript Get requests return 404):
    C:\Users\user\Desktop\Django project\general>python manage.py r
unserver
Performing system checks...

System check identified no issues (0 silenced).
August 13, 2015 - 14:55:26
Django version 1.8.2, using settings 'general.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[13/Aug/2015 15:04:26]"GET / HTTP/1.1" 200 10215
[13/Aug/2015 15:04:26]"GET /%7B%20%%20static%20'adray/js/bootstrap.min.js'%20%%2
0%7D HTTP/1.1" 404 2706
[13/Aug/2015 15:04:26]"GET /%7B%20%%20static%20'adray/js/jquery-1.10.2.js'%20%%2
0%7D HTTP/1.1" 404 2706
[13/Aug/2015 15:04:26]"GET /static/adray/assets/custom.css HTTP/1.1" 304 0
[13/Aug/2015 15:04:26]"GET /%7B%20%%20static%20'adray/morris/raphael-2.1.0.min.j
s'%20%%20%7D HTTP/1.1" 404 2730
[13/Aug/2015 15:04:26]"GET /static/adray/assets/bootstrap.css HTTP/1.1" 304 0
[13/Aug/2015 15:04:26]"GET /static/adray/assets/font-awesome.css HTTP/1.1" 304 0

[13/Aug/2015 15:04:26]"GET /%7B%20%%20static%20'adray/js/custom.js'%20%%20%7D HT
TP/1.1" 404 2685

Settings.py:
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = ***********************

DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'adray',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'general.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'general.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

TEMPLATE_DIRS = (
    'C:/Users/user/Desktop/Django project/general/adray/Templates',
)
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = "C:/Users/user/Desktop/Django project/general/adray/static"

FIXTURE_DIRS = (
   'C:/Users/user/Desktop/Django project/general/path/to/adray/fixtures/',
)

i also  ran:
C:\Users\user\Desktop\Django project\general>python manage.py collectstatic

Any idea on whats going on?
Thanks in advance!

A: Your template tags are not recognized properly because they contain spaces:
{ % static 'adray/js/jquery.metisMenu.js' % }

should be:
{% static 'adray/js/jquery.metisMenu.js' %}


text:
Q: Symmetric Part of Product of 2 tank 2 tensors Let $A_{ab}$ be a rank 2 tensor. Let $P_{abcd} = A_{ab}A_{cd}$. What are the symmetric and antisymmetric parts of $P_{abcd}$? Is it even possible to define symmetric and antisymmetric parts? (All indices range from 1 to 3).
I was thinking to use a similar definition as matrices and say that the symmetric part is $1/2(P + P^T)$ where $P^T$ is $P$ transpose. The transpose of $P_{abcd}$ could be defined as $A_{cd}^TA_{ab}^T = P_{dcba}$, per the rule governing the transpose of a product of matrices, but I don't know if that would apply here considering that$ P_{abcd} $is not a matrix but a 4 tensor. Then the antisymmetric part could be $1/2(P - P^T)$. But I don't know how to rigorously prove these are the symmetric and antisymmetric parts. I would appreciate some guidance on whether or not it is possible to define symmetric and antisymmetric parts of $P_{abcd}$ in this case, and if so then If my form for the symmetric and antisymmetric parts is correct and how to go about proving a different form/my form correct.

A: Symmetrization and antisymmetrization operations are well-defined for arbitrary tensors. To symmetrize $P_{abcd}$ one would sum over all $24=4!$ permutations of the symbols $a,b,c,d$ and divide by $24$. In this case
$$
P_{(abcd)}=\frac{1}{24}\times \Bigl[(A_{ab}+A_{ba})(A_{cd}+A_{dc})+(A_{ac}+A_{ca})(A_{bd}+A_{db})\Bigr.
$$
$$
+(A_{ad}+A_{da})(A_{bc}+A_{cb})+(A_{bc}+A_{cb})(A_{ad}+A_{da})
$$
$$
\Bigl.+(A_{bd}+A_{db})(A_{ac}+A_{ca})+(A_{cd}+A_{dc})(A_{ab}+A_{ba})\Bigr].
$$
Similarly for the antisymmetrization, except now the sign of the permutation applies:
$$
P_{[abcd]}=\frac{1}{24}\times \Bigl[(A_{ab}-A_{ba})(A_{cd}-A_{dc})-(A_{ac}-A_{ca})(A_{bd}-A_{db})\Bigr.
$$
$$
+(A_{ad}-A_{da})(A_{bc}-A_{cb})+(A_{bc}-A_{cb})(A_{ad}-A_{da})
$$
$$
\Bigl.-(A_{bd}-A_{db})(A_{ac}-A_{ca})+(A_{cd}-A_{dc})(A_{ab}-A_{ba})\Bigr].
$$
A few comments aimed at (what I guess is) the spirit of the question you are asking, and not the literal question itself.
One thing to note here is that, unlike in the rank 2 case, not all tensors are equal to the sum of their symmetrization and their antisymmetrization. The reason for this is due to group theory. Specifically, the rank 2 case is governed by the action of the symmetric group on 2 elements, which has only 2 characters: the identity (corresponding to symmetrization) and the alternating character (corresponding to antisymmetrization). But in the rank 4 case, one would need to sum over all characters of the symmetric group on 4 elements, resulting in more tensors in the symmetric/antisymmetric decomposition.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a HttpClient in Xamarin Forms in iOS I have an ASP.Net Core API that is running.
I have a Xamarin Forms solution and in the main project and I have this class:
public class GetSettings
{

    public static async Task<SettingResponse> GetSetting()
    {
        SettingResponse setting = new SettingResponse();

        var url = new Uri(string.Format(GetUrl.GenerateURL("GetSetting"), string.Empty));

        var client = new HttpClient();

        var response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            var result = response.Content.ReadAsStringAsync().Result;

            setting = JsonConvert.DeserializeObject<SettingResponse>(result);
        }
        else
        {
            setting = null;
        }

        return setting;
    }
}

In the Android and iOS project I have this two lines:
SettingResponse setting = new SettingResponse();

setting = await GetSettings.GetSetting();

In the Android project there is no problem and it works fine, but in the iOS project when getting to new HttpClient(); nothing happens and app does nothing.

A: Check if you have the NSAllowsArbitraryLoads key to YES in NSAppTransportSecurity dictionary in your info.plist file.
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>


text:
Q: $(2,p)$ generation of alternating group $A_p$ Let $p>7$ be a prime, $a=(1,2,3,...,p)$, $b$ is the product of two arbitrary transpositions such as $b=(2,6)(3,5)$. I found that when $p=11,13,17,19$, the group $\langle a,b \rangle$ is always $A_p$ (use Magma), I want to know whether it is right for all prime numbers $p$. I tried the Jordan's theorem but can't find a short cycle for all situations. Can you prove it or find a counterexample for it?
Thanks a lot for any help!

A: The subgroup $\langle a \rangle$ of $G := \langle a,b \rangle$ is not normal in $G$, so $G$ is not solvable, and hence is doubly transitive by Burnside's Theorem.
Now by Theorem 5.4A of Dixon & Mortimer's book on Permutation Groups, if $G \ne A_p$, then the minimal degree of $G$ (i.e the smallest number of moved points of a non-identity element) is at least $\sqrt{p}$, which is greater than $4$ for $p\ge17$. So $G=A_p$.
The result about minimal degrees of 2-transitive groups is due to Jordan (1871).


text:
Q: UI to call Google Apps Script function from Gmail? I have a function (and supporting functions) that reads from my Gmail account, parses the contents of the mails to find PayPal payment information, and write that information to a Google spreadsheet. It works perfectly. What I don't know is how the user can invoke this function. Gmail lacks an Add-ons menu or an object model to program against it. So how can my Gmail users invoke the function?

A: If the script is attached to a spreadsheet then they can just run it from that. Otherwise, you can deploy it as a web app and have an interface separate from Gmail. You can embed it into a Google Site as well.
I have a script that gets each message (not conversation) from a specified timeframe and writes the received date, sender, recipient, message title into a spreadsheet. The user calls this script from a web interface. To allow for extra information (such as instructions and hidden documentation for future maintainers) I embed it into a Google Site. I did that because the script creates new spreadsheets each time, so if it's the same on your end, that's what I would recommend doing.
You can create an HTML file in the script editor and use
function doGet(e) {
  var htmlPage = HtmlService.createHtmlOutputFromFile('Index.html')
  return htmlPage
}

to display have the web page displayed.

A: You can write a custom spreadsheet function and invoke it manually by typing the function name in a spreadsheet cell. This works on both desktops and mobiles.
For instance, if the code is:
function getTransaction() {
  // Your code here
}

You can go to the spreadsheet, and enter =getTransaction() in the cell to execute the function.


text:
Q: Permission problems (access denied) when listing all user profile images We have a webapp http://intranet01 (default zone) with an internal zone AAM http://intranet and a public zone http://intranet.company.com. Everyting works fine except one solution.
The solution contains a web part which lists all user profile images and names. It works for some users, but not for others. When it doesn't work, the user is requested to log in over and over again (for as many times as there are images on the page). The server is returning a 401 (access denied) for each image.
On the page where the web part is deployed, the images are referenced to as http://intranet01/my/profile/.../image.png. If I copy this link and open it in the browser, I can see the profile picture in question. However, if I try to access http://intranet.company.com/my/profile/.../image.png in the browser, I get an access denied and can't see the image.
As mentioned, the images are referenced as http://intranet01/my/profile/.../image.png. In  a test env. the same images are referenced as /my/profile/.../image.png (i.e. server relative). Why the images aren't referenced server relative on the env. in question is beyond me.
It doesn't matter if I browse the site with intranet01, intranet or intranet.company.com - I still get access denied on the page in question.
It should not be an issue with the page or the user, as the page is published and I myself am a site collection admin and still get access denied, while others whom are normal users can access the page (and images - and yes, they can see the images). It seems like this is not consistent though, as normal users also can get an access denied.
We use claims based authentication. We have uploaded all the images using PowerShell, and run the command Update-SPProfilePhotoStore after completion (with the mysitelocation url parameter of intranet.company.com).
Edit to add: If I access the intranet with http://intranet01 I only get access denied two times because two of the images are linking to http://intranet.company.com/my/..., while the others are linking to http://intranet01/my/... And if I access with intranet.company.com, the two same images are working, while all the others are not.

A: This is usually a browser setting issue.
Your browser needs to have both Intranet URL (eg. http://intranet) and My Site host url (eg. http://my.intranet) to intranet zone.
You can also opt for Trusted Zone, but then you also need to specify "Automatic logon with current user name and password" in Custom Level > User Authentication
These settings can be rolled out as a Group Policy to all your users browsers

A: This issue was resolved by a colleague. The steps to resolve this was to

*

*Change the user profile app to point to http://intranet.company.com instead of http://intranet01.

*Change the default AAM zone to http://intranet.company.com (intranet AAM zone is still http://intranet and added a custom AAM zone as http://intranet01)

*Made a script that changed the url of all user profile pictures to http://intranet.company.com/my/... instead of http://intranet01/my/...


text:
Q: Add and read a json file in the iPhone app I have created a simple Xcode 4.2 project with a empty view controller.
I added a json file to this project (i not had a resouces folder/group and so i
have create these resouces folder and group).
So, in my iphone simulator i can read this json file correctly.
When i have tested my example app on my device I had a error: i can't read the
json file: Why?
I use this simple code lines:
NSString *filePath = [[NSBundle mainBundle] pathForResource:CONFIGURATION_FILE_NAME ofType:CONFIGURATION_FILE_TYEPE];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: NULL];

A: I have solved...
in my code the CONFIGURATION_FILE_TYEPE is a define @"JSON"..
i have changed this with @"json".. this work well on device and simulator!


text:
Q: error when Redirecting user to someone profile in other model I want to redirected user to the profile page in the question model, I want when user click on url in the username of the question model, I want that url to redirected user to the author of that question to his/her public_profile page like facebook you can visit someone profile by clicking on his name when he/she post something, I have try using this method but it throws me an error: Reverse for 'Public_Profile' with arguments '('',)' not found. 1 pattern(s) tried: ['userProfile/(?P[-a-zA-Z0-9_]+)/\Z']
this is what i have try:
my urls:
urlpatterns = [
    path('', views.rules, name='Rules'),
    path('create', views.login, name='login'),
    path('index/', views.index, name='index'),
    path('view/<slug:slug>/', views.viewQuestion, name='view-Question'),
    path('question/<int:pk>/answer/', views.My_Answer.as_view(), name='answer'),
    path('question/', views.My_Question.as_view(), name='question'),
    path('register/', views.register, name='register'),
    path('feedback/', views.PostFeedBack.as_view(), name='FeedBack'),
    path('notification/', views.NotificationListView.as_view(), name='notification'),
    path('profile/<int:pk>/', views.profile, name='Profile'),
    path('edit/<slug:slug>/', views.EditProfile.as_view(), name='edit'),
    path('userProfile/<slug:slug>/', views.public_profile, name='Public_Profile'),
]

my index/home template:

        {% for question in list_of_question reversed %}

                    {{question.user.username.upper}}

{{question.title}}

{{question.category}}

        {%endfor%}

my views:
@login_required(login_url='login')
def index(request):
    query = request.GET.get('q', None)
    list_of_question = Question.objects.all()
    if query is not None:
        list_of_question = Question.objects.filter(
            Q(title__icontains=query) |
            Q(category__name__icontains=query)
        )
    unread_notifications =
    Notification.objects.filter(user=request.user,
    is_read=False).count()

    paginator = Paginator(list_of_question, per_page=15)
    context = [
        {
             'unread_notifications':unread_notifications,
             'list_of_question':list_of_question,
             'paginator':paginator
       }
    ]
    return render(request, 'index.html', context)

def profile(request, pk):
    profiles = Profile.objects.filter(user=request.user)
    questions = Question.objects.filter(user=request.user)
    context = {
        'profiles':profiles,
        'questions':questions
    }
    return render(request, 'profile.html', context)

def public_profile(request, slug):
    contents = get_object_or_404(Profile, slug=slug)
    profiles = Profile.objects.filter(user=contents)
    context = {
        'contents':contents,
        'profiles':profiles
    }
    return render(request, 'public_profile.html', context)

my model
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_image = models.ImageField(upload_to='avatar', blank=True, null=True,
    default='static/default.jpg')
    stories = RichTextField(blank=True, null=True)
    twitter = models.URLField(max_length=300, blank=True, null=True)
    website = models.URLField(max_length=300,blank=True, null=True)
    city = models.CharField(max_length=50, blank=True, null=True)
    location = models.CharField(max_length=80, blank=True, null=True)
    slug = models.SlugField(unique=True, max_length=200)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.user)
        super(Profile, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.user)

class Question(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False)
    body = RichTextField(blank=False, null=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, max_length=200)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Question, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.title)

A: In template

   {{question.user.username.upper}}

Views:
def profile(request, pk):
    profiles = Profile.objects.get(user=pk)
    questions = Question.objects.filter(user=pk)
    context = {
        'profiles':profiles,
        'questions':questions
    }
    return render(request, 'profile.html', context)

A: The error is trying to tell you that django tried to call Public_Profile but it requires some slug. This is because profile is None in the template context. You need to change  with

A: You should change profile.slug into question.user.profile.slug
Try this in your template:

        {% for question in list_of_question reversed %}

                    {{question.user.username.upper}}

{{question.title}}

{{question.category}}

        {%endfor%}


text:
Q: POSIX sigevent not compiling with c11 I have simple app in C that is using POSIX struct sigevent.
#include <signal.h>

int main(int argc, char *argv[])
{
    struct sigevent sig_event;

    return 0;
}

When I compile it like this:
gcc test.c

it is fine. When I force C11 mode, it fails:
gcc test.c --std=c11

test.c: In function 'main':
test.c:5:21: error: storage size of 'sig_event' isn't known
    struct sigevent sig_event;

I'm using gcc 5.2.1 on Ubuntu 15.10. Any ideas what is causing those errors? This problem first occured when I tried to compile example from manual for timer_create() function. Situation was the same, except for much more errors.

A: The header <signal.h> is part of standard C. But POSIX adds more to it. Since struct sigevent is not C but in POSIX -std=c11 disables (probably an ifdef somewhere) it.
gcc test.c

works because gcc by default enables certain level of POSIX functions and a lot GNU extensions.
Compile it with:
gcc -std=c11 -D_POSIX_C_SOURCE=200809 file.c

A: This is because posix symbol is not part of C standard. This can be solved in various ways,

*

*gcc -std=c11 -D_XOPEN_SOURCE=700 file.c

*gcc -std=c11 -D_GNU_SOURCE file.c

*gcc -std=gnu11 file.c
Here 700 means X Open7 Posix 2008.


text:
Q: Keep max 20 items in S3 using cloud formations I'm creating an S3Bucket using cloud formations. I want to keep max 20 items in S3. If the 21th appears, the oldest one can be deleted from the bucket.
How can I configure this in S3?
I found some info here. But this only tells me how to keep my items a certain timeframe instead of amount?
xxxS3Bucket:
  Type: AWS::S3::Bucket
  DeletionPolicy: Retain
  Properties:
    AccessControl: Private
    BucketName: !Join [ "-", [!Ref ProjectName, "app", !Ref Environment ] ]
    LifecycleConfiguration
      Rules:
        -

A: I would put an s3 event notification on the bucket that calls a Lambda function each time there is a new PUT to that bucket.
The Lambda function would then do the work of looking at what's in the bucket and if it finds there are more than 20, delete the oldest.
https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html


text:
Q: What is the status of the Infinity Stones post Avengers: Endgame? In Avengers: Endgame, the heroes travel back in time to "borrow" the Infinity Stones from the past to use them in the future.
I get that. At the end of the movie,

 Captain America travels back to return the Infinity Stones to their various points in time to merge the two timelines (I think).

But because the movie has gone for an alt-timeline mutliverse version of time travel, it's not a problem. It just means that there's now an alternative timeline kicking off in 2014 in which Nebula and Thanos don't exist. That timeline doesn't have a snap. But that doesn't mean that the MCU timeline - the one we've been watching for the last 11 years - is changed at all. Because changing the past doesn't alter the future, remember - killing baby Thanos wouldn't change a thing in the current timeline, as they point out, and that also means that killing Thanos 2014 equally has not affect on the current continuity.
DenofGeek

But, if the timelines are reset and the snap still happened and the early events of Avengers: Endgame (before the "5 years later") then aren't the Stones now destroyed in the ongoing timeline?
Specifically, what happened to the Time Stone? Surely Doctor Strange would be concerned about losing it.
(or is the last point opinion based?)

A: The status of the Infinity Stones in my mind is quite simple, the ones from the past are back in the past returned as they were taken so that the timeline doesn't spawn alternate timelines as explained by The Ancient One. The ones in the future are still destroyed as Thanos had destroyed them, assuming he wasn't lying of course, which I don't think he was considering past Thanos' comments about it.

It just means that there's now an alternative timeline kicking off in 2014 in which Nebula and Thanos don't exist.

FWIW I think this statement in the article is wrong, there is no alternative timeline starting in 2014 because the Infinity Stones were placed back where they came from.
As for whether Doctor Strange would be concerned about losing the Time Stone, probably not really. He is concerned about keeping the universe alive and losing the Time Stone is a small price to pay for that.

A: The Russo's have confirmed the infinity stones are not destroyed at all. Thanos just reduces them to atoms but they still exist in the MCU
https://www.google.com/amp/s/screenrant.com/avengers-endgame-director-russos-infinity-stones-still-exist/amp/

A: NOTE: this answer is totally wrong! The Russo brothers have confirmed that alternate realities are created without removing Infinity Stones from the timeline.

It just means that there's now an alternative timeline kicking off in 2014 in which Nebula and Thanos don't exist.

Just like in the movie itself, people love to confidently state how time travel works, despite the fact that it's an entirely fictional concept, and thus works exactly how the authors of any story decide it works, regardless of your own conception of temporal logic.
The movie goes to considerable effort to explain its time travel rules, including the alternative timeline question. The Ancient One even draws us a picture. Here's what she tells us:

*

*The Infinity Stones (as a whole) are responsible for creating the flow of time in the universe.

*If you remove an Infinity Stone from the timeline via time travel, an alternative reality will be created, without that stone in it. This would be bad for that reality.

*By implication, aside from that, time travel does not create ongoing alternate realities, yet does not affect the past, or the present.

So, after Cap returns the Infinity Stones to their original places in the timeline, everything is fine, and still happens in the way we saw it happen. Thus the Infinity Stones are eventually used to destroy themselves in Thanos' garden. (For some reason, this is presumably fine for the universe, even though the stones are apparently responsible for creating its flow of time.)
I'm not saying it makes sense! I'm just saying this is how the movie tells us it works.


text:
Q: Solr 6.6.6 Collection Restore causing problems from single node I have 2 nodes SolrCloud setup. Version is 6.6.6. I have taken Solr backup from other instance where there are 4 collection shards.
I have used following command to take back that works fine
http://10.11.31.11:8983/solr/admin/collections?action=BACKUP&name=hms&collection=collection1&location=/tmp/solr_backup&async=1001

After this I copied backup to one node of Solr Cloud and executed following command to restore.
http://10.11.31.12:8983/solr/admin/collections?action=RESTORE&name=hms&location=/home/hduser/Documents/search/data&collection=newCollection&maxShardsPerNode=4&replicationFactor=2&autoAddReplicas=true

I got following exception when executed above command
<response><lst name="responseHeader"><int name="status">500</int><int name="QTime">60</int></lst><str name="Operation restore caused exception:">org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: Couldn't restore since doesn't exist: file:///home/user12/Documents/search/data/hms</str><lst name="exception"><str name="msg">Couldn't restore since doesn't exist: file:///home/user12/Documents/search/data/hms</str><int name="rspCode">500</int></lst><lst name="error"><lst name="metadata"><str name="error-class">org.apache.solr.common.SolrException</str><str name="root-error-class">org.apache.solr.common.SolrException</str></lst><str name="msg">Couldn't restore since doesn't exist: file:///home/user12/Documents/search/data/hms</str><str name="trace">org.apache.solr.common.SolrException: Couldn't restore since doesn't exist: file:///home/user12/Documents/search/data/hms
    at org.apache.solr.handler.admin.CollectionsHandler.handleResponse(CollectionsHandler.java:300)
    at org.apache.solr.handler.admin.CollectionsHandler.invokeAction(CollectionsHandler.java:237)
    at org.apache.solr.handler.admin.CollectionsHandler.handleRequestBody(CollectionsHandler.java:215)
    at org.apache.solr.handler.RequestHandlerBase.handleRequest(RequestHandlerBase.java:173)
    at org.apache.solr.servlet.HttpSolrCall.handleAdmin(HttpSolrCall.java:749)
    at org.apache.solr.servlet.HttpSolrCall.handleAdminRequest(HttpSolrCall.java:730)
    at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:510)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:361)
    at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:305)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1691)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
    at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:119)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.rewrite.handler.RewriteHandler.handle(RewriteHandler.java:335)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
    at org.eclipse.jetty.server.Server.handle(Server.java:534)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
    at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
    at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
    at java.lang.Thread.run(Thread.java:748)
</str><int name="code">500</int></lst></response>

Then I copied the backup data to second node also with exactly same path as on first node and re-executed the restore command. The job was successful.
Does it mean for every backup, it is necessary to copy backup on all nodes of Solr with exactly same path or it is a bug ?
I was expecting that Solr should allow to restore collection from single node and then it should replicate shards on its own ? isn't it ?

A: The directory you're restoring from has to be available on all the servers at the same path. The path is assumed to be a network share available in a common location on the servers.

location
The location on the shared drive for the restore command to read from.

From the example in the documentation given above:
..&name=myBackupName&location=/path/to/my/shared/drive&...


text:
Q: react-css-modules & karma without ExtractTextPlugin I have react-css-modules working on my app with webpack which generates a compiled .css file using ExtractTextPlugin which I serve up.  Everything works fine but I'm stuck on how to get it work with karma/jasmine?
I keep getting CSS Module is undefined when this error doesn't occuer when building on webpack.
This is my karma config, the only difference is that I dont use ExtractTextPlugin
ie for test: /(((activityFeed|fonts)\.css)|(grids-core\.css)|(grids-responsive\.css))$/ I have loader: ['style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]']
var webpackConfigModified = {
  devtool: 'inline-source-map',
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          loose: ['all'],
          modules: 'commonStrict',
          optional: ['runtime', 'minification.propertyLiterals']
        }
      },
      {
        test: /(\.css)$/,
        exclude: ['./node_modules/purecss/build', './app/client/main/stylesheets'],
        loader: 'style!css'
      },
      {
        test: /(((activityFeed|fonts)\.css)|(grids-core\.css)|(grids-responsive\.css))$/,
        include: ['./node_modules/purecss/build', './app/client/main/stylesheets'],
        loader: ['style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]']
      },
      {
        test: /underscore(?:-min)?\.js$/,
        loader: 'expose?underscore'
      },
      {
        test: require.resolve('lodash'),
        loader: 'expose?lodash'
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      }
    ],
    noParse: []
  },
  plugins: [],
  externals: {
    jsdom: 'window',
    cheerio: 'window',
    'react/lib/ExecutionEnvironment': true,
    'react/lib/ReactContext': 'window',
    'text-encoding': 'window'
  },
  resolve: {
    extensions: ['', '.js', '.json', '.css', '.scss'],
    alias: {
      'purecss/build/grids-responsive.css': path.resolve('./node_modules', 'purecss/build/grids-responsive.css'),
      'purecss/build/grids-core.css': path.resolve('./node_modules', 'purecss/build/grids-core.css')
    },
    fallback: path.resolve('./app/client/'),
  }
};

  config.set({
    basePath: '',
    frameworks: ['jasmine-ajax', 'jasmine'],
    files: [
      { pattern: 'app/client/spec/**/*.spec.js', watched: true, served: true, included: true },
    ],
    preprocessors: {
      './app/client/spec/**/*.spec.js': ['webpack']
    },
    exclude: [
    ],
    webpack: webpackConfigModified,
    webpackServer: {
      noInfo: true,
      stats: 'errors-only'
    },
    plugins: [
      'karma-*'
    ],
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    autoWatchBatchDelay: 800,
    browsers: ['Chrome', 'Firefox'],
    singleRun: false
  });


text:
Q: Setting Objects Table IndexPath to Object Attributes? I want to save the index paths my objects are in within a tableview as an attribute in core data.
This is so the user can rearrange them as they please and I can save the positions and reload them in different views in that order.
Im not sure where i should be making this save, as you cant access table index paths externally to table functions?
Currently I am using
for uniqueUserExercise in queryResults {
  uniqueUserExercise.arrayPosition = ??
}

where let queryResults = try self.managedObjectContext.fetch(request)
and uniqueUserExercise is an exercise object in the array of query results
where ?? would be the way to find out the indexpath of each item in the tableview
Any ideas how I can achieve this? the result for example would be, whatever object is sat at indexpath 3 having a 2 saved, the one at 5 having a 4 saved (as obviously they start from 0)
Im just not sure how to access this data in an external function to the usual row setup stuff?
Appreciate any support in this

A: UITableViewDataSource has two methods that support the reordering of rows: tableView(:canMoveRowAt:) and tableView(:moveRowAt:to:). If you read the notes at the beginning of UITableView, you can find out when each of those methods is called -- at events like inserting, deleting or dragging. You can then use the information those methods provide you with to update the "myIndex" attribute of the NSManagedObject concerned.


text:
Q: How to convert a string date format `October 18th 2019` into a valid date `2019-10-17T23:00:00.000Z` I need to convert a string date format like this October 18th 2019 ('MMMM Do YYYY') into a valid date 2019-10-17T23:00:00.000Z or similar 17/10/2019
i have tried using parsing the string into moment but i keep getting errors
update: I used moment('October 18th 2019').format(). received invalid date as the error, sorry I should clarify i'm trying to convert the string October 18th 2019 into a valid date format,

A: You simply need to supply the format string for the input (MMMM Do YYYY) when constructing the Moment object, with one of the following approaches:
// this way interprets the input at the start of the day in the local time zone
moment('October 18th 2019', 'MMMM Do YYYY')

// this way interprets the input at the start of the day in UTC
moment.utc('October 18th 2019', 'MMMM Do YYYY')

// this way interprets the input at the start of the day in a specific named time zone
// (requires the moment-timezone add-on)
moment.tz('October 18th 2019', 'MMMM Do YYYY', 'Europe/London')

Then you can format and/or convert it however desired.  For example:
// this way keeps the local time, includes the local time offset when formatting
moment('October 18th 2019', 'MMMM Do YYYY').format()

// this way converts from local to utc before formatting
moment('October 18th 2019', 'MMMM Do YYYY').utc().format()

// this way converts from local to utc before formatting and includes milliseconds
moment('October 18th 2019', 'MMMM Do YYYY').toISOString()


text:
Q: Why won't Tex show more than one page? I'm using tex for the first time and my professor gave us the template for a homework problem set.  I opened it in LaTeXiT (the software he told us to use) and for some reason it won't show past the first page.  I tried exporting it as a pdf and still, it only shows the first page.  Sorry for including so much code, as I said I'm new and I have no idea what might be causing this.  Is there anything I can do to fix this?
\documentclass[11pt]{amsart} %superior to the ``article'' documentclass, I think

%packages give you more functionality
\usepackage[
margin=1in,
%total={6.5in, 9in},
%left=1in,
footskip=25pt]{geometry} %controls the page layout
%\usepackage{fullpage} %to get full 8.5-by-11 inch margins, can use instead of the geometry package
\usepackage{amssymb} %gives you most of the symbols you could want
\usepackage{mathabx} %more symbols
\usepackage{graphicx} %helpful for putting in pictures
\usepackage{enumerate} %lets me control list environments precisely how I want them
%\usepackage{enumitem} %another list control package
\usepackage{color} %lets me use colored text
\usepackage{tikz} %nifty math drawing package
\usepackage{multicol} %for multi-column text
\usepackage{fancyhdr} %to put the nice headers and footers on each page
\usepackage{hyperref} %allows embedding of links in pdf files

%\thispagestyle{empty} %this command removes headers and footers from the first page

%these are commands I use a lot so want shorthand for, which \newcommand lets me do.
%mostly the ``blackboard bold'' letters, I like those a lot
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\N}{\mathbb{N}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\F}{\mathbb{F}}
\newcommand{\B}{\mathcal{B}}
\newcommand{\1}{\mathbbm{1}}
\newcommand{\mb}[1]{\vec{\mathbf{#1}}}

%These change the text color, but you need to put everything within curly braces {} or else all the text following will be that color.
\newcommand{\blue}{\color{blue}}
\newcommand{\red}{\color{red}}

%I'm a weirdo and like to control the numbering and list environments to within an inch of their lives.
%\resumeenum and \pauseenum let me start a list, pause the list and go out of the list environment (which has its own vagaries) for awhile, then come back and resume the numbering from where I left off
\newcommand{\resumeenum}
{
\begin{enumerate}[\bf 1.]
\setlength{\parsep}{0.07in}
\setlength{\parskip}{0.06in}
\setlength{\parindent}{0mm}
\setcounter{enumi}{\thesaveenumi}
}

\newcommand{\pauseenum}
{
\setcounter{saveenumi}{\theenumi}
\end{enumerate}
}

\newcounter{saveenumi}
\setcounter{saveenumi}{0}

%I want to write certain math expressions in Roman font instead of the italicized math font.  Especially functions, but things like sine and cosine have built in \sin and \cos commands.  \DeclareMathOperator lets you make similar function expressions of your own.
\DeclareMathOperator{\grad}{grad}
\DeclareMathOperator{\GL}{GL}
\DeclareMathOperator{\Span}{Span}
\DeclareMathOperator{\Aut}{Aut}
\DeclareMathOperator{\Perm}{Perm}
\DeclareMathOperator{\Gal}{Gal}
\DeclareMathOperator{\im}{im}
\DeclareMathOperator{\ch}{ch}
\DeclareMathOperator{\ord}{ord}
\DeclareMathOperator{\curl}{curl}
\DeclareMathOperator{\mydiv}{div}
%\DeclareMathOperator{\gcd}{gcd}

%I like to control the spacing between lines and between paragraphs.  I don't particularly like the defaults so I use these.  They are evolving in that sometimes I decide that something is a little too close together or far apart, so I end up tweaking these values slightly.
\setlength{\parindent}{0mm}
\setlength{\parskip}{0.07in}

%Spacing for List Environments
%\setlength{\parsep}{0.07in}
%\setlength{\parskip}{0.07in}

%The following makes the nice headers and footers
\pagestyle{fancy}
\fancyhf{}
\lhead{Math 2502, Number Theory and Cryptography}
\rhead{Spring 2017, Prof King} %maybe replace this header with your name?
\lfoot{Problem Set \#1}
\cfoot{Due February 1st}
\rfoot{Page \thepage}
\renewcommand{\headrulewidth}{0.7pt}
\renewcommand{\footrulewidth}{0.7pt}

%Everything above is called the ``preamble''.
%Hey look, we're finally starting the document!
\begin{document}

%The first page doesn't have the headers and footers unless you put this in.
\thispagestyle{fancy}

\ %This creates a blank line, putting a little space at the top of the page

%Make sure to put your name on the problem set!
{\Large\textbf{Name: } }

Who I worked with: ---\\

\begin{center}
{\Large\textbf{\blue Problem Set \#1}}\\
\textsc{due Wednesday, February 1, 2017}
\end{center}
\vspace{0.3in} %force vertical space

%Leaving a blank line in the code will create a line break.  Otherwise it doesn't know you want to move onto the next line.  E.g. look how I write the next sentence on multiple lines but it all appears on one line in the pdf.

Please turn in solutions to the
following problems at the beginning of class
on the date above.\\
%The double backslash creates a larger break in the text.

%\textbf{\LaTeX\ Instructions:}
%You may submit any handwritten computations (or code if you had a computer do it for you) for \#4(a), 6, 7, and 8, but you should also type up a summary of your results (and any conjectures!) in your \TeX. Everything else should be \TeX'ed.\\

{\large\textbf{\blue Axiomatic Ring Proofs}}
%\large makes the text a bit bigger, \textbf is bold font, which should be contained in braces or else the whole document will be bold from this point on!

Prove the following using only the ring axioms (Axioms 0--6) or the previous problems. Be rigorous!

\resumeenum

\item %This command is for a single list item, so you don't have to keep track of the numbering yourself
(Handout 1, \#1)
(Additive Cancellation Law)
For all $a,b,c \in \Z$,\ \ $a+b = a+c \implies b=c$.\\

\textbf{Proof: $a+b = a+c \implies b=c$.  Let $a=0$ so $0+b = 0+c$.  By Axiom 4, $b=c$.}

\qed

\item
(Handout 1, \#5)
Every $a \in \Z$ has a \emph{unique} additive inverse. In other words, the axiom guarantees there is at least one additive inverse for any chosen integer. Show that there is also at most one additive inverse! Hint: suppose $a$ had two additive inverses. Call them\ldots\ I don't know\ldots\ $b$ and $c$. Show $b=c$.\\

\textbf{Proof:  Let $b$ and $c$ be additive inverses for $a$.  So $a+b = 0$ and $a+c = 0$.  So $a+b = a+c$.  Using the above proof, we can reduce to $b = c$.  Thus, the additive inverse for $a$ is unique.}

\qed

\item
(Handout 1, \#6)
For all $a \in \Z$, $-(-a) = a$. Hint: what are the possible inverses of $-a$?\\

\textbf{Proof:  By Axiom 6, we say $-a+-(-a) = 0$. Since the additive inverse is unique, we can say $-(-a) = a$.}

\pauseenum

{\large\textbf{\blue Finite Rings}}

Let's explore arithmetic and equations in the finite rings $\Z/m\Z$.

\resumeenum

\item
(Handout 2, \#13)
Which of the following can you find in $\Z/11\Z$? In $\Z/35\Z$? In $\Z/9\Z$?
\
\[
7+8,\ 4-9,\ 3\cdot 5,\ 5^2,\ 5^3,\ 1/5,\ 3/8,\ \sqrt{3},\ \sqrt{-2},\ \sqrt{-6}.\\
\]
%the commands \[ and \] start and end displayed math equations.  You can also use \begin{displaymath} and \end{displaymath}. \qquad inserts some horizontal space.

\textbf{Answer:\\
In $\Z/11\Z$:  \[7+8,\ 4-9,\ 3\cdot 5,\ 5^2,\ 5^3,\ 1/5,\ 3/8,\ \sqrt{3},\ \sqrt{-2}, \ \sqrt{-6}\]\\
In $\Z/35\Z$:  \[7+8,\ 4-9,\ 3\cdot 5,\ 5^2,\ 5^3,\ 3/8\]\\
In $\Z/9\Z$:  \[7+8,\ 4-9,\ 3\cdot 5,\ 5^2,\ 5^3,\ 3/8\]
}\\

\item
(Handout 2, \#15)
Make a list of the perfect squares in each of $\Z/5\Z$, $\Z/7\Z$, $\Z/11\Z$, $\Z/13\Z$, $\Z/17\Z$, and $\Z/19\Z$.  I.e., square every element in $\Z/5\Z$ and write down the resulting list.  How many \emph{distinct} squares are there in each case?  Any conjectures?\\

%\textbf{Answer:}

\item
(Handout 2, \#16)
Solve $7x = 2$ in $\Z/17\Z$.\\

%\textbf{Answer:}

\item
(Handout 2, \#17)
Find all $x$ in $\Z/12\Z$ which solve the equation $8x = 4$ in $\Z/12\Z$.  Find all $x$ in $\Z/15\Z$ which solve the equation $9x = 10$ in $\Z/15\Z$.  Find all $x$ in $\Z/55\Z$ which solve the equation $15x = 35$ in $\Z/55\Z$. \\

%\textbf{Answer:}

\item
(Multiplicative Inverses)
The integers are boring; only $\pm 1$ have multiplicative inverses. But in $\Z/5\Z$, say, $3$ has a multiplicative inverse, because $3 \cdot 2 = 1$ in $\Z/5\Z$. So we could say $\frac{1}{3} = 2$ in $\Z/5\Z$!

An element of a ring which has a multiplicative inverse is called a \textbf{\blue unit}. For example, $\pm 1$ are the only units of $\Z$, whereas every nonzero real number is a unit in $\R$.

For each of $m = 9, 10, 11, 12, 13, 14, 15$, find all the units in $\Z/m\Z$. Do you see a pattern?\\

%\textbf{Answer:}

\pauseenum

{\large\textbf{\blue Applying modular thinking to get results about the integers}}

\resumeenum

\item
(Divisibility Rules)
Given $n \in \N$, we all know the divisibility rule: $n$ is a multiple of $3$ if and only if the sum of $n$'s digits is a multiple of $3$. But why is this true?

First, how do we formulate ``digits'' mathematically? Well, 154 means $1 \cdot 10^2 + 5 \cdot 10^1 + 4$. So we write $n = d_kd_{k-1} \cdots d_1d_0$ in digits iff
\[
n = d_k \cdot 10^k + d_{k-1} \cdot 10^{k-1} + \cdots + d_1 \cdot 10^1 + d_0 = \sum_{i=0}^k d_i \cdot 10^i,\quad 0 \leq d_i \leq 9, d_k \neq 0.
\]
%You can see how summation notation works in this example.
%Also, notice that if you want more than one symbol in an exponent, you need to enclose the exponent in curly braces.

\begin{enumerate}[\bf a.]
\setlength{\parindent}{0mm}
\setlength{\parskip}{0.09in}

\item
Prove the rule for divisibility by $3$ by reducing mod 3.

%\textbf{Proof:}

\item
Why does the same rule work for divisibility by $9$?

%\textbf{Answer:}

\item
Formulate and prove a rule for divisibility by 11.\\

%\textbf{Proof:}

\end{enumerate}

\pauseenum


text:
Q: @SpringBootApplication and @ComponentScan not working together (bean configuration) I have a multi module project but I am having a problem with my configuration.
I have a my main method in package nl.example.hots.boot
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages = {"nl.*"})
@EntityScan("nl.*")
public class HotsApplication {

    public static void main(String[] args) {
        SpringApplication.run(HotsApplication.class, args);
    }

In the nl.example.hots.core.* package I have the class:
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.REQUIRED)
public class MapImportService {

    private MapInputModelMapper mapInputModelMapper;
    private MapEntityRepository mapEntityRepository;

    public void add(final MapInputModel mapInputModel) {
        System.out.println(mapInputModel.getName());
        mapEntityRepository.save(mapInputModelMapper.mapToEntiy(mapInputModel));
    }

and:
@Component
@Mapper
public interface MapInputModelMapper {

    MapInputModel mapToInputModel(final MapEntity n);

    MapEntity mapToEntiy(final MapInputModel n);

}

The repository is in the package nl.example.hots.persistence.*
I get the following error when running the application:
Description:

Parameter 0 of constructor in nl.example.hots.core.dataimport.MapImportService.MapImportService required a bean of type 'nl.timonschultz.hots.core.map.mapper.MapInputModelMapper' that could not be found.

Action:

Consider defining a bean of type 'nl.example.hots.core.map.mapper.MapInputModelMapper' in your configuration.

When I remove the @EnableAutoConfiguration and @ComponentScan annotations it works. The application starts without the bean error.
In that case however my restcontroller does not work anymore:
{
    "timestamp": "2018-07-18T20:48:39.414+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/maps"
}

When I remove the MapImportService class (and the bean error doesn't pop up) it works on the same url.
package nl.example.hots.api.data_import;

@RestController
@AllArgsConstructor
public class ImportController {

    private static final String URL = // a url
    private Reader reader;

    @RequestMapping("/maps")
    public String abilityStreamImport() {
        reader.readStream(URL); // calls a class in nl.example.hots.core.*
        return "Greetings from APP!";
    }
}

I tried several different combinations and I have a different project as and example where the annotations are used together and it works right. Can somebody explain why the annotations generate the bean error when used together? And why the controller gives an error when only using @SpringBootApplication?
In my Pom.XML the boot module has a dependency on the API layer that has a dependency on the core layer that has a dependeny on the persistence layer.
I'm using mapstruct and Lombok in the project.
--- edit: repository ---
@Entity(name = "MAPS")
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class MapEntity extends HasId<Long> {

    private String name;

    @ElementCollection
    private List<String> translations;

}

@Repository
public interface MapEntityRepository extends JpaRepository<MapEntity, Long> {
}

@MappedSuperclass
public abstract class HasId<T> {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Setter
    @Getter
    private T id;
}

project structure:
hots-application;
- hots-api
    - pom.xml
    - nl.example.hots.api.dataimport.ImportController;
- hots-boot
    - pom.xml
    - nl.example.hots.boot.HotsApplication;
- hots-core
    - pom.xml
    - nl.example.hots.core.dataimport.mapImportService.MapImportService;
    - nl.example.hots.core.map.mapper.MapInputModelMapper
- hots-persistence
    - pom.xml
    - nl.example.hots.persistence.common.HasId;
    - nl.example.hots.persistence.map.MapEntity;
    - nl.example.hots.persistence.map.MapEntityRepository;
pom.xml

A: Spring Boot will scan all the packages and sub packages starting with the package that the @SpringBootApplication annotated class is in. Your class is in nl.example.hots.boot scanning only that package. The other classes are in different, non-scanned packages.
Due to this package structure and not following the best practices you basically loose a lot of the auto configuration features (Spring Data JPA, ReST etc) and you have to resort to manually enabling/configuring that. Partially through adding additional @ComponentScan annotation, for JPA the @EntityScan annotations. But you would also need to add all the @EnableJpaRepository etc. annotations as those aren't added anymore (at least not with the right packages).
The fix is fairly easy. Move your @SpringBootApplication annotated class to the nl.example.hots package (as stated in the best practices). Remove the annotations other then @SpringBootApplication and simply start your application.

A: You're missing the @Autowired annotation on your @AllArgsConstructor, try:
@AllArgsConstructor(onConstructor = @__(@Autowired))

A: After some trial and error I managed to get it working for the most part.
I added the scanBasePackages = "nl" to the SpringBootApplication annotation.
Mapstruct did give me some trouble still however but when I removed it and made a quick mapper myself it all worked fine.
Thanks for all the help and suggestions and links to read up on! I'll keep the (bestpractice) suggestions in mind for my next project.
Below is my main class now
package nl.example.hots.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication(scanBasePackages = "nl")
@EntityScan("nl.*")
@EnableJpaRepositories("nl.*")
public class HotsApplication {

    public static void main(String[] args) {
        SpringApplication.run(HotsApplication.class, args);
    }
}

A: Spring is not creating a MapInputModelMapperBean. I have never used MapStruct, but it kinda reminds me of mybatis. It looks weird to me that you annotate MapInputModelMapperBean with @Mapper and @Component. How is spring supposed to create the bean? Are you using some sort of spring-boot-mapstruct package that performs this magic?
I made a quick search and found this https://www.credera.com/blog/technology-solutions/mapping-domain-data-transfer-objects-in-spring-boot-with-mapstruct/, from which it seems like you would need something like:
@Mapper(componentModel = "spring")
public interface MapInputModelMapper

Which I guess will generate the implementation of the mapper with @Component on it or something similar.

A: The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes.
The component scan default behaviour happens only in the same package and in its sub package. If your controllers or components are in different, dont forget to override your component scan default configurations.
Here is the sample code on how to override the default behavour.
@SpringBootApplication(scanBasePackages = "com.code")

Or you can specify multiple packages as shown below:
@SpringBootApplication(scanBasePackages = {"com.java2novice", "com.example"})

A: The @SpringBootApplication annotation is a convenience annotation that combines the @EnableAutoConfiguration, @Configuration and the @ComponentScan annotations in a Spring Boot application.
@EnableAutoConfiguration – This enables Spring Boot's autoconfiguration mechanism. Auto-configuration refers to creating beans automatically by scanning the classpath.
@ComponentScan – Typically, in a Spring application, annotations like @Component, @Configuration, @Service, @Repository are specified on classes to mark them as Spring beans. The @ComponentScan annotation basically tells Spring Boot to scan the current package and its sub-packages in order to identify annotated classes and configure them as Spring beans. Thus, it designates the current package as the root package for component scanning.
You have used all these three annotations @SpringBootApplication , @EnableAutoConfiguration and @ComponentScan.
Instead use single annotation like @SpringBootApplication(scanBasePackages = "abc.def.ghi")
Here the HotsApplication class with more efficient annotation
   @SpringBootApplication(scanBasePackages = "nl.example.hots")
    public class HotsApplication {

        public static void main(String[] args) {
            SpringApplication.run(HotsApplication.class, args);
        }


text:
Q: Interleaving Two Arrays My logic is that I want to run the loop while arrA and arrB are not empty. So why would this fail on an input on [a,b,c] and [1,2,3,4]?
function combineArrays(arrA, arrB) {
let combined = [];
while (arrA.length != 0 && arrB.length != 0) {
    if (arrA.length != 0) {
        combined.push(arrA.shift());
    }
    if (arrB.length != 0) {
        combined.push(arrB.shift());
    }
}
return combined;

A: You should use || not && in this condition arrA.length != 0 && arrB.length != 0

function combineArrays(arrA, arrB) {
  let combined = [];
  while (arrA.length != 0 || arrB.length != 0) {
    if (arrA.length != 0) {
      combined.push(arrA.shift());
    }
    if (arrB.length != 0) {
      combined.push(arrB.shift());
    }
  }
  return combined;
}

console.log(combineArrays(['a','b','c'], [1,2,3,4]));

A: Your problem will solve with Or operator like below code snippet.
But if you want to concat arrays Array Concat can be useful for you.

console.log([1,2,3].concat(["a","b","c"]))

function combineArrays(arrA, arrB) {
  let combined = [];
  while (arrA.length != 0 || arrB.length != 0) {
    if (arrA.length != 0) {
      combined.push(arrA.shift());
    }
    if (arrB.length != 0) {
      combined.push(arrB.shift());
    }
  }
  return combined;
}

console.log(combineArrays([1,2,3], ["a","b","c"]))

A: value zero is == false  -->  Boolean(0) === false ( otherwise it's true )
so:

function combineArrays(arrA, arrB)
  {
  let combined = [];
  while (arrA.length || arrB.length)
    {
    if (arrA.length) combined.push(arrA.shift())
    if (arrB.length) combined.push(arrB.shift())
    }
  return combined;
}

console.log( combineArrays(['a','b','c'], [1,2,3,4]))

You can also do

function combineArrays(arrA, arrB)
  {
  let combined = [], iMax = Math.max(arrA.length,arrB.length)
  for (let i=0; i<iMax; ++i)
    {
    if (i<arrA.length) combined.push(arrA[i])
    if (i<arrB.length) combined.push(arrB[i])
    }
  return combined.filter(Boolean)
  }

console.log( combineArrays(['a','b','c'], [1,2,3,4]))

Or:

function combineArrays(arrA, arrB)
  {
  let combined = [], i = 0;
  for(let a of arrA) { combined[i++] = a; ++i  }
  i=1
  for(let b of arrB) { combined[i++] = b; ++i  }
  return combined.filter(Boolean)
  }

console.log( combineArrays(['a','b','c'], [1,2,3,4]))

Or again ( a little bit twisted)

function combineArrays(arrA, arrB)
  {
  let combined = [...arrA,...arrB ]
    , iMin     = Math.min(arrA.length,arrB.length) *2
    , j        = arrA.length
    ;
  for (let i=1; i<iMin; i+=2)
    {
    combined.splice(i,0,combined.splice(j++,1)[0] )
    }
  return combined
  }

console.log( combineArrays(['a','b','c'], [1,2,3,4]))

A: A better apporoach takes the shorter length and iterate the index and remains the given array intact.

function combineArrays(arrA, arrB) {
  let combined = [],
      i = 0,
      l = Math.min(arrA.length, arrB.length);

  while (i < l) {
      combined.push(arrA[i], arrB[i]);
      i++;
  }
  combined.push(...arrA.slice(i), ...arrB.slice(i));
  return combined;
}

console.log(combineArrays(['a', 'b', 'c'], [1, 2, 3, 4]));

A: For 4th iteration arrA.length will be 0, so the while loop will terminate because of AND condition. Use || instead of && in the while loop.


text:
Q: Having trouble encrypting and decrypting with cmp I'm having an issue now with the cmp. I need incorporate 3 tables to encrypt and decrypt. I can play with the code to either do n_tab, l_tab, or a_tab but can't seem to make sense of incorporating all three. Any help would be greatly appreciated. Thank you
.model small

.stack 100h

.data

    prompt1 db "ENTER YOUR MESSAGE HERE: $"
    prompt2 db "ENCRYPTED: $"
    prompt3 db "DECRYPTED: $"

    a_tab db "ZYXWVUTSRQPONMLKJIHGFEDCBA"

    buff  db 50 dup(0)

    .code

    main:
    mov ax, @data
    mov ds, ax                      ; set up addressability
    mov si, offset buff             ; put into buff

    lea dx, prompt1                 ; load and print the string PROMPT
    mov ah, 9
    int 21h
    mov si, di

    mov ah, 3fH
    mov cx, 50
    int 21h
    mov si, di

    mov bx, offset a_tab
    mov si, di

    l1: lodsb
    push bx
    mov ah, 6
    mov dl, 0ffh
    int 21h
    pop bx
    mov dl, al
    mov al, 0
    sub al, 'A'

    xlat
    loop l1

    lea dx, prompt2                 ; load and print the string PROMPT
    mov ah, 9
    int 21h
    mov si, di

    mov ah, 4cH
    int 21h

end main

A: There are a few problems I see which I'll describe. Sorry I don't have DOS or a DOS emulator or Windows set up to test this, so I'm just reading through your code. There may be other issues as well, but these are significant ones:
    mov ah, 3fH
    mov bx, 0
    mov cx, 50
    mov dx, offset buff         ; put into buff
    int 21h

The start of this segment sets up a file I/O to read from file handle 0 (standard input). When the int 21h returns, the actual number of bytes read is in ax, but this seems to be ignored, ultimately.
Then the loop starts...
l1:
    mov dl, al
    mov bx, offset a_tab

You're now beginning your encryption loop. You've moved the low byte of the number of bytes read from the user into dl and loaded the a_tab address into bx to set up for the xlat which expects the table address to be in ds:bx and will index that table by the value in al, loading the result into al.
    xlat

So here we already have trouble. What was in al when this xlat was first performed? It had the number of bytes read in from standard input, which is probably not what you intended. I assume the mov dl, al was somehow intended to get the next character out of the buffer, which we need to get into al before the xlat call. But that means we have to read it out of the buffer. Whither the buffer index or the advancing buffer pointer in the loop? It doesn't appear to be setup.
Moving on...
    mov ah, 6
    mov dl, 0ffh
    int 21h

This outputs the character that's in al to the terminal. So whatever you retrieved from a_tab using the number of bytes read from the terminal as an index is what you should be seeing as the first character output.
Remember the instruction at l1: above that did the mov dl, al? That seems to have no effect since dl hasn't been used yet and is now being overwritten with 0ffh for the above DOS interrupt.
    lea dx, prompt2               ; load and print the string PROMPT
    loop l1

This says you're loading and printing the prompt string, which seems like that's what you're starting to do (with the lea) but then you do a loop to l1. I assume the loop instruction belongs before the lea instruction here. The loop will decrement the counter in cx and jump to l1 if the result is not zero. However, what is in cx? Answer: UNCERTAIN because the last DOS interrupt we executed to output a character may have altered cx since it's not guaranteed to preserve registers. And even if it did the last known value of cx was from the mov cx, 50 which set up the maximum buffer size (not the actual buffer size, which was returned by the buffer read but ignored by the code). That interrupt might also have obliterated cx.
I'm supposing you are trying to index the translation table with the input characters. You have to first decide whether you're doing upper case, lower case, or both for your input, then have enough entries in the output table, a_tab to account for that. You need to read in a character, subtract off the lowest possible character value (which would be 'A' if you're using upper case letters), then use that value to index your table.
You're seeing garbled output because there's really no telling what's in al by the time you execute your xlat instruction each time through the loop.
To make the code work properly, here are some steps to follow:
Before the loop

*

*Read the input string buffer, as you are doing is fine, and save the number of bytes actually read into the loop counter, cx. All of the x86 loop instructions use cx as a counter.

*Set up a spare register, say si as the address of the current buffered input character (set si to buf to start). The si register is ideal for buffer indexing (look up the lods, stos, etc, instructions).

During the loop

*

*Read a byte from the input buffer into al (you can use the lodsb instruction to do this which will then automatically increment si for the next load)

*If you're reading all caps input, subtract 'A' from character in al. If everything is lower case, then subtract 'a'. You need to zero-base your index into a_tab.

*Put the address of a_tab into bx

*Execute your xlat instruction which will load the translated result into al.

*Save any registers you care about onto the stack using push; this includes the cx register which is your current loop counter and the si

*Use the DOS interrupt to output the character in al

*Restore the registers you previously saved in step 5 using pop

*Go around the loop with the loop instruction which will decrement the loop counter, cx.

These are the overall steps. You may want to do other things around this as well, but this should help get you on the right track. You should also read the documentation online for special instructions such as xlat and lodsb carefully to understand their behavior. In addition, anytime you call a DOS interrupt or function, it has conventions for how to pass arguments, and how information might be returned in registers. Any other registers not mentioned that you need might get used by that interrupt or function without you knowing, so you should save those registers before doing such calls, using push for example, and then restore them after the call using pop.


text:
Q: Is is possible to have more than one AudioFocus in one app on Android? I'm developing an android app which will play both audio file(via MediaPlayer), and TextToSpeech. Each will have specific timing for playing.
While audio is playing, if TTS speaking time comes, I want to lower the volume of MediaPlayer. Also, while TTS is speaking, if audio playing time comes, I want to lower the volume of TTS. (Both using AudioManager.STREAM_MUSIC)
I wanted to use something similar to AudioFocus(like below code). Behavior like requesting audio focus with AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK would be perfect, but both MediaPlayer and TTS is in same app, so it wouldn't duck the other sound.
I was wondering if somehow I can have different AudioFocus for each MediaPlayer and TTS, so that I can duck the sound while playing the other sound..
I could manage to manually lower the volume of MediaPlayer, but I found it almost impossible to programmatically lower the volume of TTS while it is already playing.
Any other suggestion besides using AudioFocus, AudioMAanger to solve this problem would be helpful too.


text:
Q: Parenthetical plurals of nouns with stems that are written differently in singular and plural Related Question that I don't like the answer to because it conflicts with my industry's standards (see bottom of post).
Edit: I asked a new question because I'm looking for an answer, not an alternative (the prior question will likely be forgotten because the original question wasn't addressed), even if that answer is "there is no correct way".

If I have a grocery list that tells me to buy meat and fruit, but I don't know whether I'm buying 1 or more types of each, I may write something along the lines of:
Buy:
-meat(s)
-fruit(s)

How do I pluralize a word in this fashion that requires a suffix change to become plural?
candy -> candies

It doesn't seem right to use any of the following:
candy(s)
candy(ies)
cand(y)(ies)
cand(y/ies)

Background: I write software, and this type of notation seems common, but I've never run into this type of problem: usually "(s)" after the word works without any problem.
For example: from Microsoft Word:


text:
Q: Reverse radial gradient I am trying to minify a SVG by hand. It uses two radial gradients which are the same, but with colors reversed.
<radialGradient id="a">
  <stop offset="0"  stop-color="#aadee8"/>
  <stop offset=".2" stop-color="#94d7e7"/>
  <stop offset=".5" stop-color="#6dcce9"/>
  <stop offset=".8" stop-color="#28b1e6"/>
  <stop offset="1"  stop-color="#27ace2"/>
</radialGradient>

<!-- Same colors, but opposite direction as #a -->
<radialGradient id="b">
  <stop offset="0"  stop-color="#27ace2"/>
  <stop offset=".2" stop-color="#28b1e6"/>
  <stop offset=".5" stop-color="#6dcce9"/>
  <stop offset=".8" stop-color="#94d7e7"/>
  <stop offset="1"  stop-color="#aadee8"/>
</radialGradient>

Is it possible to create an inverse copy by cloning a? I already tried <radialGradient xlink:href="#a" gradientTransform="scale(-1)" />, but that did not work out.

A: Here's a bit of trickery with the spreadMethod; it depends on the use of the fr attribute which was only introduced in SVG 2, so compatibility might be an issue.
The idea is to define the colors outside the intended outer radius and then define how it is continued further in. (Percentages are relative to the bounding box, so r="50%", the default, fits the outer radius to the border of the box if cx is in the middle.)

<svg width="200" height="100">
  <radialGradient id="a" r="100%" fr="50%">
    <stop offset="0"  stop-color="#aadee8"/>
    <stop offset=".2" stop-color="#94d7e7"/>
    <stop offset=".5" stop-color="#6dcce9"/>
    <stop offset=".8" stop-color="#28b1e6"/>
    <stop offset="1"  stop-color="#27ace2"/>
  </radialGradient>
  <radialGradient id="b" spreadMethod="repeat" xlink:href="#a" />
  <radialGradient id="c" spreadMethod="reflect" xlink:href="#a" />

  <circle r="50" cx="50" cy="50" fill="url(#b)" />
  <circle r="50" cx="150" cy="50" fill="url(#c)" />
</svg>


text:
Q: How to fit more than one line to data points I am trying to fit more than one line to a list of points in 2D. My points are quite low in number (16 or 32).
These points are coming from a simulated environment of a robot with laser range finders attached to its side. If the points lie on a line it means that they detected a wall, if not, it means they detected an obstacle. I am trying to detect the walls and calculate their intersection, and for this I thought the best idea is to fit lines on the dataset.
Fitting one line to a set of points is not a problem, if we know all those points line on or around a line.
My problem is that I don't know how can I detect which sets of points should be classified for fitting on the same line and which should not be, for each line. Also, I don't even now the number of points on a line, while naturally it would be the best to detect the longest possible line segment.
How would you solve this problem? If I look at all the possibilities for example for groups of 5 points for all the 32 points then it gives 32 choose 5 = 201376 possibilities. I think it takes way too much time to try all the possibilities and try to fit a line to all 5-tuples.
So what would be a better algorithm what would run much faster? I could connect points within limit and create polylines. But even connecting the points is a hard task, as the edge distances change even within a single line.
Do you think it is possible to do some kind of Hough transform on a discrete dataset with such a low number of entries?
Note: if this problem is too hard to solve, I was thinking about using the order of the sensors and use it for filtering. This way the algorithm could be easier but if there is a small obstacle in front of a wall, it would distract the continuity of the line and thus break the wall into two halves.

A: A good way to find lines in noisy point data like this is to use RANSAC. Standard RANSAC usage is to pick the best hypothesis (=line in this case) but you can just as easy pick the best 2 or 4 lines given your data. Have a look at the example here:
http://www.janeriksolem.net/2009/06/ransac-using-python.html
Python code is available here
http://www.scipy.org/Cookbook/RANSAC

A: The first thing I would point out is that you seem to be ignoring a vital aspect of the data, which is you know which sensors (or readings) are adjacent to each other.  If you have N laser sensors you know where they are bolted to the robot and if you are rotating a sensor you know the order (and position) in which the measurements are taken.  So, connecting points together to form a piecewise linear fit (polylines) should be trivial.  Once you had these correspondances you could take each set of four points and determine if they can be modeled effectively by only 2 lines, or something.
Secondly, it's well known that finding a globally optimal fit for even two lines to an arbitrary set of points is NP-Hard as it can be reduced to k-means clustering, so I would not expect to find an efficient algorithm for this.  When I used the Hough transform it was for finding corners based on pixel intensities, in theory it is probably applicable to this sort of problem but it is just an approximation and it is probably going to take a fair bit of work to figure out and implement.
I hate to suggest it but it seems like you might benefit by looking at the problem in a slightly different way. When I was working in autonomous navigation with a laser range finder we solved this problem by discretizing the space into an occupancy grid, which is the default approach.  Of course, this just assumes the walls are just another object, which is not a particularly outrageous idea IMO.  Beyond that, can you assume you have a map of the walls and you are just trying to find the obstacles and localize (find the pose of) the robot? If so, there are a large number of papers and tech reports on this problem.

A: A part of the solution could be (it's where I would start) to investigate the robot. Questions such as:

*

*How fast is the robot turning/moving?

*At what interval is the robot shooting the laser?

*Where was the robot and what was its orientation when a point was found?

The answers to these questions might help you better than trying to find some algorithm that relies on the points only. Especially when there are so very few.
The answers to these questions give you more information/points. E.g., if you know the robot was at a specific position when it detected a point, there are no points in between the position of the robot and the detected point. that is very valuable.

A: For all the triads, fit a line through them and compute how much the line is deviating or not from the points.
Then use only the good (little-deviating) triads and merge them if they have two points at common, and the grow the sets by appending all triads that have (at least) two points in the set.
As the last step you can ditch the triads that haven't been merged with any other but have some common element with result set of at least 4 elements (to get away with crossing lines) but keep those triads that did not merge with anyone but does not have any element in common with sets (this would yield three points on the right side of your example as one of the lines).
I presume this would find the left line and bottom line in the second step, and the right line the third.


text:
Q: Using nested WHERE clause? SELECT ymd,
       creative_id,
       sum(imps) as imps,
       sum(booked_revenue_dollars) as booked_rev
  FROM agg_dw_advertiser_publisher_analytics_adjusted
 WHERE buyer_member_id=456
   AND (sum(imps) > 500 WHERE ymd > current_date() - 14) #this part is wrong
 GROUP BY 1,2
HAVING min(ymd) < current_date() - 14
 ORDER BY 2,1 ASC;

ymd = year/month/date
I'm trying to filter out creative_id's where the sum of the field imps is less than 500 in aggregate over the past 2 weeks. I'm obviously not doing this right, but have tried as an additional HAVING clause as well as a sub query. What am I doing wrong?

A: There is no such concept called Nested WHERE . You can modify your HAVING like this.
SELECT creative_id,
       sum(imps) as imps,
       sum(booked_revenue_dollars) as booked_rev
  FROM agg_dw_advertiser_publisher_analytics_adjusted
 WHERE buyer_member_id=456
 GROUP BY creative_id
HAVING sum(imps) > 500 AND min(ymd) > current_date() - 14
 ORDER BY 2,1 ASC;

A: Something like this (off the top of my head)
SELECT ymd, creative_id,
       sq.imps as imps,
       sq.booked_rev as booked_rev
  FROM agg_dw_advertiser_publisher_analytics_adjusted a
  INNER JOIN
      (
       SELECT creative_id, sum(imps) as imps, sum(booked_revenue_dollars) as booked_rev
       FROM agg_dw_advertiser_publisher_analytics_adjusted
       WHERE buyer_member_id=456 and ymd > current_date() - 14
       GROUP BY creative_id
      ) as sq
    ON  a.creative_id = sq.creative_id
 WHERE buyer_member_id=456 and sq.imps > 500 and ymd > current_date() - 14
 ORDER BY ymd,creative_id ASC;


text:
Q: Python 3.9 keyboard.record() Возник вопрос:
В модуле keyboard имеется функция записи действий с клавиатуры (start_recording - stop_recording), по окончании записи данные представляются в типе list и их можно записать в переменную.
Вопрос в том, как бы записать эти данные с записи в файл, да так чтоб при открытии в следующий раз list сохранился для чтения модулем keyboard (функция: play()). Или же имеются способы по восстановлению list из строки?...
import keyboard,json
#нажмите k для активации записи клавиш с клавиатуры пк
keyboard.wait('k')
keyboard.start_recording()
keyboard.wait('l')
a=keyboard.stop_recording()
# здесь тип переменной a list
with open('name.txt','w') as f:
    f.write(str(a))
with open('name.txt','r') as f:
    b = f.read(json.loads(f.read()))
#при присваивании b ошибка.

keyboard устанавливается на win: pip install keyboard.

A: допустим
events = [keyboard.KeyboardEvent(0,0)]

тогда можно сохранить как
with open('list.txt', 'w', encoding='utf-8') as f:
    f.writelines( [ ke.to_json()+'\n' for ke in events ] )

прочитать обратно
import json

with open('list.txt', 'r', encoding='utf-8') as f:
    events = [ keyboard.KeyboardEvent(**json.loads(js)) for js in f.readlines()]


text:
Q: lirc - Python counter script will not run I am puzzled as to why the following script (count.py) will not run using the IR remote
#!/usr/bin/env python
from __future__ import with_statement
with open('num.txt','r+') as f:
   counter = str(int(f.read())+1)
   f.seek(0)
   f.write(counter)

I have other scripts which work fine i.e. this one when mapped to same button executes without issue
#!/usr/bin/env python
import RPi.GPIO as GPIO ## Import GPIO library
GPIO.setmode(GPIO.BCM) ## Use board pin numbering
GPIO.setup(22, GPIO.OUT) ## Setup GPIO Pin 7 to OUT
GPIO.output(22,True) ## Turn on GPIO pin 7
GPIO.cleanup()

The problem script will work from the command line using 'sudo python count.py' and if I start irexec from the command line with sudo then it will also run using the remote. In essence starting irexec in this way is a workable solution. Nevertheless I am still keen to establish why under the present conditions the script will not run.

A: It might be that the problem script is not able to open "num.txt": either it is running as a user who doesn't have permission, or it is running from a directory you don't expect and so can't see the relative path to num.txt. In this case the script would fail with an error, but this might be being lost somewhere.
Try checking logs to see if there are any errors reported.
You can also alter the script to use an absolute path to num.txt, and catch exceptions and write them to a log somewhere (also absolute path, and all write permissions? - maybe in /tmp)


text:
Q: Ember date belongTo with serialized id App.Locale = DS.Model.extend
  language: DS.belongsTo("language")

App.LocaleSerializer = App.ApplicationSerializer.extend
   attrs:
     language:  { serialize: "id", deserialize: "records" }

Using ember with rails as the backend. I am trying to create a locale, which has a dropdown to select a language. My idea is to pass a language_id to the backend, however I get the following when I submit.
{"locale"=>{"language"=>"15" }

How do I convert this to look like
{"locale"=>{"language_id"=>"15" }

Thanks

A: Assuming that you're using the ActiveModelSerializer, I think your answer is here. Just add the key attribute to the hash:
App.LocaleSerializer = App.ApplicationSerializer.extend
  attrs:
    language:  { key: "language_id", serialize: "id", deserialize: "records" }

If you only want to use language_id when serializing, but get language when deserializing, you can always override serializeBelongsTo:
App.LocaleSerializer = App.ApplicationSerializer.extend
  serializeBelongsTo: (record, json, relationship) ->
    if relationship.key is 'language'
      json.language_id = Ember.get record, 'language.id'
    else
      @_super record, json, relationship


text:
Q: Receiving ServletContext Into A Plain Java Class? I'm just starting out learning some JSP and servlets today and was wondering if it's possible to get the session's ServletContext as a variable and pass it to a plain Java class?  If so, how may I do that?
My simple servlet:
public class myServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
                HttpSession session = request.getSession(true);

                //How do I receive the servlet context below in a plain Java class?
                ServletContext sc = session.getServletContext();
                request.setAttribute("sc", sc);
        }
}

My Java class is just a plain one:
public class myClass extends HttpServlet {

   //I want to be able to use the ServletContext as a variable that is passed from myServlet class into this one.

}

In myClass I want to be able to use it to get the real path file of a file within my project:
ServletContext sc
String path = sc.getRealPath(...)
EDIT:  Can I do something like this in myServlet servlet?:
String realPath = sc.getRealPath("/WEB-INF/myFile");
But then how do I pass this realPath variable into myClass so I can use it there instead of in myServlet?

A: *

*create a class
public class MyClass {....}

*Have a variable of type ServletContext
private ServletContext myContext;

*Set value through Constructor or setter
void setContext (ServletContext sc) {myContext = sc;}

*Use it
myContext.get....("xxx");
Edit
You can use this class from your servlet as
doPost (....) {

   ....
    ServletContext sc = session.getServletContext();
   MyClass mc = new MyClass ();
   mc.setContext (sc);

 // now the context is **in** the MyClass instance - how you use it is up to you.


text:
Q: SharePoint Rich Text Editor Control Using Javascript I have to create SharePoint Rich Text Editor Control using JavaScript. How can I create?
At the run time it will be decided how many control I have to display because of that I can not use static control.

A: You don't give many details in your question but here's a suggestion that might work for you.
You can use CKeditor (http://ckeditor.com/) in a script editor web part to do this.
Here is a fiddle from TheSharpieOne that shows nicely how you can use CKEditor (with Angular):
http://jsfiddle.net/thesharpieone/cptr7/

A: You can use the built-in SharePoint Rich Text Editor, as per this link. Create a div for each such field you want to add, with contentEditable set to true.
<div contentEditable="true" role="textbox"
     aria-haspopup="true" aria-autocomplete="both"
     aria-multiline="true" />
  <!-- field content goes here -->
</div>

(The role and aria-* attributes are for accessibility, not for RTE functionality.)
You'll also need to add a few classes:

*

*For SP 2010: ms-rtestate-write ms-rteflags-0 ms-rtestate-field

*For SP 2013: ms-rte-layoutszone-inner-editable ms-rtestate-write
As long as you're on a page which already has the Rich Text Editor ribbon enabled, this is all you need to do. The RTE will pick up the div, and start managing its value. (I've tested this with SP 2013.)
If you want to add the ribbon to a page, you'll have to have some server-side code (C#), using MakeRTEContextualTabsAvailable.

A: http://shareden.blogspot.ru/2013/06/jquery-plugin-for-sharepoint-2010-that.html
I hope this link will help you

A: I would recommend using one of the third party RichText controls. Quill seems to be a very good candidate.
You can get more details here...
Quill


text:
Q: how can I set a height and width for this map in d3.js I am new and I am working using this map. I have a div container called: #statesvg where I want the map to adapt to its size. but this one is cut.

in which part of the code can I modify the height and width of the map?
Thank you very much
http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922
//I get the actual size of the div
var width = document.getElementById('statesvg').offsetWidth;
var height = document.getElementById('statesvg').offsetWidth;
.
.
.
Same code

A: Other than scaling the entire svg (or portions of it), you can change the projection. The projection determines how much space your features occupy, no matter what the svg size. The easiest method would be to use projection.fitSize() in d3v4+:
projection.fitSize([width,height],feature);
Where width and height are your svg dimensions, and feature is your geojson feature collection (json in your example, not json.features, it takes an object, not an array). This method sets the scale and translate of the projection so that your features are centered and scaled appropriately for your svg/canvas.
Alternatively, given that all fitSize does is set the translate and scale of a projection, you could modify these attributes directly to set the appropriate scale and translate. Since your example centers the projection with [width/2,height/2] this is will already adapt to provided dimensions. Consequently, all you need to do is set the scale. If the scale value of 1000 is appropriate for a width of 960 and height of 500, then a scale of 2000 will be appropriate for a width of 480 and a height of 250. With this we can just use some simple math:
var scale = 960/width*1000; // assuming that width is always limiting
If width or height could be limiting, find the scale value for both using the above logic and take the higher scale value. Then apply the scale to the map the same as your example does now: projection.scale(scale);. This lets you scale the map easily, and in d3v3 as well (like your example block).


text:
Q: Owncloud upgrade fails with MySQL timeout I just upgraded to a new Owncloud version. After installing the .deb package, I ran
sudo -u www-data php /var/www/owncloud/occ upgrade

which gave me:
 oc_appconfig
  1/24 [=>--------------------------]   4%Doctrine\DBAL\Exception\DriverException: An exception occurred while executing 'SET unique_checks=1':

SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
Update failed

An online research indicated this was possibly a MySQL timeout issue, so I created /etc/mysql/my.cnf with the following content:
[mysqld]
interactive_timeout=86400
wait_timeout=86400
max_allowed_packet=521M

Then I restarted MySQL and retried—to no avail. Most of the times step 1 fails; sometimes I get as far as step 3 (always with the same SQL command timing out).
OS is Raspbian, running on a Raspberry Pi 3.
What will fix this issue?

A: The server probably dropped an incorrect or too large packet. If mysqld gets a packet that is too large or incorrect, it assumes that something has gone terribly wrong with the client and closes the connection. To fix that, you need to increase the maximal packet size limit max_allowed_packet in my.cnf file, then restart MySQL server: (/etc/init.d/mysql restart).

A: The error message

SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

can mean a couple of things: Often it refers to a timeout, which can be rectified by increasing the timeout values (default is 8 hours), or indicates that the allowed packet size was exceeded, which can be corrected by increasing max_allowed_packet. It also occurs when the MySQL server crashes in the middle of the operation, so check for that when the first two options provide no relief.
After some more research, I consulted the MySQL log. There was an empty file named/var/log/mysql.err, as well as some files which indicate log rotation.
Running ps -ef | grep mysql then gave me the full command line for the MySQL process, with a parameter for the log file, which turned out to be /var/lib/mysql/<hostname>.err.
Examining this file revealed that MySQL kept crashing due to data corruption, probably affecting the oc_filecache table. This explains why the update failed—how to recover from the corruption will be a separate question. The string displayed by occ above the progress bar seems to be the table which was being processed when the error occurred (if that is unclear from the MySQL logs, where one needs to look close to find the table).


text:
Q: E_NOINTERFACE after upgrade of VB6 After upgrading a VB 6 based application exposing a COM interface,
COM Clients (in .NET) built against the previous version receive E_NOINTERFACE errors.
The error message (translated),

Cannot convert COM-object of type AProduct.AClass to interface of type AProduct._AClass ...

What went wrong here?
What is the cause of the E_NOINTERFACE error?
I thought that once an interface was published to COM it cannot be changed; a new interface (with unique UUID) should be published which can inherit the old one, thus i reasoned that the interface might have been updated (extended) incorrectly.

A: What is the Version Compatibility setting in your VB 6.0 project? (See the Component tab of your project properties)
If it's not Binary Compatibility then the GUIDs for the interfaces and events exposed by your component may have been changed when you compiled the DLL.
Check out these resources for more information
How To Use Project and Binary Compatibility
Setting up a COM component project in Visual Basic 6.0


text:
Q: how to add a mean row, Standard deviation row, sum column I have tables varying in amounts of rows, but always the same number of columns, but they all look like this:
> head(Summary_POST,10)
        Date Standing Stepping Cycling New_Sitting Counter
1 2022-03-31     1489        8      85         639     132
2 2022-04-01     1823      951     181       29446     481
3 2022-04-04    10159      718   11093       10431    1136
4 2022-04-05     9112        6       8       23275       6
5 2022-04-06    16210      852    7258        8081     601
6 2022-04-07    10997     1607    3554       16243     862
7 2022-04-08    23803       10    2094        6468     238
>dput(head(Summary_POST,10)
structure(list(Date = structure(c(19082, 19083, 19086, 19087,
19088, 19089, 19090), class = "Date"), Standing = c(1489, 1823,
10159, 9112, 16210, 10997, 23803), Stepping = c(8, 951, 718,
6, 852, 1607, 10), Cycling = c(85, 181, 11093, 8, 7258, 3554,
2094), New_Sitting = c(639, 29446, 10431, 23275, 8081, 16243,
6468), Counter = c(132L, 481L, 1136L, 6L, 601L, 862L, 238L)), row.names = c(NA,
7L), class = c("tbl_df", "tbl", "data.frame"))

I would like to be able to add 2 rows at the end and 1 column, 1 row that does the MEAN of each column(not the Date column), 1 row that does the Standard Deviation of each column (not the Date column), and a Column that does the SUM of each Row (ONLY THE DATA IN COLUMNS "Standing:New_Sitting").
End result in this case should look like this:
        Date Standing Stepping Cycling New_Sitting Counter  SUM
1 2022-03-31     1489        8      85         639     132   2221
2 2022-04-01     1823      951     181       29446     481  32401
3 2022-04-04    10159      718   11093       10431    1136  32401
4 2022-04-05     9112        6       8       23275       6  32401
5 2022-04-06    16210      852    7258        8081     601  32401
6 2022-04-07    10997     1607    3554       16243     862  32401
7 2022-04-08    23803       10    2094        6468     238  32375
8 MEAN          10513      593    3467       13511     493
9 STDV           7254      569    3939        9343     377

EDIT
Summary_POST <- workday_POST %>% group_by(Date) %>% mutate_if(is.character,as.numeric) %>% summarise(across(Axis1:Counter,sum))
Summary_POST <- subset (Summary_POST, select = -c(Axis1,Axis2,Axis3,VM))
 Summary_POST  %>% mutate(
        Date = as.character(Date)
    )
Summary_POST %>%
    bind_rows(
        Summary_POST %>%
            summarise(across(everything(), mean)) %>%
            mutate(
                Date = 'mean'
            )
    ) %>%
    bind_rows(
        Summary_POST %>%
            summarise(across(everything(), sd)) %>%
            mutate(
                Date = 'sd'
            )
    ) %>%
    mutate(
        SUM = rowSums(across(-Date)),
        SUM = if_else(Date %in% c('mean', 'sd'), NA_real_, SUM)
    )

A: Bit ugly but this is one way:
library(dplyr)
tib <- structure(list(Date = structure(c(19082, 19083, 19086, 19087,
                                  19088, 19089, 19090), class = "Date"), Standing = c(1489, 1823,
                                                                                10159, 9112, 16210, 10997, 23803), Stepping = c(8, 951, 718,
                                                                                6, 852, 1607, 10), Cycling = c(85, 181, 11093, 8, 7258, 3554,
                                                                                2094), New_Sitting = c(639, 29446, 10431, 23275, 8081, 16243,
                                                                                6468), Counter = c(132L, 481L, 1136L, 6L, 601L, 862L, 238L)), row.names = c(NA,
                                                                                7L), class = c("tbl_df", "tbl", "data.frame")) %>%
    mutate(
        Date = as.character(Date)
    )
tib %>%
    bind_rows(
        tib %>%
            summarise(across(everything(), mean)) %>%
            mutate(
                Date = 'mean'
            )
    ) %>%
    bind_rows(
        tib %>%
            summarise(across(everything(), sd)) %>%
            mutate(
                Date = 'sd'
            )
    ) %>%
    mutate(
        SUM = rowSums(across(-Date)),
        SUM = if_else(Date %in% c('mean', 'sd'), NA_real_, SUM)
    )
# A tibble: 9 x 7
  Date       Standing Stepping Cycling New_Sitting Counter   SUM
  <chr>         <dbl>    <dbl>   <dbl>       <dbl>   <dbl> <dbl>
1 2022-03-31    1489        8      85         639     132   2353
2 2022-04-01    1823      951     181       29446     481  32882
3 2022-04-04   10159      718   11093       10431    1136  33537
4 2022-04-05    9112        6       8       23275       6  32407
5 2022-04-06   16210      852    7258        8081     601  33002
6 2022-04-07   10997     1607    3554       16243     862  33263
7 2022-04-08   23803       10    2094        6468     238  32613
8 mean         10513.     593.   3468.      13512.    494.    NA
9 sd            7835.     615.   4255.      10091.    407.    NA


text:
Q: How to fix pixelated background-image on Chromium-based browsers? On Chromium-based browsers, downscaled images used as background-image are pixelated while they look more blurred when displayed with an  tag. Is there a way to change the render style of a background image so it look like the display in the tag? I tried the image-rendering property but it doesn't seem to work on background-image. It looks fine on Firefox.
Example of render on Brave, left is background-image and right is with the  tag:

#backgroundImage, img {
  width: 80px;
  min-height: 80px;
  margin: 10px 5px;
  display: inline-block;
}

#backgroundImage {
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-image: url("https://i.stack.imgur.com/X5EfB.png");
}

A: This seems to be happening only when both the size:cover and position:center rules are applying. You can have the same result in the  by changing its object-fit to cover:

#backgroundImage, img {
  width: 80px;
  min-height: 80px;
  margin: 10px 5px;
  display: inline-block;
  object-fit: cover;
}

#backgroundImage {
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  background-image: url("https://i.stack.imgur.com/X5EfB.png");
}

So to avoid it, you can replace the background-size:cover rule with 100% 100%:

#backgroundImage, img {
  width: 80px;
  min-height: 80px;
  margin: 10px 5px;
  display: inline-block;
}

#backgroundImage {
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;
  background-image: url("https://i.stack.imgur.com/X5EfB.png");
}