text:
Q: What is the correct way to use fromIntegral to convert an Integer to real-fractional types? I am trying to use fromIntegral to convert from Integer to a real-fractional type. The idea is to have a helper method to later be used for the comparison between two instances of a Fraction (whether they are the same).
I have read some of the documentation related to:
fromIntegral :: (Integral a, Num b) => a -> b
realToFrac :: (Real a, Fractional b) => a -> b

Where I am having trouble is taking the concept and make an implementation of the helper method that takes a Num data type with fractions (numerator and denominator) and returns what I think is a real-fractional type value. Here is what I have been able to do so far:
data Num = Fraction {numerator :: Integer, denominator :: Integer}

helper :: Num -> Fractional
helper (Fraction num denom) = realToFrac(num/denom)

A: You need to learn about the difference between types and type classes. In OO languages, both are kind of the same concept, but in Haskell they're not.

*

*A type contains concrete values. E.g. the type Bool contains the value True.

*A class contains types. E.g. the Ord class doesn't contain any values, but it does contain the types which contain values that can be compared.

In case of numbers in Haskell it's a bit confusing that you can't really tell from the name whether you're dealing with a type or a class. Fractional is a class, whereas Rational is a type (which is an instance of Fractional, but so is e.g. Float).
In your example... first let's give that type a better name
data MyRational = Fraction {numerator :: Integer, denominator :: Integer}

...you have two possibilities what helper could actually do: convert to a concrete Rational value
helper' :: MyRational -> Rational

or a generic Fractional-type one
helper'' :: Fractional r => MyRational -> r

The latter is strictly more general, because Rational is an instance of Fractional (i.e. you can in fact use helper'' as a MyRational -> Rational function, but also as a MyRational -> Double function).
In either case,
helper (Fraction num denom) = realToFrac(num/denom)

does not work because you're trying to carry out the division on integer values and only then converting the result. Instead, you need to convert the integers to something fractional and then carry out the division in that type.


text:
Q: Relating PhoneGap, AngularJs, Ionic, Bootstrap, Jasmine, Grunt, Bower. I'm starting an new project targeting mobile development, and I found my self lost on many framework options.
Specifically, I choose to do an Ionic project, which is based on Bootstrap, Phonegap, and AngularJs. To build and dependencies I'm using Grunt and Bower, and Jasmine for tests.
So, can anybody give a light on how I start the project? Which framework I use to generate the folders organization. And maybe, some tips about the relation between these tools.
Thanks!

A: Let me introduce another term for you - Yeoman. Yeoman is a tool for scaffolding applications, which is what you want to do. There is a yeoman generator called generator-ionic which sounds like almost exactly what you are looking for. After installing the generator, you just run the yo ionic command to scaffold out your directory structure. It also automatically runs Bower to install any dependencies. The documentation for generator-ionic does a pretty good job of explaining how to get up and running, but feel free to ask if you have any questions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to filter and all the categories in a single statement using django I have prog, associateprof, assistantprof, research scholar and mtech categories and to get count of those I am using each statement for each. Instead is there any chance to know in a single statement or using for loop.
I am doing like this :
  count= Snippet.objects.all().count()
    count1 = Snippet.objects.filter(designation = 'Prof').count()
    count2 = Snippet.objects.filter(designation = 'RA').count()
    count3 = Snippet.objects.filter(designation = 'MTech').count()
    count4 = Snippet.objects.filter(designation = 'Asstprof').count()
    count5 = Snippet.objects.filter(designation = 'Assocprof').count()

A: Try GROUP BY clause as ,
from django.db.models import Count

Snippet.objects.values('designation').annotate(count=Count('designation')).order_by('designation')


text:
Q: NFS share problems - RPC: fragment too large: xxxxx We have a virtual server with an NFS share that is written to by other servers.  Today the NFS share became inaccessible.  The syslog was full off messages like this:
RPC: fragment too large: 311176

I've seached on google but can't find much information about this.  Could someone explain what this means?

A: A rpc message (and NFS is rpc based service) can be split into multiple frames (chunks). Any RPC server has a limit on frame size as well as a limit on message size. "RPC: fragment too large: " indicates that NFS server got a rpc frame which is bigger than max allowed size. This message can point to a bug in the client code, server code or network issues. Port scans can trigger such situation as well.

A: In redhat
https://access.redhat.com/solutions/2065483

The default maximum rsize/wsize for a RHEL NFS server is normally calculated when the NFS server starts and is based on the amount of memory the system has. The more memory, the larger the allowed value up to the maximum of 1048576.

A problem can occur if the NFS server chooses to lower this value while NFS clients have a share mounted. The way this can occur is if the NFS server is rebooted with less memory. Depending on the change in the amount of memory, the NFS server may select a smaller rsize/wsize maximum.
But NFS clients which already had the NFS share mounted from before the NFS server restarted will not know the maximum allowed rsize/wsize changed. The allowed maximum is communicated to an NFS client when it mounts the NFS share. The NFS client will still think it is permitted to send RPCs using the old, larger size. But the large RPCs get rejected and dropped by the NFS server and generate the RPC: fragment too large do to the new maximum.
In NFS source code

https://android.googlesource.com/platform/development/+/ef48154/ndk/platforms/android-3/include/linux/nfs_xdr.h

https://docs.huihoo.com/doxygen/linux/kernel/3.7/nfs__xdr_8h_source.html

To change the maximum rsize and wsize supported by the NFS client,
adjust NFS_MAX_FILE_IO_SIZE.  64KB is a typical maximum, but some
servers can support a megabyte or more.  The default is left at 4096
bytes, which is reasonable for NFS over UDP.

#define NFS_MAX_FILE_IO_SIZE  (1048576U)
#define NFS_DEF_FILE_IO_SIZE    (4096U)
#define NFS_MIN_FILE_IO_SIZE    (1024U)

A: I saw this with an Ubuntu Xenial NFS server, and it was triggered after I had resized it from 8gb of RAM to 4gb of RAM.
Clients that had originally mounted an NFS share from the server had (presumably) auto-negotiated a mount like the following (output from running mount) :
nfs-server:/backups/something on /backup type nfs4 (rw,noatime,vers=4.2,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=10.1.1.2,local_lock=none,addr=10.1.1.1)
The fix was to reboot the client, or just unmount/mount the filesystem, at which point it changed the negotiated rsize/wsize down to be like :
nfs-server:/backups/something on /backup type nfs4 (rw,noatime,vers=4.2,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,clientaddr=10.1.1.2,local_lock=none,addr=10.1.1.1)
So I'd assume the problem could also be triggered by setting too large a rsize/wsize on the NFS mount.


text:
Q: i want to get a list of semantically similar words from the two embedded documents in python I am working on text embedding in python. Where I found the similarity between two documents with the Doc2vec model. the code is as follows:
for doc_id in range(len(train_corpus)):
    inferred_vector = model.infer_vector(train_corpus[doc_id].words) # it takes each document words as a input and produce vector of each document
    sims = model.docvecs.most_similar([inferred_vector], topn=len(model.docvecs)) # it takes list of all document's vector as a input and compare those with the trained vectors and gives the most similarity of 1st document to other and then second to other and so on .
    print('Document ({}): «{}»\n'.format(doc_id, ' '.join(train_corpus[doc_id].words)))
    print(u'SIMILAR/DISSIMILAR DOCS PER MODEL %s:\n' % model)
    for label, index in [('MOST', 0), ('SECOND-MOST', 1), ('MEDIAN', len(sims)//2), ('LEAST', len(sims) - 1)]:
        print(u'%s %s: «%s»\n' % (label, sims[index], ' '.join(train_corpus[sims[index][0]].words)))

now, from these two embedded documents, how can I extract a set of semantically similar words of those particular documents.
please, help me out.

A: Only some Doc2Vec modes also train word-vectors: dm=1 (the default), or dm=0, dbow_words=1 (DBOW doc-vectors but added skip-gram word-vectors. If you've used such a mode, then there will be word-vectors in your model.wv property.
A call to model.wv.similarity(word1, word2) method will give you the pairwise similarity for any 2 words.
So, you could iterate over all the words in doc1, then collect the similarities to each word in doc2, and report the single highest similarity for each word.


text:
Q: can anyone tell me how to get rid of spaces between these two buttons? Remove spaces between buttons

    <md-content>

            <md-button class="md-primary md-raised" md-theme="indigo">Button</md-button>
            <md-button class="md-primary md-raised" md-theme="indigo">Button</md-button>

    </md-content>

Here is the working example with code.
Any help is much appreciated.

A: Just get rid of the margin
button{
  margin: 0 !important;
}

A: Remove the margin from .buttondemoBasicUsage section .md-button as below:

  .buttondemoBasicUsage section .md-button {
    display: block;
    line-height: 25px;
  }

A: It is not the best solution to add margin: 0 on the whole button tag with !important. If your project grows you gonna have problems later on. Try to avoid !important and use it only when you cannot find another solution.
Change margin: 1em; in to margin: 1em 0; to keep top and bottom and remove right and left margin. To remove whole margin change to margin: 0;
.buttondemoBasicUsage section .md-button {
        display: block;
        line-height: 25px;
        margin: 1em 0;
    }


text:
Q: How to calculate number of mondays in a given month?     $start = strtotime("tuesday UTC");
    $end = strtotime("3 tuesday UTC");
    echo date("m/d/Y", $start). " - ".date("m/d/Y", $end). " has ". countDays(0, $start, $end). " Sundays";

I found this solution . But countDays is not working .
I found the solution ..


text:
Q: Java - iterate over ArrayList rows' (columns)? What is the simplest way to just iterate over ArrayList rows values?
For example I have two ArrayList:
ArrayList<Object> main = new ArrayList<Object>();
ArrayList<Object> row = new ArrayList<Object>();

I use two fors to add values into main. First I add row, then when row iterations end, I add it to main, and then repeat for another row etc. For example:
for(int i=0; i < somearray.length; i++){
  for(int j=0; j < somearray2.length; j++){
    if(somearray2[j] == true)
      row.add(somearray2[j]);
    }
  main.add(row);

}

So now I get ArrayList filled with rows like I need. But later I need to iterate over rows values, not just rows themselves from main ArrayList. How can I do that?
As I only see the method:
main.get(index), which let's me get a row, but nothing more.

A: So, based on your description, main is not a list of Objects, but a list of lists. So it should be declared as
List<List<Object>> main = new ArrayList<>();

The iteration now becomes obvious:
for (List<Object> row : main) {
    for (Object element : row) {
        // do what you want here
    }
}

This has the additional advantage of making your code type-safe: you won't be able to add, inadvertently, anything other than a List<Object> inside the main list.

A: Yes then access them as: ((ArrayList<Object>)main.get(index)).get(index2);. But if you want all of your row element to be added to main array, you can make use of:
Collections.addAll(main, row.toArray());


text:
Q: Cant configure laravel vite, on nginx on docker I cant configure laravel vite, on nginx on docker.
How should I configure nginx and vite to make them work?
My docker image and configs:
docker-compose.yml
version: "3.3"

services:
    nginx:
        build:
            context: .
            dockerfile: docker/Nginx.dockerfile
        ports:
            -   8098:8098
        volumes:
            - ./:/var/www/laravel-docker
        links:
            - fpm
    fpm:
        build:
            context: .
            dockerfile: docker/Fpm.dockerfile
        volumes:
            -   ./:/var/www/laravel-docker
            - type: "bind"
              source: "/tmp"
              target: "/tmp"
        links:
            -   mysql
    mysql:
        platform: linux/x86_64
        image: mysql
        command: --default-authentication-plugin=mysql_native_password
        restart: always
        ports:
        -   3306:3306
        environment:
            MYSQL_ROOT_PASSWORD: root
            #MYSQL_DATABASE: laravel
        volumes:
            - mysql-data:/var/lib/mysql

    phpmyadmin:
        image: phpmyadmin
        restart: always
        ports:
            - 8080:80
        environment:
            - PMA_ARBITRARY=1
            - PMA_HOST=mysql

volumes:
    mysql-data:

Fpm.dockerfile
ROM php:8.0-fpm

COPY --from=composer /usr/bin/composer /usr/bin/composer

RUN apt-get update && apt-get install -y \
    zlib1g-dev \
    libzip-dev \
    unzip

RUN curl -sL https://deb.nodesource.com/setup_18.x | bash -
RUN apt-get install -y nodejs

ADD docker/conf/php.ini /usr/local/etc/php/php.ini

RUN docker-php-ext-install zip pdo_mysql pdo_mysql mysqli

WORKDIR /var/www/laravel-docker

vhosts.conf
server {
    listen 8098;
    listen [::]:8098;
    server_name _;
    root /var/www/laravel-docker/public;
    index index.php;
    error_log /var/log/nginx/error.log;

    location / {
        try_files $uri /$uri /index.php?$query_string;
    }

    location ~ [^/].php(/|$) {
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param HTTPS off;
        fastcgi_param APPLICATION_ENV local;
    }
}

vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js','resources/css/style.css'],
            refresh: true,
        }),
    ],
    server: {
        port: 8098,
        host: 'localhost'
    },
});

When i run "npm run dev" vite renders resources like this:
<script type="module" src="http://localhost:8098/@vite/client"></script><link rel="stylesheet" href="http://localhost:8098/resources/css/style.css" /></head>

but there is 404 on the http://localhost:8098/resources/css/style.css


text:
Q: How to install Qt module on perl? i want to install perlqt to create a GUI. i see the INSTALL file and it said that a need to install KDE. is really necessary this installation? or just some files.
thanks for you reading.

A: Which Linux distro are you using?  It is likely pre-packaged for your system.  For example, on my old Fedora box, I could do:
yum install perl-Qt
Or on Debian:
apt-get install libqt-perl
You could also build it from source directly via Perl with:
perl -MCPAN -e 'install Qt'
Or via perl's cpan command, if you have that installed:
cpan Qt


text:
Q: KeyError in python (GUI) I created this GUI which contains a listbox, an entry box and an OK button.
This is the dictionary that is saved into the hard drive (pickled):
dict1 = {1: ['Banquet Burger', 80, 19],
         2: ['Veg Burger', 40, 14],
         3: ['Chicken Burger', 68, 15],
         4: ['Cheese Burger', 50, 13]}

In the entry widget, when the user enters the product code (key), the item should be inserted into the listbox.
For example if the user types 1 then 'Banquet Burger' should be added to the list box. If he types 3 the 'Chicken Burger' should be added to the list (but 'Banquet Burger' should still be there, it shouldn't disappear).
This code gives me a KeyError. I am sure that I imported all the necessary modules.
def OK_button():
    with open('Stock Burgers.txt', 'r') as file:
        dict1=pickle.load(file)
        code=product_code.get()
        code1=int(code)
        product_info=dict1[code]
        item=product_info[0]
        items.insert(1, item)

product_code=Entry(mcD, bd=7)
product_code.grid(row=3, columnspan=1)
ok_button=Button(mcD, text='   OK   ', command=OK_button)
ok_button.grid(row=4, columnspan=3)
items=Listbox(mcD, height=10, width=22)
items.grid(row=2, column=0)
mcD.mainloop()


text:
Q: Why inserting at beginning of a vector is valid but unspecified? After watching Sean Parent's 2016 Keynote: Better Code from BoostCon I am a bit confused about a piece of code that he mentions as

Valid but unspecified

std::vector<int> x = { 1, 2, 3 };
try{
  x.insert(x.begin(), 0);
} catch (...) {
  std::cout << x.size() << std::endl;
}

Why exactly would that be unspecified?
From http://en.cppreference.com/w/cpp/container/vector/insert we read:

iterator insert( const_iterator pos, const T& value ); (1)

iterator insert( const_iterator pos, T&& value );      (2)

1-2) inserts value before pos

A:
Why inserting at beginning of a vector is valid but unspecified?

It is not.
And it is not what the linked presentation says. What the presentation attempts to convey, is that if inserting a value at the beginning of the vector (to be more accurate: any other position other than end) results in a throw, then the vector will be left in an unspecified but valid state - as opposed to being rolled back to the state that the vector was originally, before attempting the failed operation.

Why exactly would that be unspecified?

Because the standard does not require that std::vector must offer strong exception safety for such operation. †

† It is not required in general, but it actually might require it in this case: As bogdan points out in a comment, vector does in fact offer strong exception guarantee, unless the source of the exception is copy constructor or assignment operator ... (other cases) ... and in the case where element type is int, the exception can't be from such source.
So, the example given in the presentation should therefore use some type T whose copy/move constructor or assignment might throw.


text:
Q: Should using training datasets or testing datasets for evaluating the performance of the models When comparing multiple models, should use training datasets or testing datasets or both of training and testing datasets for evaluating the performance of the models?

A: You can not rely on the training dataset because it was used to build the model. You have to test the model on an unseen dataset. For example, it is not recommended to select the model which perform well on the training dataset but it performs badly on the testing (overfitted).


text:
Q: The usage of "was" before "down the line" The sentence: from NPR transcript

WOOD: John Derbyshire is - so he was a writer for the National Review. He has made claims such as intelligent, well-socialized African-Americans are as rare as fancy commercial jets - right? - so things like that, very inflammatory, very incendiary. And he was a Trump supporter down the line.

In the bold sentence quoted above, isn't it that "was" indicates past tense (things that happened), so won't that contradict with "down the line" (in the future)?
And shouldn't it be like this:

"And he "might be" a Trump supporter down the line."

A: And he was a Trump supporter down the line.
down the line idiom  TFD

*

*All the way; throughout:

  And shouldn't it be like this: "And he "might be" a Trump supporter
  down the line."

No, the idiom implies before, during and after ...  all the way and throughout.

A: If the sentences "And he was a Trump supporter all the way." and "And throughout he was a Trump supporter." are acceptable, your sentence is definitely grammatical.

down the line  (The Free Dictionary)

*

*Also, all along the line. All the way, throughout.
For example, We've found numerous errors down the line.


text:
Q: Object that stores String data Sorry I'm new to Swift, and I need to create an Array of String data. I know about 2-D Arrays, but I would prefer Objects to store String.
stringObject[0] = ("MATISSE", "JASON SHAPIRO", "9:00AM", "EXPLORE THE TOPICS AND TOOLS RELATED TO TEST DRIVEN DEVELOPMENT.", "TEST DRIVEN DEVELOPMENT")

stringObject[1] = ("ROTHKO", "JIM WHITE", "9:00AM", "DISCUSS THE LATEST SET OF TOOLS USED TO HELP EASE SOFTWARE DEVELOPMENT.", "JAVA TOOLS")

How do I initialized the stringObject?


text:
Q: Identifying duplicate features by comparing two layers in QGIS? We have around 60,000 separate shp - tab files. We have to move all those into a gdb. While doing so, at times the data are getting duplicated as shown in the fig. Lyr_1 - gdb layer. Lyr_2 - individual shp file. We have to identify the duplicates of Lyr_2 in Lyr_1(gdb) and give unique id's to that features in Lyr_2.
Curretnly, we are using Xtools pro for ArcGIS -> Find duplicates option to identify the duplicates. ArcGIS -> Select by location -> are identical to source feature layers  is not working. We dont have license to Data Reviewer & Find identical tool.
Is there a way to do this in QGIS ?
Even in QGIS, tried with Spatial query -> features equals. But didn't work

A: You could use the Select by location tool from the Processing Toolbox to identify and select features from Lyr_2 which spatially equals features from Lyr_1:

Once selected, you could add unique IDs using, for example, the Field Calculator.
Note: Depending on your data, you may need to be careful as this method makes a spatial comparison, it doesn't check if the features are duplicates.


text:
Q: Ошибка при работе с VK API Делаю запрос, вроде бы все правильно написано, получаю ошибку
users.get?user_id=31669992&v=5.60:1 Uncaught SyntaxError: Unexpected token :

И в теле ошибки получаю данные
http://joxi.ru/12MWOP7uMlOg1r
Код
    $http({
    url: 'https://api.vk.com/method/users.get',
    method: "JSONP",
    params: {
        "user_id": 31669992,
        "v": "5.60"
    }
}).success(function(data, status, headers, config) {
    console.log(data.response);
}).error(function(data, status, headers, config) {
    console.log("error" + data);
});

Пример запроса с официальной документации
Вот пример с документации
 https://api.vk.com/method/users.get?user_ids=210700286&fields=bdate&v=5.60

A: Нашел ответ, ошибка была в том, что я не передал в params - callback. Правильно будет вот так
        $http({

        url: 'https://api.vk.com/method/users.get',
        method: "JSONP",
        responseType: "json",
        params: {
            callback: "JSON_CALLBACK",
            "user_id": 31669992,
            "v": "5.60"
        }
    }).success(function(data, status, headers, config) {
console.log(data);
    }).error(function(data, status, headers, config) {
        console.log("error" + data);
    });


text:
Q: Retrieve whole object in a join instead of just properties Is there anyway I can get the whole object Platform instead of just the properties in this query, I am using Poco with EF4:
var games = (from g in ctx.Games
join p in ctx.Platforms on g.Platform.Id equals p.Id into joinTable
from j in joinTable.DefaultIfEmpty()
  select new
     {
       GameId = g.Id,
       Title = g.Title,
       PlatformId = j.Id,
       PlatformShort = j.Platform_short

      });

Instead of using PlatformId and PlatformShort I just want to retrieve the whole Platform object (j). Like "Platform = j"
And is there any better way to return a typed collection with out iterating through games first ?
foreach (var g in games)
            {
                Game game = new Game();
                game.Platform = new Platform();
                game.Id = g.GameId;
                game.Title = g.Title;
                game.Platform.Id = g.PlatformId;
                game.Platform.Platform_short = g.PlatformShort;

                col.Add(game);
            }

I tried this instead:

return
  ctx.Games.Include("Platform").Take(50).ToList();

ANd now i got same value for all 100 records.
Here is the SQL:
FROM   [dbo].[Games] AS [Extent1]
LEFT OUTER JOIN  (SELECT [Extent2].[Id] AS [Id1], [Extent2].[Platform_short] AS [Platform_short], [Extent2].[Platform_long] AS [Platform_long], [Extent2].[Description] AS [Description], [Extent2].[Image] AS [Image], [Extent2].[CreatedDate] AS [CreatedDate1], [Extent2].[ModifiedDate] AS [ModifiedDate1]
    FROM  [dbo].[Platforms] AS [Extent2]
    LEFT OUTER JOIN [dbo].[Games] AS [Extent3] ON [Extent2].[Id] = [Extent3].[PlatformId] ) AS [Join1] ON [Extent1].[PlatformId] = [Join1].[Id1] LEFT OUTER JOIN  (SELECT [Extent4].[Id] AS [Id3], [Extent5].[Id] AS [Id2]
    FROM  [dbo].[Platforms] AS [Extent4]
    LEFT OUTER JOIN [dbo].[Games] AS [Extent5] ON [Extent4].[Id] = [Extent5].[PlatformId] ) AS [Join3] ON [Extent1].[PlatformId] = [Join3].[Id3]

A: Yes there is a better way:
var collection = context.Games.Include("Platform").ToList();


text:
Q: Create a view in Mappoint with SQL addin I just downloaded the SQL add in for MS Mappoint, and I'm trying to create a view.  I have a bunch of locations stored as LocID (Ident/Key), Name, Address, City, State, Zip, Zip3, Country, Longitude, Latitude.
How do I manually create a view so that I can use that view to create a layer?  I tried selecting my locations table in the SQL add in, but it doesn't seem to recognize it as a valid view.


text:
Q: problem in app-simple player File "/home/rohit/rohit-player/rohit_player/RohitPlayerWindow.py", line 54, in on_open_clicked
    media_files.append({"File":f, "uri":file_uri, "format":format})
NameError: global name 'media_files' is not defined
i have followed line by line tutorial of rick ! on building a simple player
{http://developer.ubuntu.com/resources/app-developer-cookbook/multimedia/creating-a-simple-media-player/}
but i am stuck on the above mentioned error
when i click on open button to select files it just show up on terminal ("the above mentioned error")
i have till now worked till displaying the list to user
i m on 12.04 lts!
thanx in advance

A: As far as I know that tutorial is now out of date and won't work with the current Quickly. We are currently working to get it updated. I recommend you instead follow the video at http://developer.ubuntu.com/get-started/ for how to get started with our current developer platform.


text:
Q: Filterregisteration Bean and injection of a collection @Value We have a configuration class:
public class FilterConfigBase {

   @Bean
   public FilterRegisterationBean
   corsFilter(@value("${client.ip.headers:}") List<String>
   clientIpHeaders)
   {
    ....
    ...
    ...
  }
}

Application.properties:
client.ip.headers=A,B,C

We have a DefaultConversion service bean (which has StringToCollectionConverter)
In FilterConfigBase (Which contains only FIlterRegisterationBean), @Value annotation is not calling the StringToCollectionConverter class instead the conversion result is:
clientIpHeaders[0]="A,B,C"

Whereas in other configuration classes, @Value annotation is able to resolve the property, It calls the StringToCollectionConverter and the values are properly populated.
clientIpHeaders.get(0)="A"
clientIpHeaders.get(1)="B"
clientIpHeaders.get(2)="C"

For more details:
https://github.com/spring-projects/spring-boot/issues/11585

A: You can try to add a bit of EL there to split into list:
@Bean
public FilterRegisterationBean
corsFilter(@value("#{'${client.ip.headers:}'.split(',')}") List<String>
clientIpHeaders)


text:
Q: python flask-security: encryption error "hash could not be identified" I'm using Flask-Security in a Flask project. Basically everything works, until I try to turn on password encryption. Basically I followed this: http://packages.python.org/Flask-Security/configuration.html
Which led to me adding this:
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = '$2a$16$PnnIgfMwkOjGX4SkHqSOPO'

This results in a error unfortunately:
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask_security/decorators.py", line 171, in wrapper
return f(*args, **kwargs)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask_security/views.py", line 72, in login
if form.validate_on_submit():
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask_wtf/form.py", line 123, in validate_on_submit
return self.is_submitted() and self.validate()
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask_security/forms.py", line 165, in validate
if not verify_password(self.password.data, self.user.password):
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/flask_security/utils.py", line 84, in verify_password
return _pwd_context.verify(get_hmac(password), password_hash)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/passlib/context.py", line 2534, in verify
record = self._get_or_identify_record(hash, scheme, category)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/passlib/context.py", line 2258, in _get_or_identify_record
return self._identify_record(hash, category)
File "/home/geoadmin/.virtualenvs/flask/lib/python2.7/site-packages/passlib/context.py", line 1455, in identify_record
raise ValueError("hash could not be identified")
ValueError: hash could not be identified

I'm rather clueless as to what's happening. I thought i generated a good bcrypt hash, but there are no real examples on the website for password encryption and the error itself confuses me :/
Software used:
- Ubuntu 12.04LTS
- Python 2.7.2
- FLask 0.9
- Flask-Security 1.5.4
- Running on MongoDB 2.2 through MongoAlchemy
Thanks for your help!!
Edit: thanks to Bikeshedder, this is the likely culprit:
# Create a user to test with
@app.before_first_request
def create_user():
    user_datastore.create_user(email='test@test.net', password='testerdetest')

I assumed that the create_user method would automatically encrypt the password. But apparently it doesn't... The documentation isn't really clear here:
Class flask_security.datastore.MongoEngineUserDatastore(db, user_model, role_model)
A MongoEngine datastore implementation for Flask-Security that assumes the use of the Flask-MongoEngine extension.
create_user(**kwargs)
Creates and returns a new user from the given parameters.

Edit 2: Working further on BikeShedder's suggestion, I changed my standard user creation to this:
# Create a user to test with
@app.before_first_request
def create_user():
    user_datastore.create_user(email='test@test.net', password=bcrypt.hashpw('testerdetest', app.config['SECURITY_PASSWORD_SALT'])

So that solves the error, but it gives me an "Invalid password", meaning that flask-security does something different than I do in my encrypting... argh!
Edit 3: changed from bcrypt to passlib (which flask-security also uses)
app.config['SECURITY_PASSWORD_SALT'] = '/2aX16zPnnIgfMwkOjGX4S'

and
user_datastore.create_user(email='test@test.net', password=passlib.hash.bcrypt.encrypt('testerdetest', salt=app.config['SECURITY_PASSWORD_SALT']))

still get an invalid pw :(
If i look at the source code at https://github.com/mattupstate/flask-security/blob/develop/flask_security/utils.py it seems it only uses a sha512 encryption... I don't understand the documentation then...
Edit 5: solved (thanks for putting me on the right direction!)
flask.ext.security.utils.encrypt_password() did the trick. However, i'm still in doubt whether it really is bcrypt or not, but okay, it's encrypted at least...

A: Since you did not explain when this error occurs I have to guess that it happens when trying to log in.
If this is the case this means the password stored in the DB is in the wrong format. It is probably still plain text and Flask-Security is unable to figure out the hashing algorithm in use.
The simplest way to fix this would be resetting the passwords of the users.

A: Old question but clear answer from the developer...

It all depends on how you add users to your database. If you have set
  SECURITY_REGISTERABLE = True, and are only adding users via the
  built-in registration form, then you'll be fine. If you're adding
  users by any other means you must encrypt the password using
  flask_security.utils.encrypt_password before saving the user record in
  your database.

from flask.ext.security.utils import encrypt_password
db.create_user(email='test@test.com', password=encrypt_password('password'))

A: I had the same issue, I solve it with:
from flask.ext.security.utils import encrypt_password
user_datastore.create_user(email='test@test.fr', password=encrypt_password('password'))

The advantage is that we can choose that we want for SECURITY_PASSWORD_HASH and SECURITY_PASSWORD_SALT values.


text:
Q: Want to select all rows that meet multiple conditions and create subset for them I want to select all the rows that are equal to specific dates. I tried the following:
dsCorona <- subset(dsCorona, datum == c("2020-03-07", "2020-03-14", "2020-03-21", "2020-03-28",
                                       "2020-04-04", "2020-04-11", "2020-04-18", "2020-04-25",
                                       "2020-04-30"))

However, this does not seem to work and I end up with the following error:
In datum == c("2020-03-07", "2020-03-14", "2020-03-21", "2020-03-28",  :
  longer object length is not a multiple of shorter object length
Can anyone help me out?

A: Maybe you should consider use dplyr/tidyverse. If dsCorona is a data.frame (if not, you can cast it), with the dplyr/tidyverse package achive what are you asking would be:
dsCorona <- dsCorona %>% filter(datnum %in% c(...vector of those values))

I hope it helps!


text:
Q: What is the best way of getting the timezone from the city, country that user selects? I looked into javascript, and thought about using the client's clock, but it doesn't seem very reliable since the client's clock is out of my control.
I looked around for web services but wasn't lucky.
Basically what I want is to display a specific time (e.g. 9:00:00 GMT +4) in the user's timezone, based on location provided (city, country).
Thanks

A: If you're limiting the list of cities to the cities supported by PHP  it's pretty easy, you can then use the DateTimeZone class.
If you're allowing the user to choose any old city and want to work out the timezone from that then I'm pretty sure there isn't a maintained mapping file.
You could use a webservice to look up the latitude and longitude of a city and then plug that latitude &longitude into Ask Geo or a similar webservice. You'd need to ask the country too there's a Cairo in the USA and in Egypt.

A: I think this JavaScript tool jsTimezoneDetect is what you need. It is very easy to use and it can detect a pretty big range of timezones. Besides, if you want to detect the timezone from the country and city that the user selected, I think you would need to store the whole Olson timezone database and make Ajax call to get what you need.


text:
Q: ajax dataType Html prepend data on IE7 and IE8 I have a problem on IE7+8 on this code:
    //Post URL
    $.ajax({
        type : 'POST',
        url: url,
        dataType: "html",

    //Success Post
    success: function(data){

        //Reactivate Filters and Grid
        boxFilter.css({'opacity':1});
        var productGrid = $('.products-grid');
        productGrid.css({'background':'none', 'height':'auto', 'opacity':1}).find('img.ajax-loader').remove();

        //Append Data
        var response = $(data);
        var newHtmlGrid = $(response).find(".products-grid > div");
        productGrid.append(newHtmlGrid)

    }

    });

Everything is fine on IE9, firefox and all other, but on IE7+8 it's not working.
If I console.log(data) will give me the html, but if I try to append it (not filtered) it will not work.
Any idea why is that?
Thank you!


text:
Q: How removing duplicate rows Group two columns? I have a table (babynames) in my database which has duplicate records that I want to delete.
Ex Records in My Table
id category_id  baby_name   url_role
1      6        karthik     karthik
2      7        kalaivanan  kalaivanan
3      4        arun        arun
4      6        vijayakumar vijayakumar
5      6        karthik     karthik
6      6        karthik     karthik
7      4        karthik     karthik
9      6        vijayakumar vijayakumar
8      4        karthik     karthik

I Need Result
id category_id  baby_name   url_role
1      6        karthik     karthik
2      7        kalaivanan  kalaivanan
3      4        arun        arun
4      6        vijayakumar vijayakumar
7      4        karthik     karthik

I Need to remove Duplicate Records Found in Same Category with same baby_name. I don't want to create a new table with distinct entries for this. I Need to delete duplicate entries from the existing table without the creation of any new table.
DELETE FROM babynames
    WHERE id NOT IN
      (   SELECT MIN(id)
            FROM babynames
        GROUP BY baby_name,category_id
      )

A: In MySQL, you should use a JOIN:
DELETE b
    FROM babynames b LEFT JOIN
         (SELECT baby_name, category_id, MIN(id) as min_id
          FROM babynames
          GROUP BY baby_name,category_id
         ) bb
         ON bb.min_id = b.id
    WHERE bb.min_id IS NULL;

A: You can use an EXISTS clause, taking care to wrap the internal FROM into a subquery to avoid the dreaded

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

error:
DELETE b
FROM babynames b
WHERE EXISTS (SELECT *
              FROM (SELECT * FROM babynames) b1
              WHERE b1.category_id = b.category_id
                AND b1.baby_name = b.baby_name
                AND b1.id < b.id)

Output:
id  category_id     baby_name       url_role
1   6               karthik         karthik
2   7               kalaivanan      kalaivanan
3   4               arun            arun
4   6               vijayakumar     vijayakumar
7   4               karthik         karthik

Demo on dbfiddle

A: To delete duplicate records from table you can do like below
delete from names
where id not in
(
select min(id)
from names
group by category_id,baby_name,url_role

  )

A:
Please Try this

 DELETE FROM babynames
   WHERE id   IN
                  (
                  select id from (SELECT id ,  RANK() OVER (PARTITION BY baby_name,category_id
                 ORDER BY  sale DESC  )rw sales_rank FROM babynames)t1 where rw>1
                  )


text:
Q: Getting array names from multidimensional array I have a multidimensional array in javascript. I need to loop over the array and everytime the index of the array is equal to an array I have to make a new dropdown menu. To do this I need to get the name of the nested arrays and set it as the name of the dropdown menu.
All the elements in the array represent categories and subcategories. I tried getting for example the name of the array engine, but the only thing I am able to get is the content of the array.
var categories = [engine=[1,2,3, piston=[4,5,6]], tire=[7,8,9]];

What I want to know is if this is even the right way to do it, because I dont think so and I can't seem to find another way of doing it.

A: Iterating over an object is possible in ES2017 in a much better way than before.
Assuming you have a valid object of shape, you could do:
 const tabs = {
    engine: [],
    piston: [],
    tire: []
 };

 Object.entries(tabs) // returns an array of [key, value], here [tab1, []] etc...
    .forEach(([tabname, valueArray]) => {
        // do stuff with it
    });

Of course because order is most likely important you could add an order key for each tab, resulting in a shape like:
 const tabs = {
    engine: { order: 0, indexes: [] },
 };
 // then yo sort before iterating on it.
 Object.entries(tabs).sort(customSortFunction).forEach();

A: Technically what you posted is a valid array, except that while being created it assigns values to 4 variables all at the same scope level: categories, engine, piston and tire, which could be unintentional.
Expand the collapsed snippet to see a demo of this.

var categories = [engine=[1,2,3, piston=[4,5,6]], tire=[7,8,9]];

console.log("categories:");
console.log(categories);
console.log("engine:");
console.log(engine);
console.log("piston:");
console.log(piston);
console.log("tire:");
console.log(tire);

You probably want to use nested object syntax using {}-braces and the : character:

var categories = [{
  engine: [1, 2, 3, {
    piston: [4, 5, 6]
  }]
}, {
  tire: [7, 8, 9]
}];

console.log("categories:");
console.log(categories);

A: You'll need to define that array as an object instead. You can nest objects inside objects as long as it's a property value.
Then you can loop over the object by using Object.values(object)
E.g.

let categories = {
  engine: [1,2,3, {piston: [4,5,6]}],
  tire: [7,8,9]
};

let values = Object.values(categories);

for (let i = 0; i < values.length; i++) {
  values[i].map(x => {
    console.log(typeof x);
    if (typeof x === "object") {
      //Get the name of the object
      console.log("> " + Object.keys(x)[0]);
    }
  });
}

A: Your structure is a purely nested array. The terms "engine", "piston", "tires" are not part of it but are separate variables that are initialised to that particular sub-array.
Instead, I would suggest this structure, where these terms are stored property values, and the nested arrays are stored under the "children" property. So your example would be encoded like this:
var categories = [{
    text: "engine",
    children: [1,2,3, {
        text: "piston",
        children: [4,5,6]
    }]
}, {
    text: "tire",
    children: [7,8,9]
}];

Some alternatives have been suggested, but be aware that if you use an object like this:
var categories = {
    engine: [1,2,3, {
        piston: [4,5,6]
    }
    tire: [7,8,9]
};

...it is shorter, but in theory objects do not impose an order to the properties, so you don't really specify here that "engine" should be listed before "tire". To specify order you need an array (like in your initial plan).
Here is the suggested code to turn the first structure into an HTML menu, using ul and li DOM elements:

function menuToElement(menu) {
    const ul = document.createElement("ul");
    for (const item of menu) {
        const li = document.createElement("li");
        if (Object(item) === item) {
            li.textContent = item.text;
            li.appendChild(menuToElement(item.children));
        } else {
            li.textContent = item;
        }
        ul.appendChild(li);
    }
    return ul;
}

var categories = [{
    text: "engine",
    children: [1,2,3, {
        text: "piston",
        children: [4,5,6]
    }]
}, {
    text: "tire",
    children: [7,8,9]
}];

const ul = menuToElement(categories);
document.getElementById("menu").appendChild(ul);


text:
Q: Using OneHot Encoder to split one column into four In Python, suppose I have a column of a data frame called size, which looks like this:
E
G
F
D
F
E...

The letters D through G represent different sizes, say, from Small to X-Large. What I could do is represent them numerically, as so:
2
4
3
1
3
2...

However, since this is not continuous data, this may cause future problems with other analyses I'll do. Therefore, another idea I had was to split this into 4 columns, where an instance of the size is 1, otherwise, 0. It should look like this:
D E F G

0 1 0 0
0 0 0 1
0 0 1 0
1 0 0 0
0 0 1 0
0 1 0 0

I heard of something called OneHotEncoder in Python that is useful for these kind of scenarios. How would I use this effectively to solve this problem, or, what other ways can I go about this?


text:
Q: Magento2 Varnish configurations for mobile I am using varnish with magento2. however by default  VCL doesn't include device detection and assumes that websites are responsive so that the mobile and desktop browser would be served the same page.
How do I change varnish config so that it saves cache based on user-agent?

A: You can try adding below changes to the subroutines in default.vcl
sub vcl_recv {

    if (req.http.User-Agent ~ "iP(?:hone|ad|od)|BlackBerry|Palm|Googlebot-Mobile|Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera (?:Mini|Mobi)") {
         set req.http.X-Device = "mobile";
    } else {
         set req.http.X-Device = "other";
    }

}

sub vcl_hash {

    if (req.http.X-Device) {
        hash_data(req.http.X-Device);
    }

}

sub vcl_deliver {

    set resp.http.X-Varnish-Device = req.http.X-Device;

}


text:
Q: Multiple markers in google map I am scratching my head for google map integration please help me out.
I want multiple markers, but its taking only 11 markers not more than that.
Below is my code..
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("jquery", "1");</script>
<script type="text/javascript"> google.load("maps", "3", {other_params:"sensor=false"});</script>

<script type="text/javascript">
        var geocoder;
        var map, cloud;
        var counter = 0;
        var markers = [];
        var locations = [];

        locations[0] = "Charleston, SC";
        locations[1] = "Tuscon, AZ";
        locations[2] = "Phoenix, AZ";
        locations[3] = "San Diego, CA";
        locations[4] = "Los Angeles, CA";
        locations[5] = "Aliso Viejo, CA";
        locations[6] = "Laguna Beach, CA";
        locations[7] = "Coto de Caza, CA";
        locations[8] = "Philadelphia, PA";
        locations[9] = "Ladera Ranch, CA";
        locations[10] = "Thousand Oaks, CA";

        var image = new google.maps.MarkerImage(
            '../images/marker.png',
            new google.maps.Size(28,54),
            new google.maps.Point(0,0),
            new google.maps.Point(14,54)
        );

        function init()
        {
            //alert(locations.length);
            geocoder = new google.maps.Geocoder();
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var myOptions = {
                zoom: 4,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
            for (var i = 0; i < locations.length; i++) {
                makeMarker(locations[i]);
            }
            centerMap();
        }

        function centerMap()
        {
            map.setCenter(markers[markers.length-1].getPosition());
        }

        function makeMarker(location)
        {
            geocoder.geocode( { 'address': location}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    var marker = new google.maps.Marker({
                        map: map,
                        icon: image,
                        position: results[0].geometry.location
                    });
                    markers.push(marker);

                    alert(results[0].formatted_address);
                    var contentString = 'Content comes here';

                    var infowindow = new google.maps.InfoWindow({
                        content: contentString
                    });

                    google.maps.event.addListener(marker, 'mouseover', function() {
                        infowindow.open(map,marker);
                    });

                    google.maps.event.addListener(marker, 'mouseout', function() {
                        infowindow.close(map,marker);
                    });
                }
            });

        }
        google.maps.event.addDomListener(window, 'load', init);
    </script>

You can see practical example in: http://projects.pronixtech.net/kindcampaign/kind-country/

A: I think the problem is in "geocoder.geocode".
Look this code, with LatLong it works.
   var geocoder;
    var map, cloud;
    var counter = 0;
    var markers = [];
    var locations = [];

    locations[0] = new google.maps.LatLng(10.32522, 10.07002);
    locations[1] = new google.maps.LatLng(20.32522, 10.07002);
    locations[2] = new google.maps.LatLng(30.32522, 10.07002);
    locations[3] = new google.maps.LatLng(10.32522, 20.07002);
    locations[4] = new google.maps.LatLng(20.32522, 20.07002);
    locations[5] = new google.maps.LatLng(30.32522, 20.07002);
    locations[6] = new google.maps.LatLng(10.32522, 30.07002);
    locations[7] = new google.maps.LatLng(20.32522, 30.07002);
    locations[8] = new google.maps.LatLng(30.32522, 30.07002);
    locations[9] = new google.maps.LatLng(10.32522, 40.07002);
    locations[10] = new google.maps.LatLng(20.32522, 40.07002);
    locations[11] = new google.maps.LatLng(30.32522, 40.07002);
    locations[12] = new google.maps.LatLng(10.32522, 50.07002);
    locations[13] = new google.maps.LatLng(20.32522, 50.07002);
    locations[14] = new google.maps.LatLng(30.32522, 50.07002);
    locations[15] = new google.maps.LatLng(10.32522, 60.07002);
    locations[16] = new google.maps.LatLng(20.32522, 60.07002);
    locations[17] = new google.maps.LatLng(30.32522, 60.07002);

    var image = new google.maps.MarkerImage(
        'http://www.bookyourparis.com/images-site/beachflag.png',
        new google.maps.Size(28,54),
        new google.maps.Point(0,0),
        new google.maps.Point(14,54)
    );

    function init()
    {
        //alert(locations.length);
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 2,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

        for (var i = 0; i < locations.length; i++) {
            makeMarker(locations[i]);
        }

        centerMap();
    }

    function centerMap()
    {
        map.setCenter(markers[markers.length-1].getPosition());
    }

    function makeMarker(location)
    {

        //geocoder.geocode( { 'address': location}, function(results, status) {
          //  if (status == google.maps.GeocoderStatus.OK) {
                //map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    icon: image,
                    position: location//results[0].geometry.location
                });
                markers.push(marker);

                //alert(results[0].formatted_address);
                var contentString = 'Content comes here';

                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });

                google.maps.event.addListener(marker, 'mouseover', function() {
                    infowindow.open(map,this);
                });

                google.maps.event.addListener(marker, 'mouseout', function() {
                    infowindow.close(map,this);
                });
            //}
        //});

    }
    google.maps.event.addDomListener(window, 'load', init);


text:
Q: Delay UISearchbar parsing I have a UISearchbar in my app. This is a dynamic search and as the user enters text, a remote database is searched via a remote API call (I think it is through REST).
The table view gets refreshed dynamically, as the user types. I am using NSXMLParser for parsing the XML results. (so 3 delegate methods; didStartElement, didEndElement)
In some cases, there are duplicate entries shown in the results
e.g. If user has typed YAH, it shows YAHOO 3-4 times. I'm not sure why.
How can I reduce the number of times the parsing is done, or how to delay the parsing, so that it does not make a request for every character entered/deleted by the user.
This, I am assuming, might fix the problem.

A: One thing you can do is introduce a delay before you send off the remote API call, instead of sending one query for every character.
// Whenever UISearchbar text changes, schedule a lookup
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)text {
        // cancel any scheduled lookup
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        // start a new one in 0.3 seconds
        [self performSelector:@selector(doRemoteQuery) withObject:nil afterDelay:0.3];
}

A: Here are the relevant parts of a method I use in one of my apps to remove duplicates from a web service result.
NSMutableArray *mutableResults = [[myResults mutableCopy] autorelease];
NSMutableSet *duplicates = [NSMutableSet set];
NSMutableIndexSet *indexesToRemove = [NSMutableIndexSet indexSet];

for (NSString *result in mutableResults)
{
    if (![duplicates containsObject:result])
        [duplicates addObject:result];
    else
        [indexesToRemove addIndex:[mutableResults indexOfObject:object]];
}

[mutableResults removeObjectsAtIndexes:duplicates];
return mutableResults;


text:
Q: Centrifugal force problem involving pulley I have this following problem:

Two blocks A and B of masses $m_a, m_b$ are placed as shown on a platform at a distance $r$ from the axis of rotation. Find the angular speed of the platform so that the blocks just begin to slide. Consider friction($\mu_s$) between all contact surfaces.

I couldn't decide which block moves outwards and which one inwards, since the masses are incomparable. So I couldn't find appropriate directions of frictional force for each FBD(which includes tension, centrifugal force, normal and friction) as well. Any hint is appreciated.


text:
Q: What are the relative differential forms of a family of (nodal) curves? What is the definition of relative differential forms of a family $\pi: X \to B$ of (nodal) curves, where $B$ is the base space.

A: I learnt the following from the paper On the relative de Rham sequence (MathSciNet JSTOR) by Nick Buchdahl.  It is more general than the OP situation, but should easily specialise to it.

Let $f:X \to B$ be a smooth map between manifolds.  Then the sheaf $\Omega^1_f$ of germs of relative 1-forms on $X$ is defined by the following exact sequence
$$
f^*\Omega^1_B \to \Omega^1_X \to \Omega^1_f \to 0
$$
Then the relative differential $k$-forms are defined by
$$
\Omega^k_f = \Lambda^k \Omega^1_f
$$
as usual.  Differentiating along the fibres gives a differential $d_f: \Omega^k_f \to \Omega^{k+1}_f$.  and $(\Omega^\bullet_f, d_f)$ is called the relative de Rham complex.
When $f$ is a submersion, the relative de Rham complex gives a resolution
$$
0 \to f^{-1}\mathcal{E}_B \to \Omega^\bullet_f
$$
of the sheaf of functions of $X$ which are constant on the fibres.


text:
Q: how to change the image on a image button onmouseover event in HTML? I have 4 image button containing a image. on mouse over i have to change the image(i.e load a new image on the button). Here is the code.
<div class ="submit" id="submit" >
    <input  type="image" src="dump.png" value="Dumb" class ="Dumb" id="Dumb" onclick="posting_by_user('Dumb')" />
    <input  type="image" src="informative.png" value="Informative" class ="Informative" id="Informative" onclick="posting_by_user('Informative')"/>
    <input  type="image" src="brilliant.png" value="Brilliant" class ="Brilliant" id="Brilliant" onclick="posting_by_user('Brilliant')"/>
    <input  type="image" src="cool.png" value="Cool" class ="Cool" id="Cool" onclick="posting_by_user('Cool')"/>
</div>

Here I have loaded dump.png, informative.png, brilliant.png and cool.png. on mouse over on each button i have to change the image.

A: Try this
$(document).ready(function() {
$('input[type=img]')
    .mouseover(function() {
        var src =  "mouseover.png";
        $(this).attr("src", src);
    });

A: <input  type="image" src="dump.png" value="Dumb" class ="Dumb" id="Dumb" onclick="posting_by_user('Dumb')" onmouseover="changeImg.call(this)" />

function changeImg(){
this.setAttribute("src","newImageFileName.jpg");
}

Segregating your code from html is always advised.. this answer will be helpful as it is cleaner and good for debugging..

A: <input  type="image" src="dump.png" value="Dumb" class ="Dumb" id="Dumb"
onclick="posting_by_user('Dumb')"
onmouseover="this.src='informative.png';"
onmouseout="this.src='dump.png';" />

A: You can use either Javascript or CSS for this, below is the javascript approach.
window.addEventListener("load", function load (event) {
    window.removeEventListener("load", load, false);
    tieEvents();
}, false);

function tieEvents() {
    var button = document.getElementById('Dumb');

    button.addEventListener("mouseover", hovered, false);
    button.addEventListener("mouseout", unhovered, false);

    function hovered() {
        button.src = "anotherimg.png";
    }

    function unhovered() {
        button.src = "anotherimg.png";
    }
};

JSFiddle Demo
Note that setting events in HTML is not a good practice, it's better to tie them up in Javascript.

The CSS way is as follows:
#Dumb {
    backgroud: url("dump.png");
}

#Dumb:hover {
    backgroud: url("another.png");
}

JS Fiddle Demo


text:
Q: How to add mutiple users on same session where game will be played? It's Scrum Poker game having fibbonacci series.Every game has unique session.
I have to add multiple users on the same session.
Users will only get game session link via mail and all anonymous users will be in the same game session after login with name.
As the user selects card,its value store in session.Same selected value will be send to admin in unflipped manner.
So I need to know what user selected during game and where it will be stored. As every user has their own machine, I can't use session storage.
I am using angularjs, PHP and mysql. Does anyone has any idea of how to do this? How will I get to know what value user has voted during the game?


text:
Q: Id inheritance in JPA I have the following Scheme
@Entity
public class A

{
@Id
String field1
String field2
}
public class B extends A
{
 String field3;
 @OneToMany(MappedBy="b")
 List<C> cList;
}

public class C extends A
{
String field4;
@ManyToOne
B b;
}

Both class B and C extends A and get their id From A using table per concrete class strategy but the problem is that class B has one to many relationship with class C so what i want is to change the id of class C to be a composite key consist of the inherited id field1 and  the id of the object b. That will allow two different object of b to have the two different object of c with the same field1 value.
Is what i am thinking possible (override inheritance) i am using eclipse link as persistence provider.

A: Unfortunately, having different Id types in an entity hierarchy is not supported by the JPA inheritance strategies as it introduces ambiguities.
See this question for details.
to work around this limitation you could:

*

*'detach' C from the hierarchy so that it does not derive from A

*use C as an attribute in a different entity


text:
Q: Integrals on symbolic regions Let's define a region as r=Polygon[{{-a,0},{a,0},{a,h}}]. I want to integrate some function over that area. Say x^2. So,  Assuming[a>0&&h>0,Integrate[x^2,Element[{x,y},r]]] I get a^3h/3, as expected.
But, what if I want to have a four-sided polygon instead? If I redefine the region as r=Polygon[{{-a,0},{a,0},{a,h},{0,h}}], and then do Assuming[a>0&&h>0,Integrate[x^2,Element[{x,y},r]]], it can't do the integral.

A: Clear["Global`*"]

r = Polygon[{{-a, 0}, {a, 0}, {a, h}, {0, h}}];

As pointed out by cvgmt in a comment, the area is
area = Assuming[a > 0 && h > 0, Area[r]]

(* (3 a h)/2 *)

As a workaround to do the integral, break the region r into three triangular regions

r21 = Polygon[{{-a, 0}, {0, 0}, {0, h}}];
r22 = Polygon[{{0, 0}, {0, h}, {a, 0}}];
r23 = Polygon[{{0, h}, {a, h}, {a, 0}}];

The integral can be done over the subregions
area == Assuming[a > 0 && h > 0,
  Total[Integrate[1, {x, y} ∈ #] & /@ {r21, r22, r23}]]

(* True *)

EDIT: For a more complicated integrand
f[x_, y_] := (x^2 + 3) (x + y)

Assuming[a > 0 && h > 0,
 Total[Integrate[f[x, y], {x, y} ∈ #] & /@ {r21, r22, r23}] //
  Simplify]

(* 1/60 a h (60 a + 12 a^3 + 120 h + 11 a^2 h) *)

EDIT 2: The subdivisions do not need to be only triangles; however, there are limitations. Arbitrary polygons cannot be handled. Even a Polygon representing a Rectangle fails.
r31 = Polygon[{{0, 0}, {0, h}, {a, h}, {a, 0}}];

Assuming[a > 0 && h > 0,
 Total[Integrate[f[x, y], {x, y} ∈ #] & /@ {r21, r31}] // Simplify]

However, the equivalent Rectangle works
r32 = Rectangle[{0, 0}, {a, h}];

Assuming[a > 0 && h > 0,
 Total[Integrate[f[x, y], {x, y} ∈ #] & /@ {r21, r32}] // Simplify]

(* 1/60 a h (60 a + 12 a^3 + 120 h + 11 a^2 h) *)


text:
Q: Optional number of wildcards in URL patterns in Django #views.py
def sum(*args):
    return reduce((lambda x, y: int(x)+int(y)), args)

Is it possible to write one URL pattern that will handle uniformly such requests as /sum/1/2 (result = 3), /sum/1/2/3 (result = 6), etc.?

A: It's not exactly what you want, but you could use
(r'^sum/(?P<allargs>[/0-9]+)$', 'views.sum')

and then
def sum(request, allargs):
    args = map( int, allargs.split('/') )
    # Compute sum

A: Unless you absolutely want to use the form "/1/2/3", you'd rather use query string "/sum?1&2&3". It will be much simpler to implement.


text:
Q: Is there any way this disk might have some data on it? I'm a bit confused here.. is this just empty space, no partition?
Why are all the options greyed out?
How do I add a parition without using a 3rd party tool?
If I can't, would a 3rd party tool like minitool partition software let me do it?
I can't seem to find some files that I  thought I had on a USB drive, they are not on the other 3 (I can read all those). However it is possible that this is a drive I cleaned up long ago and therefore blank but I don't understand why it is not possible to add a new partion, format it or anything.
If it is some kind of sneaky invisible to windows partition of some kind of data, then how can I view it?

A: You dont need disk part to activate the partition. Just dont click on the partition with the right mouse button and click instead on the left side where "disk2 basic ..." is printed.
Then you should get an contex menu where you should be able to mark the disk as online.


text:
Q: When more is less in logic I am looking for examples of theorems where adding a 'trivial' extra condition makes the theorem provable in weaker systems.  By 'trivial' I mean that the extra condition is trivial in strong enough systems.   An example may be helpful as follows:
A function $f:[0,1]\rightarrow \mathbb{R}$ is called regulated in case the left and right limits $f(x+)$ and $f(x-)$ exist everywhere.
A function $f:[0,1]\rightarrow \mathbb{R}$ is called Baire 1 in case it is the pointwise limit of a sequence of continuous functions.
It is well-known from real analysis that regulated functions are Baire 1.
Now, the following is provable in Kohlenbach's system RCA$_0^\omega$ plus some induction:
A regulated and Baire 1 function on the unit interval has a point of continuity.
By contrast, the following theorem is not provable in the same system extended with $\Pi_1^1$-comprehension (and the same for much stronger systems):
A regulated function on the unit interval has a point of continuity.

A: There are various examples involving the axiom of choice.  For example:

Theorem 1 (ZFC).  Let $A$ be an infinite set (i.e., there is no bijection between $A$ and any finite von Neumann ordinal).  Then $A$ contains a countably infinite subset.

Theorem 1 is not provable in ZF.  However, if we add the "trivial" condition that $A$ be not just infinite, but Dedekind-infinite, then it becomes provable in ZF.
This is not a terribly interesting example of what you asked for.  Maybe you need to say more about what you're really interested in?

A: Consider König's theorem, which asserts that every infinite finitely branching tree has an infinite branch.
This is a theorem of ZFC, but in ZF alone, it is not provable. But meanwhile, if one adds the "trivial" assumption that the nodes of the tree admit a linear order, then it is provable in ZF, since from the linear order we can get a choice function of the successors of any node in the tree.


text:
Q: fetch form contact details from my website into whatsapp message space Am creating ecommerce site where user/customers after viewing and ordering the product, message to vendor will go by linking with whatsapp. So for the vendor to deliver the product he/she need to know the address of the customer, there is where I have created a form for contact details for customer to fill in. Now I want after the customer click to link with whatsapp, contact details should appear there in whatsapp. I have gone through [link][1] which describe for only short pre-filled message, now I want the whole contact form details.
Below is the link to whatsapp with the pre-filled message as "Your eshopsy order is:", so instead of the quoted text I want detail from the contact form
<button type="button" class="btn btn-default" aria-label="Left Align">Click to whatsapp

       </button>


text:
Q: Error sending multiple input to keras network I am trying to build a network that takes in 3 input (Image) and 1 output bounding box (x0, y0, x1, y1). The network consists of 3 VGG16 networks and concatenate into one layer and join with 4 fully connected layers.  But when I try to send input to the network, it produces the following error:
ValueError: Error when checking model input: the list of Numpy arrays that
    you are passing to your model is not the size the model expected. Expected
    to see 3 array(s), but instead got the following list of 2 arrays:

But I am sending the correct number of input to the network. Need advice here! Thanks in advace.
Code: Build Network
vgg_conv_1 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
vgg_conv_2 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
vgg_conv_3 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))

merged_layer = Concatenate(axis = 3)([vgg_conv_1.output, vgg_conv_2.output, vgg_conv_3.output])
merged_layer = Flatten()(merged_layer)
merged_layer = Dense(units = 1024, activation = "relu")(merged_layer)
merged_layer = Dense(units = 1024, activation = "relu")(merged_layer)
merged_layer = Dense(units = 1024, activation = "relu")(merged_layer)
merged_layer = BatchNormalization()(merged_layer)
merged_layer = Dropout(0.25)(merged_layer)
merged_layer = Dense(units = 4, activation = "sigmoid")(merged_layer)

newModel = Model([vgg_conv_1.input, vgg_conv_2.input, vgg_conv_3.input], merged_layer)

newModel.compile(optimizer = "sgd", loss = l2loss, metrics = ["accuracy"])

Code: Load Data (Both Training and validation set), labels = (x0, y0, x1, y1)
training_set_1 = []
training_set_2 = []
training_set_3 = []
train_labels = []

with open("train.txt") as f:
    for line in f:
        lines = line.rstrip("\n")
        line_split = lines.split(",")
        try:
            training_1 = tf.keras.preprocessing.image.load_img(line_split[0], target_size = (224, 224))
            x = tf.keras.preprocessing.image.img_to_array(training_1)
            x = preprocess(x)
            training_set_1.append(x)

            training_2 = tf.keras.preprocessing.image.load_img(line_split[1], target_size = (224, 224))
            x = tf.keras.preprocessing.image.img_to_array(training_2)
            x = preprocess(x)
            training_set_2.append(x)

            training_3 = tf.keras.preprocessing.image.load_img(line_split[2], target_size = (224, 224))
            x = tf.keras.preprocessing.image.img_to_array(training_3)
            x = preprocess(x)
            training_set_3.append(x)

            train_labels.append(np.array([line_split[3],line_split[4],
                  line_split[5],line_split[6] ]))
        except:
            pass

Code: Training
traingen = ImageDataGenerator(fill_mode="constant")
valgen = ImageDataGenerator(fill_mode="constant")

newModel.fit_generator( traingen.flow(x = [ np.array(training_set_1),np.array(training_set_2), np.array(training_set_3) ],
    y = np.array(train_labels), batch_size = 16),
    steps_per_epoch = 8000,
    epochs = 10,
    validation_data = valgen.flow(x = [ np.array(test_set_1), np.array(test_set_2), np.array(test_set_3) ], y = np.array(test_labels)),
    validation_steps = 2000)

A: You should have taken a look at the documentation of the ImageDataGenerator and especially its flow(...) method. It says

x: Input data. Numpy array of rank 4 or a tuple. If tuple, the first
  element should contain the images and the second element another numpy
  array or a list of numpy arrays that gets passed to the output without
  any modifications.

This means, that the x argument can only be a list/tuple of 2 items, not 3. If you want to pass 3 items, you have to do it like this:
traingen.flow(
    x=(np.array(training_set_1), [np.array(training_set_2), np.array(training_set_3)]),
    y=...
 ...
)


text:
Q: boost asio - exclusive binding to the network port I develop server app using boost asio. App works great. What doesn't work, is the the exclusive binding to the network port.
I launch one instance of the app - it starts listening to incoming connections.
I launch one more instance - it also starts listening to incoming connections on the same port. Handler that passed to async_accept do not invoked with error as expected.
Usually I just try to acquire the port. If operation fails - port is in use. With Asio this approach does not work. How to check availability of the port?
void TcpServerFactory::acceptConnectionsOnPort(int serverPort,
                                               boost::shared_ptr<TcpConfigServerReceiver> tcpConfig,
                                               boost::function<void(boost::shared_ptr<TcpServer>)> onSuccessfullyConnectedHandler)
{
    // todo check is port not busy
    FORMATTED_LOG(this->_log, info) << "Start to accept connections on port " << serverPort;
    auto endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), serverPort);
    boost::shared_ptr<boost::asio::ip::tcp::acceptor> tcpAcceptor(new boost::asio::ip::tcp::acceptor(this->_ioService, endpoint));

    this->acceptConnections(tcpAcceptor, tcpConfig, onSuccessfullyConnectedHandler);
}

void TcpServerFactory::acceptConnections(boost::shared_ptr<boost::asio::ip::tcp::acceptor> tcpAcceptor,
                                         boost::shared_ptr<TcpConfigServerReceiver> tcpConfig,
                                         boost::function<void(boost::shared_ptr<TcpServer>)> onSuccessfullyConnectedHandler)
{
    boost::shared_ptr<boost::asio::ip::tcp::socket> tcpSocket(new boost::asio::ip::tcp::socket(this->_ioService));
    boost::function<void(const boost::system::error_code &)> onAcceptOperationCompletedHandler =
        boost::bind(&TcpServerFactory::onAcceptOperationCompleted, this->downcasted_shared_from_this<TcpServerFactory>(),
                    _1, tcpAcceptor, tcpSocket, tcpConfig, onSuccessfullyConnectedHandler);

    tcpAcceptor.get()->async_accept(*tcpSocket, onAcceptOperationCompletedHandler);
}

void TcpServerFactory::onAcceptOperationCompleted(const boost::system::error_code & err,
                                                  boost::shared_ptr<boost::asio::ip::tcp::acceptor> tcpAcceptor,
                                                  boost::shared_ptr<boost::asio::ip::tcp::socket> tcpSocket,
                                                  boost::shared_ptr<TcpConfigServerReceiver> tcpConfig,
                                                  boost::function<void(boost::shared_ptr<TcpServer>)> onSuccessfullyConnectedHandler)
{
    if (err)
    {
        FORMATTED_LOG(this->_log, info) << "Failed to accept connections on port " << tcpAcceptor->local_endpoint().port() << "due to error " << BOOST_ERROR_TO_STREAM(err);
        return;
    }
    this->acceptConnections(tcpAcceptor, tcpConfig, onSuccessfullyConnectedHandler);
    this->onConnectionEstablished(tcpSocket, tcpConfig, onSuccessfullyConnectedHandler);
}

Update
I tried to replace constructor of acceptor on series of commands. I expected that on tcpAcceptor->bind() exception will be raised, but that didn't happened.
// boost::shared_ptr<boost::asio::ip::tcp::acceptor> tcpAcceptor(new boost::asio::ip::tcp::acceptor(this->_ioService, endpoint));

boost::shared_ptr<boost::asio::ip::tcp::acceptor> tcpAcceptor(new boost::asio::ip::tcp::acceptor(this->_ioService));
tcpAcceptor->open(endpoint.protocol());
tcpAcceptor->set_option(boost::asio::socket_base::reuse_address(true));
tcpAcceptor->bind(endpoint);
boost::system::error_code err;
tcpAcceptor->listen(boost::asio::socket_base::max_connections, err);

A: reuse_address is not supposed to do that. Its meaning to avoid "wait" interval after port was freed.


text:
Q: Rule of Thumb for minimum length of time series for AR(1) estimation I have a data set of 350 points, I want to estimate the lag 1 auto correlation for different sub-sets of the data.
More precisely I want to take non overlapping windows of length 1,2,3....n and calculate the auto correlations of these sub-sets. So for n equal to 2 I take every second observation similarly for n=3 I take every third observation and so on.
Just wondered roughly what the maximum value of n I can realistically work with? Even with n=10 I'm down to 35 observations.
Kind Regards
Baz

A: Strictly speaking, it depends on the signal/noise ratio in your dataset. The smaller the variance of the white noise component, the fewer observations one needs.
Note also that all you need to estimate ACF for AR(1) is the autoregression coefficient, $\phi$, because the correlation between points $h$ time steps apart is equal to $\phi^h$. That is, if you assume AR(1) for the original process you don't need to do any subsetting to estimate autocorrelations.


text:
Q: Can't install last version of pandas (1.0.3) For last two days, 24/7 I'm trying to deal with the problem of installation of pandas 1.0.3 package within Python 3.6.0. I will try to describe the whole situation below.
In my PyCharm I saw that I can upgrade pandas from 0.25.3 I was using to 1.0.3, but once I tried it an error has occurred.
possibility of an upgrade of pandas
an error
Firstly, I checked the default version of my python in the terminal:
In: python -V
Out: Python 2.7

In: python3 -V
Out: Python 3.6.0

Using this guid I have change the default python version for python 3.6. Which lead to this thing:
In: python -V
Out: Python 3.6.0

But still I can't install/upgrade pandas to version 1.0.3.
I've tried these commands in the terminal:
pip install pandas
pip3 install pandas
pip install pandas==1.0.3
pip3 install pandas==1.0.3

Same commands via sudo
pip install /path_to_wheel

Always I got the same error:
ERROR: Could not find a version that satisfies the requirement pandas==1.0.3 (from versions: 0.1, 0.2b0, 0.2b1, 0.2, 0.3.0b0, 0.3.0b2, 0.3.0, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.5.0, 0.6.0, 0.6.1, 0.7.0rc1, 0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.8.0rc1, 0.8.0rc2, 0.8.0, 0.8.1, 0.9.0, 0.9.1, 0.10.0, 0.10.1, 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.14.0, 0.14.1, 0.15.0, 0.15.1, 0.15.2, 0.16.0, 0.16.1, 0.16.2, 0.17.0, 0.17.1, 0.18.0, 0.18.1, 0.19.0rc1, 0.19.0, 0.19.1, 0.19.2, 0.20.0rc1, 0.20.0, 0.20.1, 0.20.2, 0.20.3, 0.21.0rc1, 0.21.0, 0.21.1, 0.22.0, 0.23.0rc2, 0.23.0, 0.23.1, 0.23.2, 0.23.3, 0.23.4, 0.24.0rc1, 0.24.0, 0.24.1, 0.24.2, 0.25.0rc0, 0.25.0, 0.25.1, 0.25.2, 0.25.3)
ERROR: No matching distribution found for pandas==1.0.3

Please help. I do not know why it happens :(
UPDATE:
Also not working:
python3 -m pip install /Users/username/Downloads/pandas-1.0.3-cp36-cp36m-macosx_10_9_x86_64.whl
Processing ./Downloads/pandas-1.0.3-cp36-cp36m-macosx_10_9_x86_64.whl
ERROR: Package 'pandas' requires a different Python: 3.6.0 not in '>=3.6.1' –

A: This is because pandas 1.0.x (and 1.1.0x) requires Python 3.6.1 or later. You are using Python 3.6.0. This can be seen in the error message you get :
ERROR: Package 'pandas' requires a different Python: 3.6.0 not in '>=3.6.1' –

This should be solved if you update your Python version.
You can see here the Python 3.6.1 requirement starting from pandas 1.0.0.


text:
Q: Selenium select each div separately that have the same class I am trying to select all the divs withclass tile-consultation in (http://raspored.finki.ukim.mk/Home/Consultations), click each of them and extract some data from each div, I tried using:
    List<WebElement> professors = driver.findElements(By.className("tile-consultation"));
    ListIterator<WebElement> theListOfProfessors = professors.listIterator();
    Thread.sleep(1000);

    int i = 1;
    while(theListOfProfessors.hasNext()) {
        WebElement professorI = driver.findElement(By.cssSelector(".tile-consultation:nth-of-type(2)"));
        professorI.click();

        Thread.sleep(1000);
        close = driver.findElement(By.cssSelector("button.btn-close"));
        close.click();
        Thread.sleep(1000);
     }

but how can I change 1 to the 2nd, 3d and so on in a while loop?

A: You've already got the work done. You've already found the web elements and made a listiterator here:
List<WebElement> professors = driver.findElements(By.className("tile-consultation"));
ListIterator<WebElement> theListOfProfessors = professors.listIterator();

The findElements method will return a collection of elements matching the selector. There's no need for you to retrieve the elements again like you're trying to with driver.findElement(By.cssSelector(".tile-consultation:nth-of-type(x)" inside that loop. You merely need to iterate over the listiterator theListOfProfessors that you already created. E.g. something to the effect of
while(theListOfProfessors.hasNext()) {
    WebElement elem = theListOfProfessors.next()
    // do something with elem
}


text:
Q: How I can add custom whois server to WHMCS How we can add custom whois server to WHMCS. I've an API access for ccTLD domain and want to add whois server from API.
Thanks for your help.

A: Edit /includes/whoisservers.php and add an entry in the format:
.extension|whois server|match string


text:
Q: Run script before vscode debug with a twist I'm trying to run a script before debugging my python project, but it seems like it gets stuck after the script is done.
If I'm exiting the environment that the script created (Ctrl+d) the debug session is starting, else, it's just stuck there.
I think that it might be happening because the script itself sourcing some files and at the end giving me a new shell.
I'm looking for a way to run a debugger while running the script before the run.
Any ideas?
My launch.json:
"version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "preLaunchTask": "Setup"
        }
    ]

My tasks.json:
"version": "2.0.0",
    "tasks": [
        {
            "label": "Setup",
            "type": "shell",
            "command": "script.csh"
        }

    ]


text:
Q: CSS browser compatibility Is there a tool what will load my css and then analyzes it and then generates/shows me what to add/change to make it more compatible with other browsers?

A: There are online tools launching your website in many different browsers taking a screenshot and then display them to you. That way you can check by yourself!
Just google for it or try http://browsershots.org/

A: A sitebuilder's job is not just to write some CSS that he thinks is cool. It is also a part of the job, to test it against different browsers, the number depending on which ones are supported in the project.
I don't think there can be a tool that can do our job instead of us. All that a sitebuilder can and should do, is collecting knowledge, experience and keeping up with the browsers and techniques. There are no exact rules how to handle cross-browser issues. There are loads of best practices, tips and tricks, and it's always the sitebuilder who has to decide which one to use in that certain situation.
What we have, is great tools to check out our pages in certain browsers, one being what @Thorben suggested.
And I have to add that this is just my opinion, feel free to disagree and argue :).


text:
Q: Restart activity - dealing with two fragments into a container I have an activity that has a container. And i have two fragments that I'm replacing into this container. The fragments are fragmentList and fragmentDetail
First time I'm adding the list fragment into the container
MainActivity OnCreate
 if (savedInstanceState == null) {
    ListFragment listFragment = new ListFragment();
    ft.add(R.id.fragment_container, listFragment, "LIST");
    ft.commit();
}

When the user clicks on the list, I replace the container with the detail fragment
ActionButton
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, detailFragment);
fragmentTransaction.commit();

http://www.vogella.com/tutorials/Android/images/xfragmentsusage10.png.pagespeed.ic.MkyF4ZO5Hr.png
The problem came when I restart the activity. How I can know if I need to request the list data again, or if the detail fragment are shown? Because in my onResume method both fragments are null.

A: you are already checking the savedInstanceState which is your first step
check this document for details:
http://developer.android.com/intl/es/training/basics/activity-lifecycle/recreating.html
the key is very simple, just save your current state in the onSaveInstanceState method, and restore the state on onRestoreInstanceState
the savedInstanceState is a bundle , Bundle objects are used to store and pass data between activities and fragments and so, you need to store a boolean variable in it to determine which fragment are you showing, and restore this fragment on resume according to this boolean flag

A: You can use
getFragmentManager().FindFragmentByTag(string tag)

And check if it is null and then you can check isVisible on the fragment returned, generally you'll need to reset your adapters as well


text:
Q: Python IndexError: Tuple out of range Could someone help me with this?
I have looked online and already on Stackoverflow.
I also used the PyCharm debugger but that also does not get me any further. I did get the debugger running, but I was not able to find the issue.
While debugging I did notice that I did not get any value in make_boarding_cards. in _passenger_seats, I do get a value.
My guess is that the problem should be somewhere in _passenger_seats, but I just can't find it.
I have to say am I new to Python so I will need some help for the near future.
This is the error message from the Python Console:
>>> from airtravel import *
>>> f = make_flight()
>>> f.make_boarding_cards(console_card_printer)
Traceback (most recent call last):
  File "/usr/lib/python3.4/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/home/johanvergeer/Documenten/Training/Pluralsight/Python-Fundamentals/airtravel.py", line 104, in make_boarding_cards
    card_printer(passenger, seat, self.number(), self.aircraft())
  File "/home/johanvergeer/Documenten/Training/Pluralsight/Python-Fundamentals/airtravel.py", line 150, in console_card_printer
    "  |".format(passenger, flight_number, seat, aircraft)
IndexError: tuple index out of range

This is the code I have:
The last two lines are there just for debugging purposes.
class Flight:
    """A flight with a particular passenger aircraft"""

    def __init__(self, number, aircraft):
        if not number[:2].isalpha():
            raise ValueError("No airline code in '{}'".format(number))
        if not number[:2].isupper():
            raise ValueError("Invalid airline code '{}'".format(number))
        if not (number[2:].isdigit() and 4 >= len(number[2:]) >= 3):
            raise ValueError("Invalid route number '{}'".format(number))
        self._number = number
        self._aircraft = aircraft

        rows, seats = self._aircraft.seating_plan()
        self._seating = [None] + [{letter: None for letter in seats} for _ in
                                  rows]

    def number(self):
        return self._number

    def airline(self):
        return self._number[:2]

    def aircraft(self):
        return self._aircraft

    def _parse_seat(self, seat):
        """Parse a seat designator into a valid row and letter.

        Args:
            seat: a seat designator such as 12F.

        Returns:
            A tuple containing an integer and a string for row and seat.
        """
        row_numbers, seat_letters = self._aircraft.seating_plan()

        letter = seat[-1]
        if letter not in seat_letters:
            raise ValueError("Invalid seat letter {}".format(letter))

        row_text = seat[:-1]
        try:
            row = int(row_text)
        except ValueError:
            raise ValueError("Invalid seat row {}".format(row_text))

        if row not in row_numbers:
            raise ValueError("Invalid row number {}".format(row))
        return row, letter

    def allocate_seat(self, seat, passenger):
        """Allocate a seat to a passenger.

        Args:
            seat: A seat designator such as '12C' or '21F'.
            passenger: The passenger name.

        Raises:
            ValueError: If the seat is unavailable.
        """

        row, letter = self._parse_seat(seat)

        if self._seating[row][letter] is not None:
            raise ValueError("Seat {} already occupied".format(seat))

        self._seating[row][letter] = passenger

    def relocate_passenger(self, from_seat, to_seat):
        """Relocate a passenger to a different seat.

        Args:
            from_seat: The existing seat assigned to the passenger to be moved.
            to_seat: The new seat designator.
        """

        from_row, from_letter = self._parse_seat(from_seat)

        if self._seating[from_row][from_letter] is None:
            raise ValueError(
                "No passenger to relocate in seat {}".format(from_seat))

        to_row, to_letter = self._parse_seat(to_seat)

        if self._seating[to_row][to_letter] is not None:
            raise ValueError("Seat {} is already occupied".format(to_seat))

        self._seating[to_row][to_letter] = self._seating[from_row][from_letter]
        self._seating[from_row][from_letter] = None

    def num_available_seats(self):
        return sum(sum(1 for s in row.values() if s is None)
                   for row in self._seating
                   if row is not None)

    def make_boarding_cards(self, card_printer):
        for passenger, seat in sorted(self._passenger_seats()):
            card_printer(passenger, seat, self.number(), self.aircraft())

    def _passenger_seats(self):
        """ An iterable series of passenger seating allocations"""
        row_numbers, seat_letters = self._aircraft.seating_plan()
        for row in row_numbers:
            for letter in seat_letters:
                passenger = self._seating[row][letter]
                if passenger is not None:
                    yield (passenger, "{}{}".format(row, letter))

class Aircraft:
    def __init__(self, registration, model, num_rows, num_seats_per_row):
        self._registration = registration
        self._model = model
        self._num_rows = num_rows
        self._num_seat_per_row = num_seats_per_row

    def registration(self):
        return self._registration

    def model(self):
        return self._model

    def seating_plan(self):
        return (range(1, self._num_rows + 1),
                "ABCDEFGHJK"[:self._num_seat_per_row])

def make_flight():
    f = Flight("BA758", Aircraft("G-EUPT", "Airbus A319", num_rows=22,
                                 num_seats_per_row=6))
    f.allocate_seat("12A", "Guido van Rossum")
    f.allocate_seat("15F", "Bjorne Stroustrup")
    f.allocate_seat("15E", "Anders Hejlsberg")
    f.allocate_seat("1C", "John McCarthy")
    f.allocate_seat("1D", "Richard Hickey")
    return f

def console_card_printer(passenger, seat, flight_number, aircraft):
    output = "| Name : {0}" \
             "  Flight : {1}" \
             "  Seat: {2}" \
             "  Aircraft : {4}" \
             "  |".format(passenger, flight_number, seat, aircraft)
    banner = "+" + "-" * (len(output) - 2) + "+"
    border = "|" + " " * (len(output) - 2) + "|"
    lines = [banner, border, output, border, banner]
    card = "\n".join(lines)
    print(card)
    print()

if __name__ == "__main__":
    make_flight()._passenger_seats()

If someone could also tell me how I could have interpreted the error message or maybe used the debugger in another way I would be greatful.

A: Try this, you have {4} instead of {3}
output = "| Name : {0}" \
         "  Flight : {1}" \
         "  Seat: {2}" \
         "  Aircraft : {3}" \
         "  |".format(passenger, flight_number, seat, aircraft)

A: Change {4} to {3} and it should work.

A: output = "| Name : {0}" \
         "  Flight : {1}" \
         "  Seat: {2}" \
         "  Aircraft : {4}" \
         "  |".format(passenger, flight_number, seat, aircraft)

You have typo in your output formatting: Aircraft : {4}. There are only 4 arguments in .format() so there is no {4} item. Change it to {3}


text:
Q: Is it theoretically possible to create a 'time bubble', where inside the bubble time will stop or at least slow down radically? I am a layman who dabbles online in physics, I thought this would be cool and has probably been done in sci fi already, but was wondering if it were actually possible.

A: Sure you can!  You will need:

*

*One (1) large spherical shell of ordinary matter

It can be shown that inside a spherical shell like this, the amount of time $\tau$ experienced by an observer at rest inside is related to the amount of  time experienced by an observer at rest very far away from the shell by
$$
\tau = \sqrt{1 - \frac{2 G M}{R c^2}} t
$$
where $M$ is the total mass of the shell and $R$ is its radius.
The smaller this square root factor is, the slower time will run inside the shell compared to outside the shell.  In principle, you can make this square root factor as small as you like by increasing the mass of the shell and/or decreasing its radius.  Note, however, that if the mass gets too big or the radius gets too small, the shell will collapse into a black hole, along with any hapless observers who happen to be inside.  This is undesirable in most situations.
In practical terms, a large spherical shell made out of "everyday" materials (i.e., those we have the technology to currently manufacture) will not be able to support its own weight, and it will collapse inwards on itself at a mass well below that required to form a black hole.  This may also have deleterious effects on anyone inside the shell at the time.

A: Very common and close to this is Gravitational Time Dilation.  If you are outside of a gravitational field and looking in, the things within the gravitational field are moving through time more slowly than the things far from the field.
This effect is fairly small for small planets, like the earth, but some classic examples on Earth are: 1) GPS, which uses very precise timing, needs to be corrected for this effect because we are moving through time more slowly than the satellites because we are in a stronger field; but that correction is in the nanosecond range. 2) Over the age of the earth, the core is about 2.5yrs younger than the surface.  This dilation effect is much more significant in larger gravitational fields, and gets totally warped in a black hole.
But, to be clear, wherever you are, it always feels locally like time is moving along at a normal speed.  It's only when you look at something else in a different circumstance that you would perceive a time dilation.

A: Dilating time inside a bubble (and then getting something back out of it) is possible, but you have to send the bubble on a journey. Strap a really big rocket and an unreasonably huge amount of fuel and armor to the bubble and send it on a long round trip. Either boost it up to close to the speed of light relative to the launch pad, fly in a big loop, come back, and boost back down to zero relative velocity; or fly to the nearest supermassive black hole, park in low orbit for a while, then boost back out to the original distance from the SMBH. In either circumstance, a clock in the bubble will measure much less time to have passed than does a clock at the launch pad.