text:
Q: Inheritance of decorators I have 3 files one person.py and items.py and game.py.
In game.py there is an event handler such that when a button or space is pressed it calls the player object to use the function given to it by object in his hand.
To achieve this I have created an inheritable item class with a function that when called by the person returns a function specific to the subclass of item.
I have tried to create a decorator function of item @efunc that sets the function beneath as a variable of self.efunc and a second function to be called by person inhand.getefunc() that returns efunc as a variable which is then called by the person when game.py calls that function.
In person.py:
class person:
  def init(self):

    self.inhand = banana # this could be many other different items and
    #changes through the game

  def useefunc(self): # game.py calls this function when e is pressed
    func = self.inhand.getefunc()
    func(self)

  def usespacefunc(self):# game.py calls this function when space is #pressed
    func = self.inhand.getspacefunc()
    func(self)

In items.py:
class items:
  def init(self):
    self.efunc
    self.spacefunc

  def efunc(func,self):
    self.efunc = func

  def getefunc(self)
    return self.efunc

  def spacefunc(func,self):
    self.spacefunc = func

  def getspacefunc(self):
    return self.spacefunc

class banana(items):

  def init(self):# was removed
    self.efunc = consume # I tried this it did not work was removed
    self.spacefunc = trash # also did not work was removed
  @spacefunc
  def consume (p):

#p is a person so consume can transfer its effects on the person and its animation
 @efunc
  def trash(p):

class nothing(items):
  pass

I have done some troubleshooting and editing and I could not determine much.

A: I think you're making things much more complicated than they need to be. It would be much easier for the Person object to pass a reference to itself to an appropriate method of the item in its hand.
class Person:
    def __init__(self, in_hand):
        self.in_hand = in_hand

    def use_object(self):
        self.inhand.use(self)

class Item:
    def use(self, person):
        pass

class Banana(Item):
    def use(self, person):
        # do something here?

There's no need for decorators or any other complexity.
As for why your code wasn't working, the main issue was that you were trying to use self in a context where there was no instance yet. A decorator of a method, for instance, can't use self directly, since the method is defined before the class exists yet (and long before any instances exist).


text:
Q: Count how many words have the same beginning and ending letter/Python
QUESTION: The variable sentence stores a string. Write code to
  determine how many words in sentence start and end with the same
  letter, including one-letter words. Store the result in the variable
  same_letter_count.

I've tweaked this a few different ways but I still can't figure it out.  Any help + explanation is appreciated so I know how to handle this the next time.
sentence = "students flock to the arb for a variety of outdoor activities
such as jogging and picnicking"

same_letter_count = 0
sentence_split = sentence.split(' ')
sent_length = len(sentence_split)
#print(sent_length)
# Write your code here.
for d in sentence_split:
    #print(d[0])
    if d[0] == d:
        same_letter_count = same_letter_count + 1
    elif d[-1] == d:
        same_letter_count = same_letter_count + 1
print(same_letter_count)

I'm getting an answer of 1, the correct answer is 2.

A: You can take advantage of the fact the Python's booleans can be treated like zeros and ones and just add up all the boolean values of the test word[0] == word[-1]. The expression:
[w[0] == w[-1] for w in sentence.split()]

evaluates to a list like [True, False, False...]. Taking the sum of that is the same as counting the number of True values and is a very typical way of doing something like this in Python.
sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = sum(w[0] == w[-1] for w in sentence.split())
# 2

A: if d[0] == d:
    same_letter_count = same_letter_count + 1
elif d[-1] == d:
    same_letter_count = same_letter_count + 1

This checks if the first letter is equal to the entire word, or if the last letter is equal to the entire word. Therefore you are only counting "a". Instead try
if d[0] == d[-1]:
    same_letter_count = same_letter_count + 1

A: A quick solution by pandas:
s = pd.Series(sentence.split(' '))
(s.str[0] == s.str[-1]).sum()

gives answer 2.
You can even get those words:
s[s.str[0] == s.str[-1]]

gives:
0    students
6           a
dtype: object

A: sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = 0

sentence_split = sentence.split(' ')
sentense_length = len(sentence_split)

for d in sentence_split:
    if d[0] == d[-1]:
        same_letter_count += 1
print(same_letter_count)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Importing json that was serialized by JSON is failing So I have an object with some fields...
protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;

Which gets serialized to JSON like this:
public void serialize(){
    Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
    String json = gson.toJson(this);

    try {
        FileWriter writer = new FileWriter(this.relativePathAndFileName);
        writer.write (json);
        writer.close();
    } catch (IOException e) {
        logger.error("Error while trying to write myAlert to json: ", e);
    }
}

Later when I need to read in this json file, I try to do so like this:
try {
        for (File f : alertConfigFiles) {
            Gson gson = new Gson();
            JsonReader reader = new JsonReader(new FileReader(f));
            Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> myMap = gson.fromJson(reader, type);
            Alert tempAlert = new Alert(myMap);
            myAlerts.add(tempAlert);
            logger.debug("Imported: " + f.toString());
        }

The error that I'm getting is:
Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.

The JSON inside the file is something to the effect of:
 {
 "name": "Logs Per Host - past 24 hours",
 "relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
 "next_Run": "2017-06-07T22:24:56.682-04:00",
 "hosts": [
    "app-12c",
    "app1-18",
    "wp-01",
    "app-02",
    "wp-02",
    "cent-04",
    "app-06",
    "app-05"
  ]
  }

It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.
Can anyone offer some advice on how to get my import working without issues?

A: Those two lines seem to be the problem:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);

You serialize your object of some specific class. You then deserialize it to type. But your JSON does not fit into a Map. Better do it like this, so you can use your own class.
YourClass myMap = gson.fromJson(reader, YourClass.class);

If you want to use this approach, you might want to change your Java class to hold an array of strings instead of an ArrayList of strings.
Maybe this page helps you a bit. Especially the first case fits your situation.
Another option is a custom Deserialzer as described here.

A: try to keep it simple. Using maps and so on, is a way to have issues.
Here is a working code to deserialise / serialise :
package com.rizze.beans.labs.sof;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.google.gson.Gson;

public class SOFGson {

    public String json = "{  \"name\": \"Logs Per Host - past 24 hours\", \"relativePathAndFileName\": \"./Elk-Reporting/Alerts/logs_per_host24h.json\", \"next_Run\": \"2017-06-07T22:24:56.682-04:00\", \"hosts\": [ \"bos-qa-app-12c\", \"bos-qa-app1-18\", \"bos-qa-wp-01\", \"bos-lt-app-02\", \"bos-qa-wp-02\", \"bos-dev-cent-04.americanwell.com\", \"bos-qa-app-06\", \"bos-qa-app-05\" ]}";

    public class MyObj{
        protected String name;
        protected String relativePathAndFileName;
        protected String next_Run;
        protected String[] hosts;
    }

    @Test
    public void test() {

        Gson gson = new Gson();
        MyObj obj = gson.fromJson(json, MyObj.class);
        assertTrue(obj!=null);
        assertTrue(obj.hosts.length==8);
        System.out.println(gson.toJson(obj));

    }

}

here is the class in gist : https://gist.github.com/jeorfevre/7b32a96d4ddc4af68e40bf95f63f2c26


text:
Q: Why am I ALWAYS getting SSL error when contacting Parse.com? Environment:
Xcode 7.0/Swift 2.0.

I could connect to parse via Xcode 6.4/Swift 1.2; but after switching to Xcode 7.0/Swift 2.0 I've been getting  the following runtime connection error:

An SSL error has occurred and a secure connection to the server cannot be made. (Code: 100, Version: 1.7.5)
[Error]: Network connection failed. Making attempt 5 after sleeping
  for 9.864530 seconds. NSURLSession/NSURLConnection HTTP load failed
  (kCFStreamErrorDomainSSL, -9802)

I read that it may be due to iOS 9's security setup.
Setting the .plist value 'NSAppTransportSecurity' to turn off this security check didn't change anything.

This problem occurs in simulation or device; every time.

How can I access parse.com as I've always done?

A: I went to Apple's Security Doc site to find that I didn't set up my plist correctly.  The following WORKS: this allows me to access parse within iOS9:

A: You just have to add this in your code :
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>


text:
Q: Spring custom validator with dependencies on other fields We are using spring custom validator for our request object used in our controller endpoint. We implemented it the same way as how its done in the link below:
https://www.baeldung.com/spring-mvc-custom-validator
The problem we are facing is, it can't work if the particular field has dependencies on other input fields as well. For example, we have the code below as the request object for our controller endpoint:
public class FundTransferRequest {

     private String accountTo;
     private String accountFrom;
     private String amount;

     @CustomValidator
     private String reason;

     private Metadata metadata;

}

public class Metadata {
   private String channel; //e.g. mobile, web, etc.
}

Basically @CustomValidator is our custom validator class and the logic we want is, if the supplied channel from Metadata is "WEB". The field "reason" of the request won't be required. Else, it will be required.
Is there a way to do this? I've done additional research and can't see any that handles this type of scenario.

A: Obviously if you need access to multiple fields in your custom validator, you have to use a class-level annotation.
The same very article you mentioned has an example of that: https://www.baeldung.com/spring-mvc-custom-validator#custom-class-level-validation
In your case it might look something like this:
@Constraint(validatedBy = CustomValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomValidation {

    String message() default "Reason required";
    String checkedField() default "metadata.channel";
    String checkedValue() default "WEB";
    String requiredField() default "reason";

    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

package com.example.demo;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/*
If the supplied channel from Metadata is "WEB". The field "reason" of the request won't be required.
Else, it will be required.
 */
@Component
public class CustomValidator implements ConstraintValidator<CustomValidation, Object> {
    private String checkedField;
    private String checkedValue;
    private String requiredField;

    @Override
    public void initialize(CustomValidation constraintAnnotation) {
        this.checkedField = constraintAnnotation.checkedField();
        this.checkedValue = constraintAnnotation.checkedValue();
        this.requiredField = constraintAnnotation.requiredField();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Object checkedFieldValue = new BeanWrapperImpl(value)
                .getPropertyValue(checkedField);
        Object requiredFieldValue = new BeanWrapperImpl(value)
                .getPropertyValue(requiredField);

        return checkedFieldValue != null && checkedFieldValue.equals(checkedValue) || requiredFieldValue != null;
    }
}

And the usage will be:
@CustomValidation
public class FundTransferRequest {
...

or with parameters specified:
@CustomValidation(checkedField = "metadata.channel",
        checkedValue = "WEB",
        requiredField = "reason",
        message = "Reason required")
public class FundTransferRequest {
...


text:
Q: How to redirect non-existent website from one domain to an existing website on another domain using https and http? I purchased a domain name (we'll call it "exampledomain.com"). There is no website tied to the domain and there are no plans to do so.
I want to redirect all URL variants of this domain to an existing website I also own: (we'll call it "destinationdomain.com")
If a user types any of the following, I want to redirect them to https://www.destinationdomain.com/

*

*https://exampledomain.com/

*https://www.exampledomain.com/

*http://exampledomain.com/

*http://www.exampledomain.com/
How would I set this up?
What I believe I need to do is:

*

*Add exampledomain.com as a Subject Alternative Name (SAN) to an existing SANs supported SSL I own for an existing website.

*Point IPs of exampledomain.com to the IP used by destinationdomain.com

*Add code to destinationdomain.com so that when it receives requests from the above exampledomain.com variants, it performs a 301 redirect to https://www.destimationdomain.com
POSSIBLE ALTERNATIVE?

*

*Set up domain forwarding from exampledomain.com to https://www.destinationdomain.com/

*Add exampledomain to destinationdomain.com's Subject Alternative Names (SANs)?

Is this accurate, or can I achieve this without step 3?
Thank you in advance.

A:
Point IPs of exampledomain.com to the IP used by destinationdomain.com

You need to point it somewhere. It doesn't have to be the same server as you are using for your other site. (e.g. I might do this all in AWS and use an S3 bucket to do the redirect).

Add code to destinationdomain.com so that when it receives requests from the above exampledomain.com variants, it performs a 301 redirect to https://www.destimationdomain.com

The server that you point the new domain to does need to issue a 301 redirect.
This doesn't need to be anything to do with the old domain though. Even if they are hosted on the same server, you can use Virtual Name Hosting to use separate server configurations.

Add exampledomain.com as a Subject Alternative Name (SAN) to an existing SANs supported SSL I own for an existing website.

You will need the domain in the certificate for whatever server is hosting it. If you're using the same server then setting it up as a SAN makes sense.


text:
Q: Get last record offset in kafka partition I want to get the last record offset in the topic partition. There is endOffsets method in the consumer. And usually endOffsets - 1 works fine. But in the case of transactional producer topic may contain offsets without a records. And endOffsets - 1 will point to the offset without record. So, how should I compute the last record offset in this case?
More interestingly, what if I will have both a simple and transactional producer for my topic? Is there any reliable way to get the last record offset ignoring all this complexity?

A: I ended up realizing that there is no reliable and simple way to do that in the current version of the java consumer. I created a feature request for that in Kafka's issue tracker: https://issues.apache.org/jira/browse/KAFKA-10009


text:
Q: iPhone app that responds when running in background I know that you can for example play music in you app and it would be running in background but it looks like it's not working. I've this code when my application starts on iPhone:
pathToAudio = [[NSBundle mainBundle] pathForResource:@"silence" ofType:@"mp3"];
audioURL = [NSURL fileURLWithPath:pathToAudio];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:NULL];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:NULL];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];

Result is that it plays music when I send app to background but other activities doesnt run. For example in my app I'm listening to socket and although music plays in background my app doesnt respond to incomming messages (it normally responds when app is in foreground). What do I do wrong? I've read that you can do other activities when playing music when app is in background but it looks like it doesn't work...
Edit: I have jailbroken iPhone so any unconventional methods are welcome. I know that Apple would reject my app if I was playing silent audio in background and I dont care about it. I just want to know how to make app running in background when playing music or in any other way... Maybe I need to have iPhone 4? I have iPhone 3G.

A: Nothing, it's only possible to run audio in background (aside with some special cases like geoloc notifs & VoIP), not other stuff.

A: You'll need to provide a specification for the info.plist file like the UIBackgroundModes.


text:
Q: Замена надписи в dropdown Bootstrap 4 Есть combobox выполненный средствами bootstrap 4, типа:

  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Корпоратив
  </button>

    Корпоратив
    Банкет
    Свадьба
    Другое

Вопросы

*

*Как сделать так, чтобы после выбора элемента изменялась надпись в комбобоксе? На примере выше, если я выбираю, допустим, "Банкет". Комбобокс должен закрыться, и вместо изначальной надписи "Корпоратив" должна стать надпись "Банкет".

*Выбранное значение мне нужно передавать в качестве поля формы - что и откуда будет передаваться?
ADD: Может имеет смысл просто использовать <select> и его немного переоформить?

A: Dropdown это не ComboBox. Dropdown предназначен скорее для выбора пункта меню, а для выбора значения поля обычно используют select. См. The "select" Element Для придания ему бутстраповского внешнего вида используйте класс form-control.


text:
Q: Laravel with Docker issue connecting MySQL Steps I follow to setup Laravel using Docker: in my local system I don't have  installed PHP, Composer, Apache, MySQL, phpMyAdmin, etc. I only have Git and Docker install in my system.

*

*git clone https://github.com/laravel/laravel.git

*create docker-composer.yml file on project root.
version: "3"
services:
  db:
  image: mysql:5.7
  environment:
    MYSQL_ROOT_PASSWORD: pass
    MYSQL_DATABASE: db
    MYSQL_USER: root
    MYSQL_PASSWORD: pass
  ports:
    - "3306:3306"

web:
  image: php:7.2.2-apache
  container_name: web_laravel
  depends_on:
    - db
  volumes:
    - ./:/var/www/html/
  ports:
    - "4000:80"
  stdin_open: true
  tty: true

phpmyadmin:
  image: phpmyadmin/phpmyadmin
  depends_on:
    - db
  external_links:
    - db:mysql
  ports:
    - "9191:80"
  environment:
    MYSQL_USER: root
    MYSQL_PASSWORD: pass
    MYSQL_ROOT_PASSWORD: pass
    PMA_HOST: db

*run command from project root.
docker-compose up

This command will fetch all the images (php:7.2.2-apache, phpmyadmin/phpmyadmin, mysql:5.7) from local cache or Docker Hub and start three containers for these images.
Now I need to interact with php:7.2.2-apache image's container called web_laravel (see in yml file) so I can add PHP extensions and Composer to run Laravel project.

*run this command.
docker exec -it web_laravel /bin/bash

Now I have access to run any command in running web_laravel container so I've installed Composer and PHP extensions like mbstrings, pdo, pdo_mysql etc.
Then install Laravel dependency using composer install, set permission for storage and bootstrap/cache folders and run php artisan key:generate.
open localhost:4000 and I'm able to see Laravel home page:

At this point all is good. The problem starts now when I'm connecting to my DB.
Next command to run (I'm still within container):
  php artisan migrate

and the errors are:
 Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = blog and table_name = migrations)

 Illuminate\Database\QueryException  : could not find driver (SQL: select * from information_schema.tables where table_schema = blog and table_name = migrations)

I'm able to open phpMyAdmin (http://localhost:9191) and can create DB, table and operations related DB. I've DB called blog.
MySQL env variables:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=pass

A: I think you have a couple of issues, the first is that laravel .env configuration should point to the MySQL container, not localhost
DB_HOST=127.0.0.1
should be
DB_HOST=db
And the other error you talked about, is not related to Docker

Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] No such
  file or directory (SQL: select * from information_schema.tables where
  table_schema = blog and table_name = migrations)
Illuminate\Database\QueryException  : could not find driver (SQL:
  select * from information_schema.tables where table_schema = blog and
  table_name = migrations)

it's probably related to a missing dependency, you should run
composer require doctrine/dbal
Also, you said:

now I have access to run any command in running web_laravel container
  so I've installed composer and php extensions like mbstrings, pdo,
  pdo_mysql etc.

You should build your image on top of PHP 7/Apache image, and add those to the build dockerfile, because your changes (php extensions, configurations...etc) are not persistent. I would suggest you use Laradock or any other existing Laravel/docker environment.

A: try DB_HOST=host.docker.internal

Inside docker-compose.yml
 environment:
      - DB_HOST=host.docker.internal

Works also.

A: In my Docker-compose.yml, I added this:
phpmyadmin:
        image: 'phpmyadmin/phpmyadmin'
        links:
            - mysql:mysql
        ports:
            - 8080:80
        environment:
            MYSQL_USERNAME: "${DB_USERNAME}"
            MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
            PMA_HOST: mysql
        networks:
            - sail

In my Laravel Env:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=teram_a_notificationdemo
DB_USERNAME=sail
DB_PASSWORD=password

You have to change DB_HOST=mysql to DB_HOST=127.0.0.1


text:
Q: cfc remote method result wrapped up in wddxpacket When I return a string from my remote method from cfc. The returned string is wrapped up in a strange wddxpacket:

I tried to turn off the debugging output like this:
<cfsetting showDebugOutput="no">

But it didn't work.

A: set returnformat to plain or json in the remote <cffunction>
see: http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7f5c.html


text:
Q: How to store list of objects in floor? I'm using the floor as a local database and I want to store this object after running the build_runner command it gives me this error
The column type is not supported for List?.
I know that I should use foreign keys but I don't know How can I use them in this situation.
any ideas, please?
@entity
    @JsonSerializable()
    class SalesOrder extends BaseResponse<SalesOrder> {
      @PrimaryKey(autoGenerate: true)
      int? salesId;
      String? salesCode;
      String? clientName;
      int? salesOrderTypeId;
      int? clientId;
      int? branchId;
      int? agentId;
      int? representativeId;
      int? storeId;
      int? priorityTypeId;
      int? paymentTermId;
      String? salesDate;
      String? salesTime;
      int? salesOrderStatusId;
      int? salesOrderSourceId;
      double? latitude;
      double? longitude;
      double? itemTotal;
      double? itemDiscountTotal;
      double? taxTotal;
      double? cashDiscountTotal;
      double? customDiscountTotal;
      double? deliveryTotal;
      double? netTotal;
      String? notes;
      int? invoiceRetry;
      bool? hasError;
      bool? isInvoiced;
      String? invoiceCode;
      String? invoiceDate;
      int? recId;
      int? cBy;
      String? cDate;
      int? eBy;
      String? eDate;
      List<SalesOrderDetail>? salesOrderDetails;
      List<SalesOrderError>? salesOrderErrors;

    }


text:
Q: How to prevent notification icon in shade from disappearing when put application in background In my android app I am using notification service (NotificationManagerCompat). My problem is when I get more then one notification, I see them in the shade, but when I put my application in the background, all the notifications in the shade disappear.
How do I prevent them from disappearing, and keep them in the shade while my app is moving from the foreground to the background?
Here is my code example:
Intent pushHanlderActivityIntent = new Intent(this, PushHandlerActivity.class);
        pushHanlderActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pushHanlderActivityIntent.putExtra(PUSH_BUNDLE, extras);
        pushHanlderActivityIntent.putExtra(START_IN_BACKGROUND, true);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, pushHanlderActivityIntent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_1_ID)
                .setSmallIcon(R.drawable.clalit_notification)
                .setContentTitle(title)
                .setContentText(message)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManager1 = NotificationManagerCompat.from(getApplicationContext());
        //show the notification in shade
        int random = (int)(Math.random() * 50 + 1);

        notificationManager1.notify(random,builder.build());


text:
Q: Twitter feed doesn't work over HTTPS We recently installed a SSL certificate on our website, all content must be over HTTPS since the whole site runs on SSL.
We have the following twitter feed which gets built in the code behind and then passed to the view.
sb.Append("
Tweets by @pageName");

Now before this use to be http://twitter..... which worked perfectly, but now we have the SSL it needs to be HTTPS which I have done, but it no longer shows the feed on the page? I'm unfamiliar with the twitter feed so I'm curious to find out what I'm doing wrong here?
** Update **
The suggestion below i.e changing https:// to // worked on staging, but doesn't work when I put the site live! can anyone suggest anything else?

A: Could this be because the browser does not show unsecure content when the page is loaded over https?
Try changing to a protocol relative URL, e.g. start the URL with '//' instead of 'https://'


text:
Q: Print last element of each row How can one print the element after the last tab in a file?
Exemple: File1
A    3    8    6    7
B    4    6    2    3    6    8
c    1    9

would return:
7
8
9

A: If you want the last field only and not both first and last, you could try:
rev file | cut -f 1

The rev reverses each line of the file and the cut prints only the first field (fields are defined by tabs by default). Since the line has been reversed, the first field is the original last field.
The above works in your given example but, as @Bernhard points out below, it will print fields that are longer than a single character reversed. In those cases, you will need a second rev:
 rev file | cut -f 1 | rev

A: You can use sed for such operation:
sed 's/.* //' file # where ' ' -- is your delimiter

It will delete all symbols before the delimiter. If your file is tab-separated, use:
sed 's/.*\t//' file

A: Bernhard's answer is the correct one. For fun and completeness, bash:
while read -a fields; do
    echo ${fields[-1]}
done < file

A: You can make smart use of the NF variable in awk
awk '{print $NF}' File1

From man awk

NF          The number of fields in the current input record.

So NF will give you the amount of fields and $NF will then expand to $3 for example, which you can use in a print statement.

A: awk is really the tool for the job here but for the sake of completeness here's a GNU grep way
grep -oE '[^[:space:]]+$' file
7
8
9


text:
Q: return multidimensional JSON from mysql I'm trying to get a list of temperature data from my MYSQL database.
data format is like:
masterid - beerline - temperature - temperaturetime
4000       1              20        2018-02-12 15:59
4000       1              22        2018-02-12 16:59
4001       1              20        2018-02-12 15:59
4001       1              22        2018-02-12 16:59
4002       1              20        2018-02-12 15:59
4002       1              22        2018-02-12 16:59

what i would like to do is group these into JSON arrays by the masterid
so i would here get 3 different arrays that i can return with the same JSON output.
it would look something like (i know this is not correct but need some help)
    {"4000":{"date":"2018-02-12 15:59","beerline":"1","temperature":"20"},
             {"date":"2018-02-12 16:59","beerline":"1","temperature":"22"}
   },{"4001":{"date":"2018-02-12 15:59","beerline":"1","temperature":"20"},
             {"date":"2018-02-12 16:59","beerline":"1","temperature":"22"}
   },{"4002":{"date":"2018-02-12 15:59","beerline":"1","temperature":"20"},
             {"date":"2018-02-12 16:59","beerline":"1","temperature":"22"}
    }

I tried doing:
$json = array();

// prepare and bind
        $stmt = $con->prepare("SELECT MasterID,beerline, temperature, temperaturetime
        FROM temperatures
        WHERE temperatures.MasterID IN (SELECT masterdata.masterNo FROM masterdata WHERE masterdata.customerNo = ?)
        AND temperaturetime BETWEEN DATE_ADD(NOW(), INTERVAL -1 DAY) AND NOW()
        ORDER BY MasterID,temperaturetime DESC");
        $stmt->bind_param("s",$customerID);
        $stmt->execute();
        $stmt->bind_result($masterid, $beerline, $temperature, $temperaturetime);

        while ($stmt->fetch()) {
            $json[$masterid] = array(
            'date' => $temperaturetime,
            'volume' => $beerline,
            'value' => $temperature
            );
        }

This almost works, but clearly only giving me 1 entre for each master: (just ran so not same data)
{"4018":{"date":"2018-02-12 08:59:40","volume":14,"value":22.5},"4019":{"date":"2018-02-12 08:59:36","volume":14,"value":22},"4020":{"date":"2018-02-12 08:59:33","volume":14,"value":22},"4021":{"date":"2018-02-12 09:01:26","volume":14,"value":22.5}}

A: Just replace
$json[$masterid] = array(

to
$json[$masterid][] = array(

A: while ($stmt->fetch()) {
            $json[$masterid] = array(
            'date' => $temperaturetime,
            'volume' => $beerline,
            'value' => $temperature
            );
        }

Modify your above php code like below :
while ($stmt->fetch()) {

     if( !isset($json[$masterid]) )
         $json[$masterid] = array();

     $json[$masterid][] = array(
             'date' => $temperaturetime,
             'volume' => $beerline,
             'value' => $temperature
     );
}

A: Not an answer. Too long for a comment...
FWIW, I find this easier to read:
SELECT t.MasterID
     , t.beerline
     , t.temperature
     , t.temperaturetime
  FROM temperatures t
  JOIN masterdata m
    ON m.masterno = t.masterid
 WHERE m.customerNo = ?
   AND t.temperaturetime BETWEEN NOW() - INTERVAL 1 DAY AND NOW()
 ORDER
    BY t.MasterID
     , t.temperaturetime DESC

This sounds like incredibly important work by the way


text:
Q: Questions on Theon's Ladder Imagine we want to use Theon's ladder to approximate $\sqrt{3}$. The appropriate expressions are
$$x_n=x_{n-1}+y_{n-1}$$
$$y_n=x_n+2x_{n-1}$$
Rungs 6 through 10 in the approximation of $\sqrt{3}$ are
$\{\{208, 120\},\{568, 328\}, \{1552, 896\}, \{4240, 2448\}, \{11584, 6688\}\}$
a) Compute the two values in rung 11 of the ladder.
I'm assuming that all I need to do plug into the formula. So:
$x_{11}=x_{10}+y_{10}$
$x_{11}=6688+11584=18272$
$y_{11}=x_{11}+2x_{10}$
$y_{11}=18272+2(6688)=31648$
Is this correct?Part b is really what I am struggling with.
b) The figure below shows five rectangles whose dimensions correspond to rungs 6 through 10 above. That is, the lower left corner of each is at (0,0), while the upper right corners are at $(208,120),(568, 328),...,(11584,6688)$ Are any of these rectangles similar to each other? Explain, briefly, your reasoning.
All I can think is that 6688 and 120 have a gcd of 8, and the gcd of 11584 and 208 is 16. Not really sure how to articulate that this helps with the similarity of the rectangles. Thanks for the help

A: The idea is that, if you can show that the ratios of the rectangles are getting closer to $\sqrt 3$, then none of them should be similar to each other. So you need to have some way to track $\frac{y_n}{x_n}$ in each iteration.
If you try some related expressions, you might discover that tracking $y_n^2 - 3x_n^2$ actually helps you a bit. Playing with the iteration relations you will get:
$$
y_n^2 - 3x_n^2 = -2(y_{n-1}^2 - 3x_{n-1}^2).
$$
From this,
$$
\left|\left(\frac{y_n}{x_n}\right)^2-3\right| = 2\left(\frac{x_{n-1}}{x_n}\right)^2\left|\left(\frac{y_{n-1}}{x_{n-1}}\right)^2-3\right|.
$$
This leads to our assertion. Can you finish up the arguments?

A: Hint.
Calling $\lambda_n = \frac{y_n}{x_n}$ we have
$$
\lambda_n = \frac{\lambda_{n-1}+3}{\lambda_{n-1}+1}
$$
giving a sequence $\lambda_n$ with limit at
$$
\lambda = \frac{\lambda+3}{\lambda+1}\Rightarrow \lambda^2 = 3
$$


text:
Q: Position Fixed div leaving normal document flow I am trying to create a sticky sidebar as follows, the sidebar's height is greater than that of the viewport.

This is the page structure:

There is a fixed mainmenu at the top of height 54px that scrolls along with the page. I have written this code which works perfectly but the problem is that when the class "fixed-top" and "fixed-bottom" are applied it changes the width of the sidebar and moves it out of the normal document flow. Even when I change the width back to normal it still moves out of the normal flow due to which the result is not smooth. I have tried making changes to margin, translating it but none of it seems to work, I would really appreciate some help here.
Here is the code :
.stop-top{
   position:static;
    top:0px;
    bottom:auto;
}

.fixed-top{
    position:fixed;
    top:54px;
    bottom:auto;
}

.fixed-bottom{
    position:fixed;
    top:auto;
    bottom:0px;
}

.stop-bottom{
    position:relative;
    bottom:auto;
}

.hang{
    position:relative;
    bottom:auto;
}

.
 // Sidebar div
var stickySidebar = $('.sticky');
var stickyHeight = stickySidebar.height();
var stickyOffsetLeft = $('.sticky').offset().left;

var originalOffset = stickySidebar.offset().top + $('.main-menu').height();

// content__left div
var contentLeft = $('.content__left');
var contentLeftTop = contentLeft.offset().top;

// Floating menu
var mainmenu = $('.main-menu');
var mainmenuHeight = mainmenu.height();

var lastScrollTop = 0;

var onScroll = function () {

    var sidebarTop = stickySidebar.offset().top;
    var scrollTop = $(window).scrollTop();

    var stopPosition;

    //triggered on scrolling down
    if (scrollTop > lastScrollTop){

        // Bottom Position of the viewport
        var ViewportBottom = $(window).scrollTop() + $(window).height();

        // if class "fixed-top" is found while scrolling down, remove it and add "hang"
        if(stickySidebar.hasClass("fixed-top")){
            stickySidebar.removeAttr( 'style' );
            var newTop = stickySidebar.offset().top;

            stickySidebar.removeClass("fixed-top");
            stickySidebar.addClass("hang");

            // Calculate 'top' for hang class
            stickySidebar.css('top', newTop - contentLeftTop);
        }

        // if bottom of the viewport crosses the bottom of the sidebar,
        if(ViewportBottom > $('.sticky').offset().top + $('.sticky').height()){

            // Remove any added classes and instead add class "fixed-bottom"
            stickySidebar.css("top","");
            stickySidebar.removeClass("hang");
            stickySidebar.removeClass("stop-top");
            stickySidebar.removeClass("stop-bottom");
            stickySidebar.addClass("fixed-bottom");
            stickySidebar.css({"width":0.3 * stickySidebar.parent().width()});
            // stickySidebar.css({"width":0.3 * stickySidebar.parent().width(), "left":stickyOffsetLeft });
        }

        var contentLeftBottom = $('.content__left').offset().top + $('.content__left').height();

        // When bottom of the viewport crosses the bottom of the 'content__left', remove class "fixed-bottom" and add "stop-bottom"

        if(ViewportBottom > contentLeftBottom){
            stickySidebar.css('width',"");
            // stickySidebar.css('left',"");
            stickySidebar.removeClass("fixed-bottom");
            stickySidebar.addClass("stop-bottom");
            stickySidebar.css('top', contentLeft.height() - stickyHeight);
        }
    }
    else {// triggered on scrolling up

        // if class "fixed-bottom" is found while scrolling up, remove it and add "hang"
        if(stickySidebar.hasClass("fixed-bottom")){

            stickySidebar.removeAttr( 'style' );
            var newTop = stickySidebar.offset().top;
            stickySidebar.removeClass("fixed-bottom");
            stickySidebar.addClass("hang");

            // Calculate 'top' for hang class
            stickySidebar.css('top', newTop - contentLeftTop);
        }

        // When top of the viewport is less than the top of sidebar, add class "fixed-top"
        if(scrollTop + mainmenuHeight < $(".sticky").offset().top){
            stickySidebar.css("top","");
            stickySidebar.removeClass("hang");
            stickySidebar.removeClass("stop-bottom");
            stickySidebar.addClass("fixed-top");
            stickySidebar.css({"width":0.3 * stickySidebar.parent().width()});
            // stickySidebar.css({"width":0.3 * stickySidebar.parent().width(), "left":stickyOffsetLeft});
        }

        // When top of the viewport is less than top of the 'content__left', add class "stop-top"
        if(scrollTop + mainmenuHeight < contentLeftTop){
            stickySidebar.removeClass("fixed-top");
            stickySidebar.addClass("stop-top");
            stickySidebar.removeAttr( 'style' );
        }
    }
    lastScrollTop = scrollTop;
} // onScroll

$(window).on('scroll', onScroll);


text:
Q: Error In Push Notification on Distribution I have implement the push notification after create the ck.pem file on development end. But when i create on distribution end then we check the ck.pem file is correct or not.I have error show below:-
pksinghs-Mac-mini:SchoolPush pksingh$ php /Users/pksingh/Desktop/SchoolPush/simplepush.php
Warning: stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown in /Users/pksingh/Desktop/SchoolPush/simplepush.php on line 21
Warning: stream_socket_client(): Failed to enable crypto in /Users/pksingh/Desktop/SchoolPush/simplepush.php on line 21
Warning: stream_socket_client(): unable to connect to ssl://gateway.push.apple.com:2195 (Unknown error) in /Users/pksingh/Desktop/SchoolPush/simplepush.php on line 21
Failed to connect: 0
pksinghs-Mac-mini:SchoolPush pksingh$
i have ck.pem file and pushnofication.php in same folder on desktop.
Can anybody help me.

A: Find the tutorial for how to create certificate and implement notification from below link
https://www.raywenderlich.com/123862/push-notifications-tutorial
you can use below command to create certificate
so there are something wrong in creating distribution certificate
Use below command to create certificate
openssl x509 -in aps_production.cer -inform der -out PushChatCert.pem
openssl pkcs12 -nocerts -out PushChatKey.pem -in Certificates_dist.p12
cat PushChatCert.pem PushChatKey.pem > ck_dist.pem
openssl s_client -connect gateway.push.apple.com:2195 -cert PushChatCert.pem -key PushChatKey.pem
where
aps_production.cer = downloaded from developer apple
Certificates_dist.p12 = Exported from your keychain after installing aps_production.cer


text:
Q: Migrate an on-prem AD DL Group to Pure Office 365 DLs Can anyone advise if there is a way to migrate on-prem AD groups to pure Office 365.
In our environment we have a hybrid configuration which uses AD Sync to synchronize ad objects to Azure. So we have DL groups which exist in both places. What we want to be able to do is to sever the connection of the on-prem group from 365 and remove it from on-prem AD.
The reason for doing this is that we want to be able to achieve the ability of being able to delegate 365 users the ability to manage the groups. We want to avoid removing and recreating them because of the issues this causes for users with the groups cached in their suggested contacts.
Can anyone advise if this is possible and how it is done? I have searched online, but can't find anything.

A: At present there is not a way to convert an user or group synced from on-premises to a cloud only version. You would have to delete and recreate it.
There is a Uservoice item you can vote on here.

A: Yes, delete and recreate it in cloud directly is the supported way.
For example : Deleting an Office 365 mailbox in hybrid deployment
http://www.brisk-it.net/deleting-office-365-mailbox-hybrid-deployment/


text:
Q: Use a CX_Oracle SQL output to Trigger a Python Script I looking for a bit of help in producing a SQL table update checker. For example I have a SQL table on a oracle Database classing each day as a colour (Single value).
 DATE     |   Colour
 25/08/16 |   Blue
 24/08/16 |   Red
 23/08/16 |   Red
 22/08/16 |   Blue

I'm using CX_Oracle to connect with the database, but I need an output back that says whether it's a Red day or Blue day. Then I want to combine this value with an if statement that says if today = blue then run Blue.PY script else if Red run Red.PY else if null then wait 60 mins & check again.
I'm stuck on how to pull the output from CX_Oracle.

A: Your question is short on details on how a day is considered red or blue...but the basic idea would be as follows:
import cx_Oracle

conn = cx_Oracle.Connection("user/pw@tns")
cursor = conn.cursor()
cursor.execute("select TheDate from TheTable")
for theDate, in cursor:
    if theDate.day in (22, 25):
        run_script("Blue.py")
    else:
        run_script("Red.py")

The method run_script() would do whatever you needed to do to run the red or blue scripts. And the if clause would need to be adjusted to handle whatever actually makes a date red or blue.


text:
Q: How to word-wrap HTML in Mergin Input? This is a follow-up to a question that I previously asked regarding QGIS map tips in Mergin.
Based on that answer, I am trying to display a text field (location_description) in the Mergin input preview panel, using HTML.  Here's the HTML that I enter into the QGIS Layer Properties > Display > HTML Map Tip:
<h2>
[% "location_description" %]
</h2>

And here's the Mergin display, which does not wordwrap.  How can I get the contents of this text field to wordwrap?
Edit: The Mergin documentation for this topic does not mention word wrapping, leaving me to assume that it should happen by default.

A: There are multiple ways to create a line break in HTML, like style='word-break:break-all' or using <textarea>...</textarea>, but unfortunately none of them work here.
Instead you can use the QGIS expression function wordwrap:
[%  wordwrap(  "location_description" ,30) %]


text:
Q: Как указать значение в диапазоне от 50 до 150 при запросе в бд MYSQL LARAVEL? Использовал различные варианты:
->whereRaw("square BETWEEN  ? AND ?", [$from, $to])

->whereRaw("parent_id = ? AND number_floors = ? AND roof = ? AND square > ? AND square < ?",
        [$section, $floor, $roof, $from, $to])

->where([
                ['parent_id', '=', $section],
                ['from', '>', $from],
                ['to', '<', $to],
                ['number_floors', '=', $floor],
                ['roof', '=', $roof],
            ])

 DB::table('projects_store_projects')->where([
                    ['parent_id', '=', $section],
                    ['number_floors', '=', $floor],
                    ['roof', '=', $roof],
                ])->whereBetween('square', [$from, $to])
                    ->offset(0)->limit(2)->get();

Ничего не работает, если оставить одно условие, то всё правильно, а два не работают. orWhere не подходит.
Запрос на mysql
SELECT * FROM projects_store_projects WHERE square BETWEEN 50 AND 150;

A: $users = DB::table('users')
           ->whereBetween('votes', [1, 100])
           ->get();

Документация laravel 9x: https://laravel.com/docs/9.x/queries#additional-where-clauses


text:
Q: Make PNG sprites in PIL but want to preserve alpha channel I'm creating a script to grab a bunch of favicons, convert them to png and make a single sprite image out of all of them.
The helpful g.etfv.co will detect and convert favicons in PNG format, and I'm using PIL to montage the images into a sprite sheet.
It all works fine except I seem to lose the alpha transparency channel when I do this.
Resulting image from the below script: . Note the black areas that are supposed to be transparent.
Update: Now creating image in mode 'RGBA' rather than 'RGB'. Resulting image is now only partially borked: . OKCupid's icon looks correct but stackoverflow's is still losing the alpha channel.
Update: I note that it so happens that images it messes up on it reports as being RGB (not RGBA) prior to conversion.
>>> print url, img.getbands()
http://stackoverflow.com/ ('R', 'G', 'B')
http://www.google.com/ ('R', 'G', 'B')
http://blog.okcupid.com/ ('R', 'G', 'B', 'A')

What am I doing wrong?
import urllib
import PIL.Image
import StringIO

favicon_base = 'http://g.etfv.co/'

icons = """
http://stackoverflow.com/
http://www.google.com/
http://blog.okcupid.com/
"""

icons = [icon.strip() for icon in icons.strip().splitlines()]

left = 0
right = 16
upper = 0
lower = 16

inew = PIL.Image.new('RGBA',(len(icons)*16,16))

for url in icons:
    favicon = urllib.urlopen(favicon_base + urllib.quote(url) + '?defaulticon=lightpng').read()

    img = PIL.Image.open(StringIO.StringIO(favicon))
    img = img.convert('RGBA')

    bbox = (left, upper, right, lower)
    inew.paste(img, bbox, img)

    left += 16
    right += 16

inew.save(open('blah.png', 'wb'), 'png', optimize=1)

A: The result image inew has no alpha chanel.
UPDATE:
try
inew = PIL.Image.new('RGBA',(len(icons)*16,16))


text:
Q: mysql show columns for each of the tariff names I have the following table
+------------+------------------------+-------------+-------------+--------+
| dialprefix | destination            | rateinitial | tariffname  | id     |
+------------+------------------------+-------------+-------------+--------+
| 1          | North American Region  |     0.01710 | Call Center | 476610 |
| 1201       | United States          |     0.01710 | Call Center | 512642 |
| 1201       | United States          |     0.01110 | Direct      | 586007 |
| 1201       | United States          |     0.01055 | Standard    | 622786 |
| 1201       | United States          |     0.02949 | Premium     | 549254 |
| 1201763    | United States - OffNet |     0.01785 | Call Center | 499834 |
| 12017632   | United States - OffNet |     0.01785 | Call Center | 510969 |
| 12017636   | United States - OffNet |     0.01785 | Call Center | 510970 |
| 12017637   | United States - OffNet |     0.01785 | Call Center | 510971 |
| 12017638   | United States - OffNet |     0.01785 | Call Center | 510972 |
+------------+------------------------+-------------+-------------+--------+

in the tariffname column shows different names like: Call center, Direct, Premium, Standard.
what mysql query do I need to show columns for each of the tariff names and include the rate, and also remove any dialprefix duplicates and only use one to display its rate. for example:
+------------+------------------------+-------------+-------------+-------------+-------------+
| dialprefix | destination            | Call Center | Standard    | premium     | Direct      |
+------------+------------------------+-------------+-------------+-------------+-------------+
| 1201       | United States          | 0.01710     | 0.01055     | 0.02949     | 0.01110     |
+------------+------------------------+-------------+-------------+-------------+-------------+

this query is later on json encoded and passed to data tables to display data.
this is the query that i use right now:
select cc_ratecard.dialprefix, cc_prefix.destination , cc_ratecard.rateinitial, cc_tariffplan.tariffname, cc_ratecard.id
from cc_ratecard, cc_prefix, cc_tariffplan
where cc_ratecard.dialprefix = cc_prefix.prefix
and cc_tariffplan.id = cc_ratecard.idtariffplan


text:
Q: Send POST request via Fetch from frontend and handle request on backend Thank you for your time.
I am trying to build an application where I need to send a POST request from the client to the server. But I always get this same problem of request body being undefined.
On client side:
const addProblem = (e)=>{
    e.preventDefault();
    const form = document.getElementById("addForm");
    const problemLink = form.firstElementChild.value;
    const page = document.getElementById("page").innerHTML;
    const data = {
      problemLink: problemLink,
      page: page,
    };
    fetch("/addProblem", {
        method: 'POST',
        headers:{
            'Content-Type':'application/json'
        },
        body: JSON.stringify(data),
    })
    .then((res) => {console.log("done")})
    .catch((err) => console.log(err));
}
const addBtn = document.getElementById("addProbBtn");
addBtn.addEventListener('click',addProblem);

Server
//native node modules
const path = require("path");

//external node modules
const express = require("express");
const mongoose = require("mongoose");

const app = express();

const MONGODB_URI =  "hello world";

app.set("view engine", "ejs");
app.set("views", "views");

// routes
const hubRoutes = require("./routes/hub");

app.use(hubRoutes);

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));

mongoose.connect(MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(result => {
    app.listen(3000, () => {
      console.log("server started on port 3000");
    });
  })
  .catch((err) => {
    console.log(err);
  });

Routes
const express = require("express");

const router = express.Router();

const hubController = require("../controllers/hub");

router.get("/",hubController.getHub);

router.get("/dsaProblems",hubController.getDsaProblems);

router.post("/addProblem",hubController.addProblem);

module.exports = router;

I can see in the networks tab that the request is sent without an issue. The payload is exactly what I want - JSON data. But on ther server when I try to access req.body, I get undefined.
Please help! Following is the controller where I handle the request.
exports.addProblem=(req,res,next)=>{

    console.log(req.body); //request body undefined here :(
    const problemLink = req.body.problemLink;
    const page = req.body.page;
    const newProb = new Problem({
        problemLink:problemLink,
        status:false
    });
    newProb.save()
    .then(savedDoc=>{
        res.redirect(`/dsaProblems/?async=true&itemspp=10&page=${page}`)
    })
    .catch(err=>console.log(err));
}


text:
Q: Jersey matches regex pattern before the method type Is it possible to define 2 methods in Jersey with same regex but different type? (GET, PUT ..):
@GET
@Path("{key: .+}")
@Produces(MediaType.TEXT_PLAIN)
public Response root(String key) {
}

@PUT
@Path("{key: .+}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response publish(String key, FormDataMultiPart data) {
}

The first method should only reply for the key (with or without slashes)
curl -X GET "http://localhost/key
Jersey respond with 200 OK since it went to the GET method

curl -X GET "http://localhost/key/
Jersey respond with 200 OK since it went to the GET method

curl -X PUT -T file.txt "http://localhost/key
Jersey respond with 200 OK since it went to the PUT method

curl -X PUT -T file.txt "http://localhost/key/
Jersey respond with 200 OK since it went to the PUT method

curl -X PUT -T file.txt "http://localhost/key/folder/folder
Jersey respond with 405 Method Not Found since it went to the GET method
instead of the PUT (the get only respond to 1 folder level which is the 'key'
but i expected that jersey will go directly to the PUT since it suppose to check for the method type before the regex matching

Why the last one doesn't work? it seems Jersey first looks for regex even though it's a PUT request.

A: You say "Jersey respond with 405 Method Not Found since it went to the GET method instead of the PUT" but a 405 means that it didn't go to any method.  Try changing your PUT method to:
@PUT
@Path("{key: .+}")
@Produces(MediaType.TEXT_PLAIN)
public Response publish(String key) {
}

And that should work.  You then need to ensure that you provide the correct data as part of your CURL request to ensure that it matches the @Consumes annotation when you put it back in to the request.


text:
Q: How to find the count of the maximum pair of a window Today I got an interview question about finding the maximum pair window but I felt like I could solve it more efficient. I was wondering if theres any way to solve it more efficiently.
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3, n = 7
Output: 3
Explanation:
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       4 (1,3) < 7 false
 1 [3  -1  -3] 5  3  6  7       2 (3, -1) < 7 false
 1  3 [-1  -3  5] 3  6  7       4 (5, -1) < 7 false
 1  3  -1 [-3  5  3] 6  7       8 (5,3) > 7 true
 1  3  -1  -3 [5  3  6] 7       11 (6,5) > 7 true
 1  3  -1  -3  5 [3  6  7]      13 (6,7) > 7 true

just solved it by getting the subarray -> sorting then getting the last 2 element but I think theres a more efficient solution?


text:
Q: Extracting IP Address and Port Info from sockaddr_storage I'm currently working on a UDP server that receives a request from a client. The datagram I receive is a byte (char) array 5 elements long, with the final two elements being a port number.
Eventually this server will have to return both the IP address and the port number in a datagram of its own.
I already know how to use inet_ntop and the sockaddr struct I've connected with and received from to print out the ip, but it returns a string that's not in the format I want. For instance:
string1 = inet_ntop(their_addr.ss_family,get_in_addr(
    (struct sockaddr *)&their_addr),s, sizeof s);

returns:
127.0.0.1

or:
[1][2][7][.][0][.][0][.][1]

when I need something like:
[127][0][0][1]

Should I be using some sort of character and array manipulation to make my 4-element byte array? Or does a sockaddr have this information in a way that I can leave it in this hex form and return it?

A: You want to probably use getnameinfo() function:
int getnameinfo(const struct sockaddr *sa, socklen_t salen,
                   char *host, size_t hostlen,
                   char *serv, size_t servlen, int flags);

E.g.:
struct sockaddr_storage client_addr;
socklen_t client_len = sizeof(struct sockaddr_storage);

/* Accept client request */
int client_socket = accept(server_socket,
    (struct sockaddr *)&client_addr, &client_len);

char hoststr[NI_MAXHOST];
char portstr[NI_MAXSERV];

int rc = getnameinfo((struct sockaddr *)&client_addr,
    client_len, hoststr, sizeof(hoststr), portstr, sizeof(portstr),
    NI_NUMERICHOST | NI_NUMERICSERV);

if (rc == 0)
    printf("New connection from %s %s", hoststr, portstr);

A: Assuming for IPv4.
After taking the address of your sockaddr_storage or sockaddr structure and casting it to the IPv4 version sockaddr_in, you can then access the individual bytes of the IPv4 address.
struct sockaddr_in *sin = (struct sockaddr_in *)&their_addr;

Then you can take address of the s_addr member which is a 32 bit value (in_addr_t) that holds the 4 bytes of the ip address (in network byte order) and cast it to a pointer to an unsigned char which then lets you access the individual bytes of the value.
unsigned char *ip = (unsigned char *)&sin->sin_addr.s_addr;

printf("%d %d %d %d\n", ip[0], ip[1], ip[2], ip[3]);

A: Here is a simple immutable class I used for the same purpose you mentioned in your question:

class address_t {

private:
    uint16_t m_Port = 0;
    std::string m_Ip = "";

public:
    address_t(const sockaddr_in & address) {
        m_Ip = inet_ntoa(address.sin_addr);
        m_Port = ntohs(address.sin_port);
    }

    uint16_t GetPort() const { return m_Port; }
    std::string GetIp() const { return m_Ip; }
    std::string ToString() const {
        return "IP: " + m_Ip + ", Port: " + std::to_string(m_Port);
    }
};


text:
Q: "None of your accounts are a member of XXXXX" trying to set an app group I've developed an app for a customer who has their own Apple account and profiles etc.
They have given me their development profiles and dev keychain certificate and want me to deliver the app to them signed with their dev profiles which they will then replace with app store distribution profiles.
I'm having a problem adding an app group to the capabilities. When I click on the + button to add an app group I get the following error:

This is the signing settings. When their developer provisioning profile was imported as the signing profile XCode set the Team to "Unknown Name (XXXXX)" so it must have pulled that team name from the profile.

In XCode's accounts I only have my own Apple IDs added, I don't have their Apple ID added (its not possible to without knowing their password though?, something I won't get). I presume this might be why I am getting that error code?
Is there anyway of adding the group id to the project without having to add their Apple ID to XCode's account section?

A:
They have given me their development profiles and dev keychain certificate and want me to deliver the app to them signed with their dev profiles which they will then replace with app store distribution profiles

That whole approach is mistaken (as you now know). They have two choices:

*

*You can just develop the app under your own banner, making all your own profiles as needed, and they can make all the necessary substitutions and other changes at their end when they have the code. Or:

*They must make you formally a member of their team (e.g. an Admin), at least while you're working on the app.


text:
Q: Handling final page in Python paginated API request I'm requesting Microsoft's Graph API, where I'm using the following function to request multiple pages. I'm trying to request all pages, merge the json files and finally write them to a pandas dataframe.
v = "v1.0"
r = "/users?$filter=userType eq 'Member'&$select=displayName,givenName,jobTitle,mail,department&$top=200"

def query(v, r):
    all_records = []
    url = uri.format(v=v, r=r)

    while True:
        if not url:
            break
        result = requests.get(url, headers=headers)
        if result.status_code == 200:
            json_data = json.loads(result.text)
            all_records = all_records + json_data["value"]
            url = json_data["@odata.nextLink"]
    return all_records

The while-loop goes through all the pages, but when I run the function I'm getting a error:
KeyError: '@odata.nextLink'

I assume this is because the loop reaches the final page, and thus the '@odata.nextLink' cannot be found. But how can I handle this?

A: You are doing
url = json_data["@odata.nextLink"]

which suggest json_data is dict, so you should be able to use .get method which returns default value when key not found (None by default), please try doing following and write if it does work as excepted:
url = json_data.get("@odata.nextLink")
if url is None:
    print("nextLink not found")
else:
    print("nextLink found")


text:
Q: ConstraintLayout not changing to landscape I am a begginer in android. So I created an small android app using ConstraintLayout, just to test. But, everytime I click on the button to change the orientation of the screen on the emulator, it´s not changing, it continues the same. As far as I remember, with linear layout, the orientation change, but it breaks the layout if you not handle well with it. But with ConstraintLayout, it always continue the same
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".view.MainActivity">
    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" tools:srcCompat="@tools:sample/avatars[0]"
            android:id="@+id/imageView"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="120dp"
            android:layout_marginStart="120dp" app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginEnd="120dp"
            android:layout_marginRight="120dp" android:layout_marginTop="28dp"
            app:layout_constraintTop_toTopOf="parent" app:layout_constraintHorizontal_bias="0.497"
            android:layout_marginBottom="497dp" app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintVertical_bias="0.0"/>

    <TextView
            android:text="Get Rewarded with this"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:id="@+id/textView" android:layout_marginTop="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginEnd="32dp" android:layout_marginRight="32dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="33dp"
            android:layout_marginStart="33dp"
            android:fontFamily="sans-serif-light" android:lineSpacingMultiplier="40"
            android:lineSpacingExtra="40sp"
            android:textSize="32dp"`enter code here`
            android:layout_marginBottom="378dp" app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imageView"/>
</androidx.constraintlayout.widget.ConstraintLayout>

A: You can just make individual layout for landscape view. That way:
https://i.stack.imgur.com/4Adij.png
https://i.stack.imgur.com/xmIva.png
https://i.stack.imgur.com/EBzCX.png


text:
Q: Бизнес-логика для работы с SOAP-запросами на Python Мне нужно отправлять запросы SOAP-сервису и получать ответы.
Запросы выглядят так:
vpuStatus = '''
<vpuStatus version="1.0">
    <fromDate value="01.06.2018"/>
    <toDate value="18.06.2018"/>
    <OperId value=""/>
    <CustomResult value=""/>
</vpuStatus>'''

А ответы приходят в таком формате:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <NS1:GetBlockResponse xmlns:NS1="SysEtranInt">
         <return xsi:type="xsd:boolean">true</return>
         <Text xsi:type="xsd:string"><?xml version="1.0" encoding="windows-1251"?>
<error>
<errorCode value="4"/>
<errorMessage value="Накладная с ID=1 не найдена или у Вас нет прав доступа к данному документу."/>
<errorStatusCode value="404"/>
</error></Text>
      </NS1:GetBlockResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Чем удобнее всего организовать общение с сервисом на питоне? Желательно написать высокоуровневую бизнес-логику, которая будет формировать нужный xml с требуемыми данными, делать запрос и возвращать высокоуровневое (удобное) представление ответа.
Сейчас мы решили использовать zeep для общения с сервисом и xmltodict для конвертирования xml в dict. XML-запросы до сих пор формирую руками. Каким инструментов можно их формировать? Какие структуры данных использовать для работы с ответами?


text:
Q: How to read/write/sync data on cloud with Kedro In short: how can I save a file both locally AND on cloud, similarly how to set to read from local.
Longer description: There are two scenario, 1) building model 2) serving model through API. In building the model, a series of analysis is done to generate feature and model. The result will be written locally. At the end everything will be uploaded to S3. For serving the data, first all required files which are generated from the first step, will be downloaded.
I am curious how I can leverage Kedro here. Perhaps I can define two entries for each file conf/base/catalog.yml one corresponds to the local version and the second for the S3. But perhaps not the most efficient way when I am dealing with 20 files.
Alternatively, I can upload the files using my own script to S3 and exclude the synchronization from Kedro ! in otherwords, Kedro is blind from the fact that there are copies exist on the cloud. Perhaps this approach is not the most Kedro-friendly way.

A: Not quite the same, but my answer here could potentially be useful.
I would suggest that the simplest approach in your case is indeed defining two catalog entries and having Kedro save to both of them (and load from the local one for additional speed up) which gives you the ultimate flexibility, though I do admit isn't the prettiest.
In terms of avoiding all your node functions needing to return two values, I'd suggest applying a decorator to certain nodes that you tag with a certain tag, e.g tags=["s3_replica"] taking inspiration from the below script (stolen from a colleague of mine):
class S3DataReplicationHook:
    """
    Hook to replicate the output of any node tagged with `s3_replica` to S3.

    E.g. if a node is defined as:
        node(
            func=myfunction,
            inputs=['ds1', 'ds2'],
            outputs=['ds3', 'ds4'],
            tags=['tag1', 's3_replica']
        )

    Then the hook will expect to see `ds3.s3` and `ds4.s3` in the catalog.
    """

    @hook_impl
    def before_node_run(
        self,
        node: Node,
        catalog: DataCatalog,
        inputs: Dict[str, Any],
        is_async: bool,
        run_id: str,
    ) -> None:
        if "s3_replica" in node.tags:
            node.func = _duplicate_outputs(node.func)
            node.outputs = _add_local_s3_outputs(node.outputs)

def _duplicate_outputs(func: Callable) -> Callable:
    def wrapped(*args, **kwargs):
        outputs = func(*args, **kwargs)
        return (outputs,) + (outputs,)

    return wrapped

def _add_local_s3_outputs(outputs: List[str]) -> List[str]:
    return outputs + [f'{o}.s3' for o in outputs]

The above is a hook, so you'd place it in your hooks.py file (or wherever you want) in your project and then import it into your settings.py file and put:
from .hooks import ProjectHooks, S3DataReplicationHook

hooks = (ProjectHooks(), S3DataReplicatonHook())

in your settings.py.
You can be slightly cleverer with your output naming convention so that it only replicates certain outputs (for example, maybe you agree that all catalog entries that end with .local also have to have a corresponding .s3 entry and you mutate the outputs of your node in that hook accordingly, rather than do it for every output.
If you wanted to be even cleverer, you could inject the corresponding S3 entry into the catalog using a after_catalog_created hook rather than manually writing the S3-versioon of the dataset in your catalog, again, as per a naming convention you choose. Though I'd argue that writing the S3 entries is more readable in the long-run.

A: There are 2 ways I can think of. A simpler approach is to use --env conf for both cloud and local. https://kedro.readthedocs.io/en/latest/04_kedro_project_setup/02_configuration.html#additional-configuration-environments
conf
├── base
│   └──
├── cloud
│   └── catalog.yml
└── my_local_env
    └── catalog.yml

And you can call kedro run --env=cloud or kedro run --env=my_local depending on which env you want to use.
Another more advanced way is to use TemplatedConfigLoader https://kedro.readthedocs.io/en/stable/kedro.config.TemplatedConfigLoader.html
conf
├── base
│   └── catalog.yml
├── cloud
│   └── globals.yml (contains `base_path:s3-prefix-path`)
└── my_local
    └── globals.yml (contains `base_path:my_local_path`)

In catalog.yml, you can refer to base_path like this
my_dataset:
    filepath: s3:${base_path}/my_dataset

And you can call kedro run --env=cloud or kedro run --env=my_local depending on which env you want to use.


text:
Q: How to make a table two row in one column I want to have a table like you see in the picture.

But I am really unsuccessful in this.
here is my code:

table,
td,
th {
  border: 1px solid black;
}

table {
  width: 100%;
  border-collapse: collapse;
}

    SOL
    K
    Y
    M

      b
      a1

    b
    b

Could you please help me on this?

A: Here's the solution

table {
  width: 100%;
  border-collapse: collapse;
}

table,
th,
td {
  border: 1px solid lightgray;
  font-family: sans-serif;
  padding: 7px 15px;
}

      SOL
      K
      Y
      M

      a1

      1
      a2

      b1

      b2


text:
Q: Magento 2 does not allow Special characters in First Name & Last name even though the Input Validation is None In my magento setup I am not able to insert special characters for customer First name and Last name.
The Input Validation for Customer Attribute First Name and Last Name is NONE.
But still Magento 2 not allowing me to insert special characters for customer First name and Last name.
I also checked in a fresh magento 2 installation setup and there I am able to insert special characters.
Please help. I am using Magento 2.4.2
Customer Attribute configurations:

Frontend - Create Account:

A: In \Magento\Customer\Model\Validator\Name::isValidName
Magento matches the first name of the customer with the regex pattern
private const PATTERN_NAME = '/(?:[\p{L}\p{M}\,\-\_\.\'\s\d]){1,255}+/u';
 /**
 * Check if name field is valid.
 *
 * @param string|null $nameValue
 * @return bool
 */
private function isValidName($nameValue)
{
    if ($nameValue != null) {
        if (preg_match(self::PATTERN_NAME, $nameValue, $matches)) {
            return $matches[0] == $nameValue;
        }
    }

    return true;
}

A: where can I find \Magento\Customer\Model\Validator\Name::isValidName to edit the private const PATTERN_NAME?
Regards


text:
Q: java exception code error drag and drop There is an error in this code. The code should not rewrite the path of the file obtained by dragging if it already exists. Could you help me please? I'm implementing drag and drop. The original file
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.util.List;
import java.util.StringTokenizer;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;

public class Main extends JFrame implements DropTargetListener {

  DropTarget dt;

  JTextArea ta = new JTextArea();

  public Main() {
    super("Drop Test");
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    add(new JLabel("Drop a list from your file chooser here:"), BorderLayout.NORTH);
    ta.setBackground(Color.white);
    getContentPane().add(ta, BorderLayout.CENTER);

    dt = new DropTarget(ta, this);
    setVisible(true);
  }

  public void dragEnter(DropTargetDragEvent dtde) {
//      System.out.println("Drag Enter");
  }

  public void dragExit(DropTargetEvent dte) {
//      System.out.println("Source: " + dte.getSource());
//      System.out.println("Drag Exit");
  }

  public void dragOver(DropTargetDragEvent dtde) {
//      System.out.println("Drag Over");
  }

  public void dropActionChanged(DropTargetDragEvent dtde) {
//      System.out.println("Drop Action Changed");
  }

public void drop(DropTargetDropEvent dtde) {
      try {
          Transferable tr = dtde.getTransferable();
          DataFlavor[] flavors = tr.getTransferDataFlavors();
          for (int i = 0; i < flavors.length; i++) {
            System.out.println("Possible flavor: " + flavors[i].getMimeType());
            if (flavors[i].isFlavorJavaFileListType()) {
              dtde.acceptDrop(DnDConstants.ACTION_COPY);

             // ta.setText("Successful file list drop.\n\n");

              //System.out.println("---"+ta.getText());
              java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
              for (int j = 0; j < list.size(); j++) {
                  StringTokenizer st = new StringTokenizer(ta.getText(), "\n");
                  ta.append(list.get(j) + "\n");

              }

            }

              dtde.dropComplete(true);
              return;

          }
          System.out.println("Drop failed: " + dtde);
          dtde.rejectDrop();
        } catch (Exception e) {
          e.printStackTrace();
          dtde.rejectDrop();
        }
      }

  public static void main(String args[]) {
    new Main();
  }
}

A: This is where a single exit point to a method would have helped you...
Let's strip out some code and have a closer look...
public void drop(DropTargetDropEvent dtde) {
    try {
        Transferable tr = dtde.getTransferable();
        DataFlavor[] flavors = tr.getTransferDataFlavors();
        for (int i = 0; i < flavors.length; i++) {
            System.out.println("Possible flavor: " + flavors[i].getMimeType());
            if (flavors[i].isFlavorJavaFileListType()) {
                //...
            }
            // !!!
            dtde.dropComplete(true);
            return;
            // !!!
        }
        System.out.println("Drop failed: " + dtde);
        dtde.rejectDrop();
    } catch (Exception e) {
        e.printStackTrace();
        dtde.rejectDrop();
    }
}

Basically, when you're looping through all the available DataFlavors, you immediately accept the drop and return on the first one.
So, if instead, we move those lines to within the if statement
public void drop(DropTargetDropEvent dtde) {
    try {
        Transferable tr = dtde.getTransferable();
        DataFlavor[] flavors = tr.getTransferDataFlavors();
        for (int i = 0; i < flavors.length; i++) {
            System.out.println("Possible flavor: " + flavors[i].getMimeType());
            if (flavors[i].isFlavorJavaFileListType()) {
                dtde.acceptDrop(DnDConstants.ACTION_COPY);

                // ta.setText("Successful file list drop.\n\n");
                //System.out.println("---"+ta.getText());
                java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
                for (int j = 0; j < list.size(); j++) {
                    StringTokenizer st = new StringTokenizer(ta.getText(), "\n");
                    ta.append(list.get(j) + "\n");

                }
                dtde.dropComplete(true);
                return;

            }

        }
        System.out.println("Drop failed: " + dtde);
        dtde.rejectDrop();
    } catch (Exception e) {
        e.printStackTrace();
        dtde.rejectDrop();
    }
}

it will start working.
We could, however, simplify the code a little by making better use of the available functionality, for example...
public void drop(DropTargetDropEvent dtde) {
    try {
        Transferable tr = dtde.getTransferable();
        if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
            dtde.acceptDrop(DnDConstants.ACTION_COPY);
            List files = (List) tr.getTransferData(DataFlavor.javaFileListFlavor);
            for (Object obj : files) {
                ta.append(obj + "\n");
            }
            dtde.dropComplete(true);
        } else {
            System.out.println("Drop failed: " + dtde);
            dtde.rejectDrop();
        }
    } catch (Exception e) {
        e.printStackTrace();
        dtde.rejectDrop();
    }
}


text:
Q: 'super' object does not support item assignment Alguien puede ayudarme con este error en Django con python 2.7. Estoy tratando con este codigo implementar un calendario.
Estoy teniendo un error en la variable context['calendar'] = mark_safe(html_cal)
Nose que estoy haciendo mal.
 from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
from django.views import generic
from django.utils.safestring import mark_safe

from .models import *
from .utils import Calendar

class CalendarView(generic.ListView):
    model = Event
    template_name = 'agendas/templates/calendar.html'

def get_context_data(self, **kwargs):
    context = super(CalendarView,self)

    # use today's date for the calendar
    d = get_date(self.request.GET.get('day', None))

    # Instantiate our calendar class with today's year and date
    cal = Calendar(d.year, d.month)

    # Call the formatmonth method, which returns our calendar as a table
    html_cal = cal.formatmonth(withyear=True)
    context['calendar'] = mark_safe(html_cal)
    return context

def get_date(req_day):
    if req_day:
        year, month = (int(x) for x in req_day.split('-'))
        return date(year, month, day=1)
    return datetime.datetime.today()

El error en el log de Django
    'super' object does not support item assignment
    context['calendar'] = mark_safe(html_cal)

Aqui esta descrito la variable context.
<super: <class 'CalendarView'>, <CalendarView object>>
d   datetime.datetime(2020, 3, 25, 23, 26, 52, 368050)
self    <comutechapps.agendas.views.CalendarView object at 0x7fbb7d6d0250>
cal     <comutechapps.agendas.utils.Calendar object at 0x7fbb79e94a90>
html_cal    '<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n{self.formatmonthname(self.year, self.month, withyear=withyear)}\n{self.formatweekheader()}\n{self.formatweek(week, events)}\n{self.formatweek(week, events)}\n{self.formatweek(week, events)}\n{self.formatweek(week, events)}\n{self.formatweek(week, events)}\n{self.formatweek(week, events)}\n'
kwargs {}

A: El error está en la línea:
context = super(CalendarView,self)

super devuelve un objeto proxy que delega llamadas de método a una clase padre siguiendo el MRO. No es la clase misma. En tu caso contex por tanto es simplemente un objeto tipo super, por lo que cuando posteriormente haces:
context['calendar'] = mark_safe(html_cal)

intentas asignar a la clave calendar y super no es ningún contenedor que defina el método __getitem__ como es dict, por lo que tienes el error mencionado.
El problema es que te falta la llamada al método de la clase padre:
context = super().get_context_data(**kwargs)

o si aún usas Python 2.x:
context = super(CalendarView, self).get_context_data(**kwargs)


text:
Q: How to soft delete functionality in neo4j? In relational databases like mysql I was used to do soft delete by setting deleted_at.  And then for retrieving SELECT just get rows WHERE deleted_at IS NULL.
I am confused how to implement soft delete in neo4j database. There are multiple ways I am getting but not sure which method or combination will have more advantages.
I also read Neo4j: implementing soft delete with optional relationships but not helping.

*

*Just set property of node deleted_at.

*Remove node label and change by prefix "_" like "Student" will become "_Student"

*Remove relationship and change by prefix "_" like "TEACHES" will become "_TEACHES"

Which will be best way or combination or other way to achieve soft delete in neo4j?

A: Which way is the best way will be debatable.  If you don't need the actual date of soft delete, then you can just apply/remove a label as necessary:
Mark as "soft deleted":
match (a {name: "foo"}) set a:deleted return a;

Unmark:
match (a {name: "foo"}) remove a:deleted return a;

If you need to assert properties about the soft delete, then it makes sense to model it as a node (e.g. a "soft deletion event") and then link it to the node via a relationship.  The nodes that are deleted then are any nodes of a certain type that have a "DELETED" relationship that goes to a soft-delete node.  That soft delete node would then have a deleted_at property, along with anything else about the deletion event you're modeling.
I don't think a simple deleted_at property in the node is as good of a solution, because it confuses the node information with the information about the deletion event.  I would argue you're trying to model a deletion event here.

A: I think have a deleted_at property for node. In which you can store deleted time-stamp.
And at the time of fetching nodes information you can check deleted_at IS NULL.
like -
  MATCH (n:node)
  WHERE n.deleted_at IS NULL
  RETURN n;

Storing time-stamp you can get when node is deleted.
You can also have relationship deleted_by between user who deleted the node. So that you can find out who deleted node.


text:
Q: Getting the Variable for a chosen Application Apple Script I want to do a simple AppleScript Script, that opens an App Chooser and gets the selected App.
choose application with prompt "Choose an App:"

So it opens a Window where I can choose an App. In the next line I do:
activate application "Safari"

How can I write it so it opens the SELECTED App?
like activate application SelectedApp
Thanks in advance :)

A: Here you go:
set theApp to choose application with prompt "Choose an App:"
tell theApp
    activate
end tell


text:
Q: Github API: Mulitple parameters not Working ENVIRONMENT: Ubuntu 20.04
TASK: Mine all closed bug reports (issues) with the label 'incorrect' from the repository Ansible.
SOLUTIONS: I have tried using Github's REST API via the curl command. However, curl is either stalling or simply producing a server error. I have not seen much usage of how to include multiple parameters or working with large requests even from the documentation
First thing I tried was to mine just the closed issues, below mines all the closed issues or so it seems. It looks like it only includes a couple which leads me to think there are 'pages' to large requests?
 curl "https://api.github.com/repos/ansible/ansible/issues?state=closed" > closed_issues

However the 'labels' is not working for me neither is combining the two. I get a "server_error" and it stops there.
curl "https://api.github.com/repos/ansible/ansible/issues?state=closed&labels=incorrect" > labeled_closed_issues


text:
Q: Why am I unable to see a folder in a ntfs formated drive I am running ubuntu 12.04. My problem: In a ntfs formatted disk I have created one folder and stored some files. Now it is showing nothing in that drive. But if I check the size of the disk there is still some space used. How can I get into that folder now.

A: May be similar to reported bug Data saved to a fuseblk (Windows NTFS) file system is silently lost


text:
Q: VBA Change Sourcedata Line Color Trying to change the line of my fullseries sourcedata rangey3.
I tried using:
.Format.Line.ForeColor.RGB = RGB(56, 182, 75)
.MarkerBackgroundColor = RGB(56, 182, 75)

to no avail but it does work for the forecasted values.
My code is:
ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
With ActiveChart
.SetSourceData Source:=rangey3
' Must have this as we will be using different series inside of this chart from here on out
.FullSeriesCollection(1).Name = "Demand"
' This is the first series of the full series collection
.SeriesCollection(1).XValues = rangex
.SeriesCollection.NewSeries
' Creates legend at the bottom of the chart
.SetElement (msoElementLegendBottom)
' Deletes the chart title as per the illustration in Assignment 2's illustration screenshot
.ChartTitle.Delete

' Creates the line Demand (Forecast)
With .SeriesCollection(2)
    .Name = "Demand (Forecast)"
    .Values = rangey2
    .Format.Line.Visible = msoTrue
    ' Makes the forecast line distinguishable by dotting it
    .Format.Line.DashStyle = msoLineSysDot
    .Format.Line.ForeColor.RGB = RGB(56, 182, 75)
    .MarkerBackgroundColor = RGB(56, 182, 75)
End With

A: Use for each statement.
Dim Srs As Series

ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select
With ActiveChart
    .SetSourceData Source:=rangey3
    ' Must have this as we will be using different series inside of this chart from here on out
    .FullSeriesCollection(1).Name = "Demand"
    ' This is the first series of the full series collection
    .SeriesCollection(1).XValues = rangex
    .SeriesCollection.NewSeries
    ' Creates legend at the bottom of the chart
    .SetElement (msoElementLegendBottom)
    ' Deletes the chart title as per the illustration in Assignment 2's illustration screenshot
    .ChartTitle.Delete

    ' Creates the line Demand (Forecast)
    With .SeriesCollection(2)
        .Name = "Demand (Forecast)"
        .Values = rangey2
        .Format.Line.Visible = msoTrue
    End With
    ' Makes the forecast line distinguishable by dotting it
    For Each Srs In .SeriesCollection
        With Srs
            .Format.Line.DashStyle = msoLineSysDot
            .Format.Line.ForeColor.RGB = RGB(56, 182, 75)
            .MarkerBackgroundColor = RGB(56, 182, 75)
        End With
    Next Srs
End With


text: Q: erro ao Salvar no banco JSF+JPA & Hibernate Boa tarde estou fazendo um cadastro com JSF , e quando tento salvar o usuário no banco acontece esse erro , porem ja adicionei todos os jars na pasta lib tomcat , e ja foi verificado que não existe nenhum jar igual ou com versão diferente para não dar conflito, fiz o teste com a classe de persistência e conseguir cria tabela funcionário, então acredito que não seja esse  o problema.


text:
Q: CPU frequency is very low and system is very slow too in core i5 vaio laptop Sometimes I notice that system is very slow and when I see task manager, these are information in performance tab:
Utilization: 8%
Speed: 0.2 Ghz
Maxsimum speed: 2.5 GHz

Hardware details are:
Windows 8 Pro x64
Sony vaio vpcse23fx
core i5 2450M
RAM 8 GB
VGA Intel gen2 hd 3000
ATI 7400 series
HDD 5400 rpm

As an aside, my graphics driver is from leshcatlabs.net (updated and joined drivers for Intel and ATI).
I use this driver because last update of Sony's driver is 2012 and original ATI's driver from AMD has some problems.
I also disabled ATI card in device manager but problem occurred again. Is it possible that this problem be related to VGA?
Please note, this slow issue occurs at least once every 2 hours, but only lasts a period of time.
What do I mean by slow? It is slow when I want to open an app, when I move mouse (moves with some lags), when I open task manager, when I switch tabs in chrome, even slow in network. Also copying and moving files.
It's obviously related to frequency, because when frequency backs to 2 GHz everything acts normally again.
How can I fix this annoying speed issue?
Update: I found that this issue occures only when laptop uses Intel VGA, And instantly after switching to ATI card frequency goes back to 2GHz.
Distance between frequency issue occurences in my tests is under 1 minute! I mean after switching graphics card to Intel, It happens after less than a minute and switching to ATI fixes it instantly.

Solved:
By using amd.com driver and drivermax for updating intel driver problem totally solved and after some months of this update i have not this problem again.

A: Slowness on a machine can be caused not just by CPU activity but also by disk activity and I have seen this on a number of occassions. Sometimes this could be down to a background process accessing a big file.
To check your disk activity download Sysinternal's Process Monitor. When your computer is running slow then run the utility for I would say no more than a minute (more than that is not really necessary).
When you've completed your trace, do a count for the number of times each file was being accessed during that the trace you captured. To do this, go to to Tools -> Count Values Occurences -> Select Path from the Column drop-down and then click on the Count button. Click the Count button to sort the count numbers in ascending/descending order and it should become clear which files are being heavily accessed. Double-click on any of those file paths to focus on them and see which programs are responsible for the disk access.


text:
Q: How create video file from bitmap array by NReco I have pictures from the camera and I'd like to save them as a video. I do not have pictures saved as files, I just keep them in my memory (like Bitmap).
The headword method I need might look like this:
public void createVideoFileFromBitmapList(List<Bitmap> inputList, String pathToOutputFile){

}

I tried to use the example:

NReco.VideoConverter.Examples.LiveStreamFromImages.csproj

But I do not like the fact that there is a * .h264 file in the process and the resulting video is too compressed.


text:
Q: SVN More repositories for working copy I have one repository with read-only access on remote server. On my computer I have just working copy of that repository which I'm working on and I need to commit whole working copy to my own Repository with full access. Simply it looks like: Update WC, add/edit some code, commit it on my own repository.
Is it possible because I can't figure out how to do this in Eclipse (with Subclipse plugin) or TortoiseSVN.

A: Since you only have read-only access to the remote server you might export rather than creating a working copy, and treat that as you might any third-party code. The SVN book contains advice on managing vendor branches, making changes in your repository and merging in changes from the remote repository.

A: This should work:

*

*Update working copy from their repository

*Edit

*Use svn Export (tsvn context menu on the root of the working copy) to create a non-SVN copy of the source tree in a new local directory (e.g. "\exported").

*If you don't already have one, in your repository create a new directory. This directory is where you will host the source tree.

*Create a local working copy of this new svn path by using Checkout into a local directory (e.g. "\myRepo").

*Move the exported tree ("\exported") into this new working copy that mirrors your repository ("\myRepo")

*Add the files/directories in this tree to your working copy.

*Commit to your repository.

Remember, if the original codebase was made available under the GPL or something similar, you must make your modifications available as well if you distribute any compilations of the code.

A: Try this:

*

*Export your existing working copy to some new directory.

*Import this new directory to your own repositry.

Tortoise will help you with import and export.


text:
Q: Using HashMap.keySet as a dirty copy I have a requirement where I have to use a hashMap where values can change dynamically and keys can get only inserted not deleted or updated. However Keys will be read many times and values may be updated many times.
For latency issues, I haven't made entire HashMap as ConcurrentHashMap in which case while writing keys I will have issues. I am fine with compromising slight data accuracy with keys. So I decided to keep my own dirty copy of keys. A code snippet like below.
package com.test.collections;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;

public class CheckKeySet {

    private static Map<String, ConcurrentHashMap<String, String>> testMap = new HashMap<String, ConcurrentHashMap<String, String>>();

    public static void main(String[] args) {
        CheckKeySet trial = new CheckKeySet();
        try {
            trial.doIt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doIt() throws InterruptedException {
        Thread accessThread1 = new AccessKeySet("Access1");
        Thread writeThread = new WriteValueSet();
        Thread accessThread2 = new AccessKeySet("Access2");
        Thread accessThread3 = new AccessKeySet("Access3");

        writeThread.start();
        Thread.sleep(1000);
        accessThread1.start();
        Thread.sleep(2000);
        accessThread2.start();
        Thread.sleep(4000);
        accessThread3.start();
    }

    private Set<String> getKeySet() {
        return new TreeSet<String>(testMap.keySet());
    }

    class AccessKeySet extends Thread {

        public AccessKeySet(String string) {
            super(string);
        }

        @Override
        public void run() {
            Set<String> keySet = getKeySet();
            System.out.println("###############Trying to print########## " + getName() + " keySet size " + keySet.size());
            for (String s : keySet) {
                System.out.println(s);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class WriteValueSet extends Thread {

        @Override
        public void run() {
            int i = 1;
            for (i = 1; i < 10000; i++) {
                testMap.put("Check-" + i, new ConcurrentHashMap<String, String>());
                System.out.println("Inserted " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

My question,  I am creating new Set Object in above implementation with the HashMap.keySet() as base value. HashMap.keySet() will live forever in my code. Will this impact the GC of dirty set objects that I am creating in getKeySet() ? I want this new set object to be cced whenever its holding object becomes eligible for gc. It should not be stopped from getting gced because hashMap.keySet is alive

A: Correct me if I'm wrong, but it sounds like you don't want keys or values to get garbage collected from testMap, unless you manually remove them. Rather, you only want keys in the key set returned by your getKeySet() method to be garbage collected, if at all possible, even you might not remove them explicitly from the set.
Assuming that is the case, you should consider using weak references. More precisely to your implementation, you could simulate a WeakHashSet (as per this answer) and change your getKeySet() method implementation to:
private Set<String> getKeySet() {
  Set<String> cache = Collections.newSetFromMap(
    new WeakHashMap<String, Boolean>());
  cache.addAll(this.testMap.keySet());
  return cache;
}

This new code copies all of the keys of the strongly referenced testMap into the weakly referenced cache. Thus, whenever the garbage collector runs after you remove an element from testMap, the garbage collector will remove that same element automatically from cache.


text:
Q: mysql syntax error on removing duplicates I am trying to remove rows having duplicate hid column values with this query:
DELETE FROM dmf_product_match_unmatches as pmu1
WHERE ID not in
(
    SELECT MAX(ID) as maxRecId
        FROM dmf_product_match_unmatches as pmu2
        GROUP BY hid
);

But this gives
QL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as pmu1
WHERE ID not in
(
    SELECT MAX(ID) as maxRecId
        FROM dmf_prod' at line 1

The query looks fine. What am I missing here?

A: The documentation on DELETE doesn't make this clear in the syntax reference at the top of the page, but if you define an alias for a table, you must use the syntax like this:
DELETE pmu1 FROM dmf_product_match_unmatches as pmu1
...

The reason is that using the as keyword  makes the parser think you're using the multi-table delete syntax, even though you are only referencing one table in your outer query. The syntax reference on the documentation I linked to shows that DELETE tbl_name FROM ... syntax is required if you make use of table_references syntax, which you are if you use the as keyword.
The documentation does have a note lower down:

If you declare an alias for a table, you must use the alias when referring to the table:
DELETE t1 FROM test AS t1, test2 WHERE ...

Alternatively, you don't need to define an alias in this query, so you can use the simpler syntax:
DELETE FROM dmf_product_match_unmatches
...

A: This is the case when the error message does not match the error by some unknown reason. I don't understand why so - while executing in CLI the error message must be

You can't specify target table 'pmu1' for update in FROM clause

The root of the error - you cannot use the table to be altered as datasource of the subquery in WHERE.
You must use multiple-table DELETE syntax instead:
DELETE pmu1
FROM dmf_product_match_unmatches as pmu1
LEFT JOIN ( SELECT MAX(ID) as ID, hid
            FROM dmf_product_match_unmatches as pmu2
            GROUP BY hid) pmu3 USING (ID, hid)
WHERE pmu3.ID IS NULL;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=202cddc698cda3f83e0172c7e4e28a7d