text:
Q: Systemd service that only runs when USB Drive is mounted I've been searching for an elegant way of automating a very tedious process.
This is the workflow I want to achieve:

*

*Plug in the USB Disk (single partition)

*sdX1 gets automatically mounted to /mnt/data with some mounting options

*Some systemd services are started (which interact with the files in the mountpoint.

*I manually issue a command to unmount the drive.

*Services get automatically terminated.

I've been experimenting with Transmission, so I have the following service:
[Unit]
Description=Transmission BitTorrent Daemon
After=network.target
After=mnt-data.mount

[Service]
User=transmission
Type=notify
ExecStart=/usr/bin/transmission-daemon -f --log-error
ExecReload=/bin/kill -s HUP $MAINPID
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target
WantedBy=mnt-data.mount

And this is my udev rules file:
SUBSYSTEMS=="usb", ATTRS{idProduct}=="1153", ACTION=="add", ENV{SYSTEMD_WANTS}=="transmission.service"
I thought managed to get the service started when the drive gets mounted but I can't get this to behave.
I appreciate your help.
EDIT: This seems to be a bit harder than what I assumed since udisks doesn't appear to talk to systemd. When I unmount drive via systemctl stop mnt-data.mount the service gets stopped, but if I unmount any other way, the service continues to run.


text:
Q: Center percentages in pie chart in R I am in the process of creating a pie chart in R using ggplot2. So far everything has worked great, only the percentages don't fit to their corresponding section.
Can anyone tell me what could be the reason for this? I have already tried many things but nothing has worked.
Many thanks and greetings
datE = data.frame(
  group = c("A","B","C","D"),
  value = c(41,18,30,19)
)

ei <- ggplot(datE, aes(x="", y=value, fill=group))+
  geom_bar(width = 1, stat = "identity")
pieE <- ei + coord_polar("y")
blank_themeG <- theme_minimal()+
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    plot.title=element_text(size=14, face="bold")
  )
pieE + scale_fill_brewer("group") + blank_themeG +
  theme(axis.text.x=element_blank()) +
  geom_text(aes(y = value/3 + c(0, cumsum(value)[-length(value)]),
                label = percent(value/100)), size=5)

I tried to change something in geom_text, but it didn't work.

A: You can simply use position_stack(vjust = 0.5) on the values instead of calculating the position yourself:
pieE + scale_fill_brewer("group") + blank_themeG +
  theme(axis.text.x=element_blank()) +
  geom_text(aes(y = value, label = percent(value/100)), size = 5,
            position = position_stack(vjust = 0.5))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql : sql select query if condition parameter is null then ignore the parameter I have an Mysql query
SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = ?
    AND DESIGNATION = ?
    AND DISTRICT = ?
    AND CIRCLE = ?

And quite possible any 1 or 2 or 3 of the parameter (?) can be empty or null.

so what should I do so that the empty parameters are totally Ignore
  in the where clause and only search for the non-empty parameter in the
  table.

How can I achieve this
Please help..
The query must be compatible mysql. Thanks

A: You could add the input parameters twice and make the query like this:
SELECT *
FROM EMPLOYEE
WHERE (DEPARTMENT = ? OR ? IS NULL)
    AND (DESIGNATION = ? OR ? IS NULL)
    AND (DISTRICT = ? OR ? IS NULL)
    AND (CIRCLE = ? OR ? IS NULL)

So on the first and second '?' you bind the same value.
Alternatively (and arguably better), you can build the SQL dynamically, and leave out certain parts of the where clause if it doesn't apply. You can concat the strings to get the basic SQL and still use bind parameters.


text:
Q: JSON.parse(fs.readFileSync()) returning a buffer - string of numbers I'm using a simple Node.js to pull information from a valid jsonfile (checked with JSLint), but the code i'm using doesn't return the expected value:
        squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json'));

and it returns:
{ type: 'Buffer', data:
[ 123,
 10,
 32,
 32,
 34,
 97,
 99,
 ... 548 more items ] }

Any reason as to why this happens?

A: fs.readFileSync() returns a Buffer if you don't specify an encoding.
https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options
So, tell fs.readFileSync() what encoding to use:
squadJSON = JSON.parse(fs.readFileSync('./squads/squad' + whichSquad + '.json', 'utf8'));

A: The "why" has been answered by Sidney, but a better "what to do" would be to use require(), which supports parsing valid JSON files synchronously and returning the result as an object:
squadJSON = require('./squads/squad' + whichSquad + '.json');

or even nicer, using an ES6 template literal:
squadJSON = require(`./squads/squad${whichSquad}.json`);

One notable difference using require() is that it resolves relative paths from __dirname, which is the directory path of the current module, whereas fs methods resolve relative paths using process.cwd(), or "current working directory". It is the directory within a shell session from which the main module of the program is executed by node.
Hopefully the examples below demonstrate how their relative path resolution differs:
To make require(...) behave like JSON.parse(fs.readFileSync(..., 'utf8')):
const { resolve } = require('path');

function readFileSyncJson (path) {
  return require(resolve(process.cwd(), path));
}

And to make JSON.parse(fs.readFileSync(..., 'utf8')) behave like require(...):
const { resolve } = require('path');

function requireJson (path) {
  return JSON.parse(fs.readFileSync(resolve(__dirname, path), 'utf8'));
}


text:
Q: How to fix "Attempting to unpack a non-sequence" I have a server as follows:
import string
import zmq

host = '127.0.0.1'
port = 6789
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind('tcp://%s:%s' % (host, port))

with open('mammoth.txt', 'rt') as poem:
    words = poem.read()
for word in words.split():
    word = word.strip(string.punctuation)
    data = word.encode('utf-8')
    if word.startswith(('a','e','o','u','A','e','i','o','u')):
        pub.send_multipart([b'vowels', data])
if len(word) == 5:
    pub.send_multipart([b'five', data])

and a client:
import string
import zmq

host = '127.0.0.1'
port = 6789

ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect('tcp://%s:%s' % (host, port))
sub.setsockopt(zmq.SUBSCRIBE, b'vowels')
sub.setsockopt(zmq.SUBSCRIBE, b'five')
while True:
    topic, word = sub.recv_multipart()
    print(topic, word)

Specifically, the:
topic, word = sub.recv_multipart()

is giving me an unpacking sequence issue.
I am a little bit out of practice, and not sure how to get around this.


text:
Q: Why do dotfiles without extension appear as folders in Finder (Ventura)? I recently moved to a new Mac with a clean install of MacOS Ventura 13.1 on an M1 Pro. I discovered that some files in my home folder show as folders in Finder, while still being files. I cannot get rid of it and have no idea, how that could happen.

*

*It seems to only happen to files starting with a dot and no extension.

*File type seems to be fine as there is no chevron next to the icon

*It also happens with the guest user.

Thanks for any ideas or help!

*

*Am I doing something wrong?

*What could be the reason?

*How could I fix it?

Finder

Terminal


text:
Q: Can I rely on the LINQ ToArray() always returning a new instance? I'm looking for an easy way to clone off an IEnumerable<T> parameter for later reference. LINQ's ToArray extension method seems like a nice, concise way to do this.
However, I'm not clear on whether it's always guaranteed to return a new array instance. Several of the LINQ methods will check the actual type of the enumerable, and shortcut if possible; e.g., Count() will see if the method implements ICollection<T>, and if so, will directly read its Count property; it only iterates the collection if it has to.
Given that mindset of short-circuiting where practical, it seems that, if I call ToArray() on something that already is an array, ToArray() might short-circuit and simply return the same array instance. That would technically fulfull the requirements of a ToArray method.
From a quick test, it appears that, in .NET 4.0, calling ToArray() on an array does return a new instance. My question is, can I rely on this? Can I be guaranteed that ToArray will always return a new instance, even in Silverlight and in future versions of the .NET Framework? Is there documentation somewhere that's clear on this point?

A: For non-empty collections, ToArray will always return a new array - making it change to return an existing value would be a horribly breaking change, and I'm utterly convinced that the .NET team wouldn't do this. It's an important thing to be able to rely on, in terms of the effect of modifying the resulting array. It's a shame it's not documented :(
There are lots of subtle bits of behaviour in LINQ to Objects which probably aren't worth relying on, but in this case it's such a massive bit of behaviour, I would be absolutely astonished for it to change.
Short-circuiting is great when it doesn't affect behaviour, but generally LINQ to Objects is pretty good about only optimizing in valid cases. You might want to look at the two posts in my Edulinq series covering optimization.
For empty source collections, some versions will return a different empty array on each call, and some will return the same empty array on each call. While that could break code, it's much less problematic than a change of implementation to say "if it's already an array, just return it" would be: empty arrays are naturally immutable, so the only way you'll be able to observe the difference is if you compare for reference identity.
Example:
var empty1 = new string[0];
var empty2 = new string[0];

var array1 = empty1.ToArray();
var array2 = empty2.ToArray();

// Prints True in some versions, and False in others
Console.WriteLine(ReferenceEquals(array1, array2));

A: Since that ToArray method is internal to the .NET framework, I wouldn't stake my life on MS never changing it. However, what I would do, is to add a Unit Test asserting that ToArray returns a new array instance.
Assert.AreNotSame(myArray, myArray.ToArray());

That way, if you later change .NET framework versions, you will automatically know if the functionality changes.

A: Update: Jon has updated the accepted answer to cover this case.
The accepted answer is wrong as of this writing.
If your IEnumerable<T> is empty, you'll get back the singleton Array.Empty<T> instance.
https://source.dot.net/#System.Linq/EnumerableHelpers.Linq.cs,75
via https://source.dot.net/#System.Linq/System/Linq/ToCollection.cs,10


text:
Q: Displaying a mobile version of responsive component without resizing the browser window Making a document for the designers that displays the desktop and mobile examples of each visual component in a style library.  Client wants to see the examples of each on the page at the same time.
Currently doing this by putting it in an iframe, similar to here.  Unfortunately the iframe solution is causing odd complications and side-effects.
I was wondering if theres a better/simpler way I can tell the container of the mobile example to use the mobile breakpoint media queries?


text:
Q: Spring-Mongo : mapping mongo document field/s to BasicDBObject/Map of BasicDBObject of an Entity I have an entity ProjectCycle mapped to mongo DB collection ProjectCycle. I am trying to retrieve 2 fields, _id and Status. I am able to retrieve both like the following
@Document(collection="ProjectCycle")
public class ProjectCycle {
    @Id
    private String id;
    @Field("Status")
    private String status;
//getters and setters
}

Application.java

    Query query = new Query();
    query.fields().include("Status");
    Criteria criteria = new Criteria();
    criteria.and("_id").is("1000");
    query.addCriteria(criteria);
    Iterable<ProjectCycle> objectList = mongoOperations.find(query, ProjectCycle.class);
    for(ProjectCycle obj : objectList) {
        System.out.println("_id "+obj.getId());
        System.out.println("status "+obj.getStatus());
    }

Output

_id 1000
status Approved

But, the problem is when i use an Entity with field private DBObject basicDbObject; instead of private String status; i am getting value as null instead of Approved
I have tried like the following
public class ProjectCycle {
    @Id
    private String id;
    private DBObject basicDbObject;
    //getter & setter
}

What I am trying to achieve is that, the collection 'ProjectCycle' is very large and creating a POJO corresponding to it is quiet difficult. Also I am only reading data from mongoDB. So creating the entire POJO is time wasting and tedious.

*

*How I can achieve mapping between any field/fields from mongo Collection to entity?.

*Will it be possible to create a Map<String, BasicDBObject> objectMap; to fields returned from query? I am using Spring-data-mongodb for the same.

Version details
Spring 4.0.7.RELEASE
spring-data-mongodb 1.7.2.RELEASE

A: Try mapping your query like below.
Iterable<BasicDBObject> objectList = mongoOperations.find(query, BasicDBObject.class, collectionname);

for(BasicDBObject obj : objectList) {
    System.out.println("_id "+obj.get("id"));
    System.out.println("status "+obj.get("status"));
}


text:
Q: WebScraping javascript page in python Hello World,
New in Python, I am trying to webscrape a javascript page : https://search.gleif.org/#/search/
Please find below the result from my code (using request)
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta content="width=device-width,initial-scale=1" name="viewport"/>
<title>LEI Search 2.0</title>
<link href="/static/icons/favicon.ico" rel="shortcut icon" type="image/x-icon"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,600,700,900&subset=cyrillic,cyrillic-ext,greek,greek-ext,latin-ext,vietnamese" rel="stylesheet"/>
<link href="/static/css/main.045139db483277222eb714c1ff8c54f2.css" rel="stylesheet"/>

The question:
Instead of retrieving the above script:
    "src="/static/js/manifest.2ae2e69a05c33dfc65f8.js" type="text/javascript""
I would like to have the content of the table in order to store it.
Table that I want to scrape

A: Following code is written using PySelenium.
import time
from selenium import webdriver

country = []
legal_name = []
lei = []

driver = webdriver.Chrome()
driver.implicitly_wait(5)

for i in range(1,30395):
    driver.get('https://search.gleif.org/#/search/fulltextFilterId=LEIREC_FULLTEXT&currentPage='+str(i)+'&perPage=50&expertMode=false#results-section')

    time.sleep(5)

    country += [i.get_attribute('innerHTML') for i in driver.find_elements_by_xpath('//*[@class="table-cell country"]/a')]
    legal_name += [i.get_attribute('innerHTML') for i in driver.find_elements_by_xpath('//*[@class="table-cell legal-name"]/a')]
    lei += [i.get_attribute('innerHTML') for i in driver.find_elements_by_xpath('//*[@class="table-cell lei"]/a')]

Logging in (Change this with the respective elements.)
driver.find_element_by_id("UserName").send_keys("xxxx")
driver.find_element_by_name("Password").send_keys("yyyy")
driver.find_element_by_class("loginButton").click()

Get page content
print(driver.page_source)


text:
Q: IE CSS hover loses focus when over img I am working on making some drop-down menus. Our designer prescribed a gap between the mega menu and the rollover item. Normally, no problem at all. I just dropped a transparent div tag there in the middle, and we're good to go, right? Nope. Well, everything (FireFox, Chrome) BUT IE works. The problem is the image that is below the gap between the menus. If I remove the image or turn the extension div white, all is well. But I would like to have the best of both worlds. Is this possible? Is there more information that you need to be of assistance?
Thanks,
JMax
HTML:

            Apparel

Jacket

Male

Female

Shirt

Male

Female

Officer

Item 1

CSS
    #navigation { left:0px; top:25px; position:relative; width:100%; margin: 0 auto; }
    #navMenu { left:0px; list-style:none outside none; text-align:justify;  }
    .navItem { /*float: left;*/ position:relative; margin-right:5px; width:inherit; display:inline-block; *display:inline;  }
    .trigger { padding:2px 0; font-weight:bold; text-decoration:none;  color:#adadad; }
    .trigger:hover, .trigger.hover { color:#332d53; border-bottom:solid 1px #f5d371;}
    .stretch {width: 100%; display: inline-block; *display: inline; zoom: 1; font-size: 0; line-height: 0; }
    #navMenu:first-child .trigger { margin-left:0px; }

    .sub-level { border:1px solid #CCC; width:775px; background-color:#FFFFFF; position:fixed; display:none; height:190px; margin-top:25px; margin-left:-35px; z-index:1001;}
    .extension { width:775px; position:fixed; height:30px; display:none; z-index:1000; /*background-color:#FFF; */}
    .categories { list-style:none outside none; padding-left:0px; height:160px;  font-weight:bold; font-size:10px; color:#adadad; top:0px; margin-top:10px; margin-bottom:20px; border-right: solid #DDDDDD 2px;  }
    .categories li { padding:5px; text-transform: uppercase; padding-left:20px;}
    .categories li:hover { /*background-color:#f5d371;*/ color:#332d53; }

A: Could you maybe give the spacer-div a transparent gif/png as background? Then there might be something for IE to "hit". Just at thought though

A: I had the exact same problem today, in a case where you have ul > li > a, the ul or anchor must have a background (color suffices) so IE8- doesn't lose focus when hovering an underlying image (it gives a crap on z-indexes). If the background is set only on the anchors, there must be no gap between them. I had a background on the lis and didn't have a clue what's wrong... cursed over IE for a while now...


text:
Q: How can I select by multiple columns based on multiple values? I tried searching for an answer, but didn't find anything, and I'm not sure if I'm describing this in the best way, but here goes...
So, I have a MySQL database, and a website that the user can select 0-3 categories to search the database on.
For example, if I have records like this in the DB:
id|cat1|cat2|cat3
-----------------
1 |  a |  b |  c
2 |  a |    |
3 |  z |  b |  a
4 |  y |  a |
5 |  b |  c |  a

I'm trying to figure out a way so if the user selects, for example, 1 category to search on and it's "a", then it would return records [1,2,3,4,5], and if the user selects 2 categories to search on, like "a" and "b" it would return records [1,3,5], and it the user selected 3 categories, like "a" and "c" and "b", then it would return [1,5].
There is no guarantee on sequence, neither in the DB nor in what the user enters.
I've gotten my query to where it can select records that have any of the entered categories, but I can't seem to figure out how to get to return only records that have ALL the categories provided.
Does anyone know how to do that?
Thanks!
Here's what I have so far, it's messy and I've just been kind of shooting in the dark here, haha, but here it is (in this example, the categories "Church" and "Occupation" were selected):
SELECT * FROM all_terms
WHERE
(      (subject1 in ('Church', 'Occupation') OR subject1 IS NULL OR subject1 = '')
   AND (subject2 in ('Church', 'Occupation') OR subject2 IS NULL OR subject2 = '')
   AND (subject3 in ('Church', 'Occupation') OR subject3 IS NULL OR subject3 = '')
   AND (     (subject1 IS NOT NULL && subject1 != '')
          OR (subject2 IS NOT NULL && subject2 != '')
          OR (subject3 IS NOT NULL && subject3 != '')))

A: The general query structure you need is something like this:
Give a user selection of a:
SELECT id
FROM table1
WHERE 'a' IN (cat1, cat2, cat3)

Give a user selection of a, b:
SELECT id
FROM table1
WHERE 'a' IN (cat1, cat2, cat3)
  AND 'b' IN (cat1, cat2, cat3)

Give a user selection of a, b, c:
SELECT id
FROM table1
WHERE 'a' IN (cat1, cat2, cat3)
  AND 'b' IN (cat1, cat2, cat3)
  AND 'c' IN (cat1, cat2, cat3)

See this SQL fiddle
You could use a loop to dynamically generate the right statement depending on the user input, something like:
Given $arr is an array of user input:
$sql = 'SELECT id FROM table1 WHERE ';

$and = '';

foreach ($arr as $a) {
    $sql .= $and . "'$a' IN (cat1, cat2, cat3) ";
    $and = 'AND ';
}

For example, if $arr = array('a', 'b'), then the query generated would be:
SELECT id
FROM table1
WHERE 'a' IN (cat1, cat2, cat3)
  AND 'b' IN (cat1, cat2, cat3)

See this PHP fiddle

A: This will do what you're looking for if each category is unique.  You have to set your $mysqli connection above.
$query = "
SELECT *
FROM table
WHERE
cat1 = ? AND cat2 = ? AND cat3 = ? AND cat4 = ?
";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ssss", $cat1, $cat2, $cat3, $cat4);
$stmt->execute();

If the categories aren't unique, and just sequential according to what the user selected it may be more difficult.
Edit: Check this answer for maybe some insight if our questions are the same.


text:
Q: Possible to use the same ssd for a Windows and a Mac laptop via different partitions? So my main laptop is a MacBook which runs on a Samsung 850 evo ssd, has 2 partitions- one runs El Capitan and other is formatted as exfat.
My questions is - how can I use this very ssd to run Windows 10 on my other (HP) laptop off the exfat partition?
Situation as of now - I have a bootable usb of Windows 10 but it asks for a cd disk, and I can't seem to find a way to use the usb.
What I fear is that by using a recovery cd to install Windows, the program might overwrite over all my existing data. What I want is to just install Windows on the exfat partition
I understand that unlike Mac, Windows has to be installed separately for each and every computer, I can't use some other laptops ssd to boot this laptop.
Any help or comments are appreciated. Thank you!
Edit: Im gonna use the ssd as an internal ssd on the HP laptop,  not as an external with an enclosure. Its my fathers old work laptop and i have standing instructions to not to edit anything on it (but the damn thing is  running windows 7), since there will come a day when he'll have to return it. This is why i wanna 'preserve' the partition with el capitan. I will not be connecting-disconnecting it again and again. Jist twice. I have since formatted the partition in NTFS.
**so my ultimate question is this : I have a drive with two partitions,  I want to install windows 10 on just one while the other partition remains untouched. Since its too messy to install windows on 1 device and then port it to other,  I have inserted the ssd in the new laptop.  How do I move forward with the installation? **

A: I think this might be a better fit for Super User as it's mainly about PC/Windows rather than Mac.
However, as a rough guide -
you'd do far better to clone the Mac's boot & recovery partitions to a spare drive using something like Carbon Copy Cloner then let the Windows installer [from a PC] just break the whole darn thing - which it will, it will insist on NTFS & will probably set up its own EFI & recovery partitions; and Windows won't boot easily if it's not at the beginning - then use the Mac to restore the 2 Mac partitions afterwards to the end of the disk.  This will likely need 3rd Party software, such as Paragon Hard Disk Manager
Windows also is not truly portable like macOS, so each time you move it to a different machine it will either crash/fail or require re-authorisation from Microsoft. Windows is also not too keen on booting from a removable drive.
Ultimately, I think buying a second SSD would be simplest & safest.

A: First, Windows does not run on ExFAT; Windows requires NTFS.
Secondly, this is a bad idea all around.  The SATA cables/connectors are not designed to be a device that can be connected/disconnected repeatedly.
You could potentially damage the connectors on your drive, damage the cable itself (where applicable) or worse, the connectors on the logic board.  This is not a path I would advise.
Can you do it?  Technically speaking, yes.  Should you do it?  Absolutley not.  Get a new drive.


text:
Q: Displaying code with  tags Currently I'm using

 code here

to display code. I'm pulling this information from a DB for a blog. The problem I'm having is that some of the code isn't showing. For example, in the source code I have this:

echo '

';
foreach($nameArray as $name) {
    if($countervar == $half) {
        echo '

';
        echo'

';
    }
    echo '
$name
';
    ++$i;
}
echo '

';
echo '
';
?>

But all that shows up is this:

echo '';
foreach($nameArray as $name) {
if($countervar == $half) {
echo '';
echo'';
}
echo '$name';
++$i;
}
echo '

An there's some really weird formatting/spacing issues as well. Any ideas as to what is causing this? I should also mention that some of the other sets of code show up just fine.

A: You need to HTML escape the code before echoing it using the htmlspecialchars function.

A: is it escaped? if not, there is htmlspecialchars.

A: If you have XHTML you can also use CDATA sections. They are generally more readable (and pretty!) than a text with HTML encoded entities. Just don't forget to replace occasional ]]> sequences with ]]>]]><![CDATA[

A: As others have said, using htmlspecialchars()/htmlentities() will work however there is a builtin function for doing PHP syntax formatting - checkout highlight_string() and highlight_file(). And if you want even more flexibility / control have a look at Geshi
C.


text:
Q: Get a list of unmountable drives using Cocoa I would like to obtain a list of drives that are unmountable/ejectable using Cocoa/Objective-C under OS X.
I was hoping that NSWorkspace getFileSystemInfoForPath::::: would help me:
NSArray* listOfMedia = [[NSWorkspace sharedWorkspace] mountedLocalVolumePaths];
NSLog(@"%@", listOfMedia);

for (NSString* volumePath in listOfMedia)
{
    BOOL isRemovable = NO;
    BOOL isWritable  = NO;
    BOOL isUnmountable = NO;
    NSString* description = [NSString string];
    NSString* type = [NSString string];

    BOOL result = [[NSWorkspace sharedWorkspace] getFileSystemInfoForPath:volumePath
                                                             isRemovable:&isRemovable
                                                              isWritable:&isWritable
                                                              isUnmountable:&isUnmountable
                                                                description:&description
                                                                       type:&type];
    NSLog(@"Result:%i Volume: %@, Removable:%i, W:%i, Unmountable:%i, Desc:%@, type:%@", result, volumePath, isRemovable, isWritable, isUnmountable, description, type);
}

Output:
...
Result:1 Volume: /Volumes/LR Photos, Removable:0, W:1, Unmountable:0, Desc:hfs, type:hfs
...

"LR Photos" is an external drive (connected via Thunderbolt) that should be removable and/or unmountable (or, at least I think it should be). :)
Should I be going about this a different way?
Thanks in advance!

A: You can use diskArbitration framework.
#import <DiskArbitration/DiskArbitration.h>
   +(NSMutableArray *)getListOfEjectableMedia
{
    NSArray *mountedRemovableMedia = [[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:nil options:NSVolumeEnumerationSkipHiddenVolumes];
    NSMutableArray *result = [NSMutableArray array];
    for(NSURL *volURL in mountedRemovableMedia)
    {
        int                 err = 0;
        DADiskRef           disk;
        DASessionRef        session;
        CFDictionaryRef     descDict;
        session = DASessionCreate(NULL);
        if (session == NULL) {
            err = EINVAL;
        }
        if (err == 0) {
            disk = DADiskCreateFromVolumePath(NULL,session,(CFURLRef)volURL);
            if (session == NULL) {
                err = EINVAL;
            }
        }
        if (err == 0) {
            descDict = DADiskCopyDescription(disk);
            if (descDict == NULL) {
                err = EINVAL;
            }
        }
        if (err == 0) {
            CFTypeRef mediaEjectableKey = CFDictionaryGetValue(descDict,kDADiskDescriptionMediaEjectableKey);
            CFTypeRef deviceProtocolName = CFDictionaryGetValue(descDict,kDADiskDescriptionDeviceProtocolKey);
            if (mediaEjectableKey != NULL)
            {
                BOOL op = CFEqual(mediaEjectableKey, CFSTR("0")) || CFEqual(deviceProtocolName, CFSTR("USB"));
                if (op) {
                    [result addObject:volURL];
                }
            }
        }
        if (descDict != NULL) {
            CFRelease(descDict);
        }
        if (disk != NULL) {
            CFRelease(disk);
        }
        if (session != NULL) {
            CFRelease(session);
        }
    }
    return result;
}

A: Unfortunately getFileSystemInfoForPath: is not really the right way to do this. What removable means is that the volume is on removable media such as a CD or DVD. In practice unmountable seems to give the same results as removable. See for example, this post on results using getFileSystemInfoForPath. So unless you want to simply know if a volume is on removable media, you'll need to use another technique.
What you really want to check is the connection bus type of the volume. Firewire, USB, Thunderbolt, etc. are unmountable in the sense you mean. You can see this information in Disk Utility if you select the volume and push the "Info" button under "Connection Bus". Getting this information programmatically is much harder and as far as I can tell is only possible using the IOKit. Details are in Apple's documentation on Accessing Hardware from Applications.

A: you can use command line version of Disk Utility app that is "diskutil", run it with parameter "list" and pipe output and get it in your program ( don't need to use cocoa ).


text:
Q: MySQL - 1111 - Invalid use of group function I'm getting an error of group function while trying to get the volatage stability per hour.
table as an image below.
table-image
SELECT  ip,
        SUM(CASE HOUR(time) WHEN '1' THEN CAST(AVG(IF(volt=0,0,1)) AS DECIMAL(2,1)) ELSE 0 END) AS '1',
        SUM(CASE HOUR(time) WHEN '2' THEN CAST(AVG(IF(volt=0,0,1)) AS DECIMAL(2,1)) ELSE 0 END) AS '2',
        SUM(CASE HOUR(time) WHEN '3' THEN CAST(AVG(IF(volt=0,0,1)) AS DECIMAL(2,1)) ELSE 0 END) AS '3'
FROM UPS_Status
WHERE time BETWEEN NOW() - INTERVAL 24 hour AND NOW()
GROUP BY ip, HOUR(time)

A: HOUR(time) does not belong in the GROUP BY clause.  Try removing it:
SELECT
    ip,
    SUM(CASE HOUR(time) WHEN 1 THEN CAST(IF(volt=0, 0, 1) AS DECIMAL(2,1)) ELSE 0 END) AS `1`,
    SUM(CASE HOUR(time) WHEN 2 THEN CAST(IF(volt=0, 0, 1) AS DECIMAL(2,1)) ELSE 0 END) AS `2`,
    SUM(CASE HOUR(time) WHEN 3 THEN CAST(IF(volt=0, 0, 1) AS DECIMAL(2,1)) ELSE 0 END) AS `3`
FROM UPS_Status
WHERE
    time BETWEEN NOW() - INTERVAL 24 hour AND NOW()
GROUP BY ip;


text:
Q: SIGPIPE in C++ determining which TCP socket is disconnected I'm using Linux/Ubuntu. I've written a pair of classes that implement a TCP server and TCP client, respectively. Part of the code is to have graceful recovery from disconnects. My only problem is with SIGPIPE. I've written code to capture the signal, but I'd like it to start the "attempt to reconnect" process on the class instance that hit the broken pipe. signal( SIGPIPE, functionname ) requires function name to be C-type function or static class method.
How can I determine which socket the SIGPIPE occurred for if I've got multiple instances of my classes in an application?

A: SIGPIPE is useless for TCP. This signal was invented for shell pipes (e.g. proc_1 | proc_2 | proc_3), because SIGINT is only delivered to the last process in the shell pipe. When the last process is killed and the previous process tries to write into its stdout it gets killed with SIGPIPE because the reader of the pipe terminated and so on, effectively killing all processes involved in the shell pipe. And this is why the signal has word pipe in its name.

Normally people ignore SIGPIPE completely when doing TCP:
// Early in main().
signal(SIGPIPE, SIG_IGN);

And/or:
ssize_t rc = send(..., MSG_NOSIGNAL);
if(rc == -1)
    // errno can be EPIPE

This way your just deal with error from send and errno is set to EPIPE.
When SIGPIPE is ignored it is not necessary to use MSG_NOSIGNAL, but it is still good practice, IMO.


text:
Q: Handling events in a Task; Handling Navigated event from WebBrowser in Task? I am rewriting some code that uses a WebBrowser object to determine when a server is ready to have a file downloaded. Overall the behavior is this, first a file is uploaded to the server, once it is uploaded the server then gets to work, as it is doing work it redirects users connected to a specific page it serves to various URLs until it is done, once it is done then the file is ready to be downloaded.
I would like to have all of this behavior in a single function call, basically GetFileFromServer(). Once this call returns then the file is at a specified file path.
The issue is when using the WebBrowser I have to handle the Navigated event to determine when the file is ready to be downloaded, this takes the program flow away from the GetFileFromServer function. I could just have a small while loop
while(fileNotDownloaded)
    Thread.Sleep(500);

But I would like to use a Task instead so that the function looks something like
public void GetFileFromServer()
{
    UploadFile();   // Blocks until file is uploaded
    DownloadFile(); // Blocks until file is downloaded
}

I have implemented UploadFile but, again, am having issues with DownnloadFile. Basically I would like my function too look like so
private void DownloadFile()
{
    var DoWebDriverTask = Task.Factory.StartNew(() =>
    {
        Boolean fileReady = false;
        WebBrowser webBrowser = new WebBrowser();
        webBrowser.Url = new Uri(MySpecificIP);
        webBrowser.Navigated += WebBrowserNavigated;

        // Sit and Spin until the specific URL is navigated to
        while(!fileReady)
            Task.WaitAll(new Task[] { Task.Delay(500) });

        DownloadFile();

        private void WebBrowserNavigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if(e.Url.AbsoluteUri.ToString().Contains("mySpecificURLString"))
                fileReady = true;
        }
    }, CancelWaitForDownloadTaskToken);
    Task.WaitAll(new Task[] { WebDriverTask });
}

But this obviously is not proper code. I also understand this is the same solution I offer above but just moved into a Task, but it does give me the behavior I want out of GetFileFromServer. Note, none of this is going on in the UI thread as is, so again, the solution I offer above is viable... But using a Task I would have the ability to cancel waiting on the download if the user wishes to.
So is there a way to handle the event Navigated within the Task as I "described" in the code above?

A: Here is how you can handle the event in the same scope of the method:
webBrowser.Navigated += (s, e) =>
{
    if (e.Url.AbsoluteUri.ToString().Contains("mySpecificURLString"))
        fileReady = true;
};

However, looping and waiting is not a very good idea, here is a better alternative:
private Task WaitBeforeDownloadFile(WebBrowser webBrowser)
{
    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

    WebBrowserNavigatedEventHandler web_browser_on_navigated = null;

    web_browser_on_navigated = (s, e) =>
    {
        if (e.Url.AbsoluteUri.ToString().Contains("mySpecificURLString"))
        {
            tcs.TrySetResult(true);

            webBrowser.Navigated -= web_browser_on_navigated;
        }
    };

    webBrowser.Navigated += web_browser_on_navigated;

    return tcs.Task;
}

This method creates a Task that completes when the Navigated event is raised and the condition you specified is met.
Here is how you would use it:
private void DownloadFile()
{
    WebBrowser webBrowser = new WebBrowser();
    webBrowser.Url = new Uri(MySpecificIP);

    //Initiate whatever here before waiting for the Navigated event

    WaitBeforeDownloadFile(webBrowser).Wait();

    //Continue here
}

Which again is not a very good thing to do. However, since you want a synchronous behavior, then you have to do it like this.
A better alternative that requires a lot of changes to how you do things is to do things asynchronously which requires a good amount of learning to do. Here is an example:
public async Task GetFileFromServer()
{
    await UploadFile();
    await DownloadFile();
}

public async Task UploadFile()
{
    ...
}

public async Task DownloadFile()
{
    WebBrowser webBrowser = new WebBrowser();
    webBrowser.Url = new Uri(MySpecificIP);

    //Initiate whatever here before waiting for the Navigated event

    await WaitBeforeDownloadFile(webBrowser);

    //Continue here
}


text:
Q: Fabric JS scaling multiple objects and center it on the canvas without scaling the canvas Is it possible to scale down every object in a canvas (my image example contain about 10 objects) and center them without scaling the canvas? (The size of the canvas is the same in both the first and second image)
See image example the first image represent the original version, and the second image represent the desired version. Given some number, all objects are shrunk but their positioning are also tweaked so that their relative distances to each other are not disrupted, while maintaining centerism. The two images seem to be of different sizes, but they are the same size.

A: Yes, you can select every object and scale them to whatever dimension you need (if I understand your question).
   var selection = new fabric.ActiveSelection(canvas.getObjects(), { canvas:canvas });

        var sizeObj = resizer(
          { width: canvas.getWidth(), height: canvas.getHeight() },
          { width: selection.width, height: selection.height });

        selection.scaleToHeight(sizeObj.height)
        selection.center();

// routine from a stackoverflow contributer
resizer(canvas, imageObj) {
    var imageAspectRatio = imageObj.width / imageObj.height;
    var canvasAspectRatio = canvas.width / canvas.height;
    var renderableHeight, renderableWidth, xStart, yStart;

    // If image's aspect ratio is less than canvas's we fit on height
    // and place the image centrally along width
    if (imageAspectRatio < canvasAspectRatio) {
      renderableHeight = canvas.height;
      renderableWidth = imageObj.width * (renderableHeight / imageObj.height);
      xStart = (canvas.width - renderableWidth) / 2;
      yStart = 0;
    }

    // If image's aspect ratio is greater than canvas's we fit on width
    // and place the image centrally along height
    else if (imageAspectRatio > canvasAspectRatio) {
      renderableWidth = canvas.width
      renderableHeight = imageObj.height * (renderableWidth / imageObj.width);
      xStart = 0;
      yStart = (canvas.height - renderableHeight) / 2;
    }

    // Happy path - keep aspect ratio
    else {
      renderableHeight = canvas.height;
      renderableWidth = canvas.width;
      xStart = 0;
      yStart = 0;
    }
    return { x: xStart, y: yStart, width: renderableWidth, height: renderableHeight }
  }


text:
Q: perl - Hash in hash - how are elements stored? I am a newbie to perl programming and having tough time to adapt from C to perl. Would greatly appreciate your help.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;

my %tgs;
$tgs{"0"}{"1"} = 01;
$tgs{"0"}{"2"} = 02;
$tgs{"0"}{"3"} = 03;
$tgs{"1"}{"1"} = 11;
$tgs{"1"}{"2"} = 12;
$tgs{"1"}{"3"} = 13;
$tgs{"2"}{"1"} = 21;
$tgs{"2"}{"2"} = 22;
$tgs{"2"}{"3"} = 23;

print Dumper(\%tgs);
exit(0);

o/p is
$VAR1 = {
          '1' => {
                   '1' => 11,
                   '3' => 13,
                   '2' => 12
                 },
          '0' => {
                   '1' => 1,
                   '3' => 3,
                   '2' => 2
                 },
          '2' => {
                   '1' => 21,
                   '3' => 23,
                   '2' => 22
                 }
        };

I have entered the hash values in the order of 1,2,3. But when i print the order is first 1 then 0 and then 2. Why is it happenning like this? Is there any way i can controle this? I need to control it because i will read this data in a foreach loop by assuming it is of the order 0 1 2 3...

A: Perl doesn't guarantee anything about the order of the keys in a hash.  If you must loop over the elements in a specific order, you can do:
for (sort keys %myhash) {
    print Dumper($tgs{$_});
}

Or if the keys aren't easily sorted, you may need to use an array with a mapping:
my %tgs;
$tgs{"0"}{"1"} = 01;
$tgs{"0"}{"2"} = 02;
$tgs{"0"}{"3"} = 03;
$tgs{"1"}{"1"} = 11;
$tgs{"1"}{"2"} = 12;
$tgs{"1"}{"3"} = 13;
$tgs{"2"}{"1"} = 21;
$tgs{"2"}{"2"} = 22;
$tgs{"2"}{"3"} = 23;

my @tag_keys = qw(1 2 3);

And then use:
foreach (@tag_keys) {
    print Dumper($tgs{$_});
}

A: Hashes are unordered, as you have discovered.  If you're familiar with "hash tables" in C, it's essentially the same thing - the keys are passed through a hashing function and the hash keys ended up sorted by the resulting hashes.  And if the hashing function is any good (it is), that order is effectively random.  Additionally, recent versions of Perl have implemented randomization functions which will cause the order of the hash keys to be different each time your program runs.  So you really, really can't count on hash keys having any particular order.
Or at least you can't... by default.
There's long been a desire for hashes which remember the order that keys were inserted, so someone invented Tie::IxHash, which acts just like a regular hash, except that it also attaches a little metadata to each key to indicate their order.


text:
Q: VueJS real SEO friendly 404 page for search engines like Google / MSN I am not VueJS programmer, but I work with in a company where we developing a VueJS website.
The website have articles. The URL is something like this:
http://example.com/here_is_news_from_sofia.htm
However if you type:
http://example.com/here_is_news_from_blabla.htm
You should go to 404 page.
I inspected several websites and stackoverflow questions, they explain how you should do catch-all router etc, so finally you get a page with "404 Not Found" text on it.
However, in ALL cases, the HTTP code send to the client is not 404, but 200.
With my team, I elaborated this:
When you go to any article, you get something like this:
<html>
    <body>
        <div id="app">
            <app />
        </div>
        <script src="/js/client.js"></script>
    </body>
</html>

Of course, if you click on a link, this page remains and everything is loaded via JS dynamically.
Then lets suppose article is not found.
VueJS will be able to show "404 Not Found" as text, but because HTTP headers are already send (HTML page is already loaded), it will not be able to send 404 code to the client.
For the same reason, VueJS can not send 301 code redirect to the client.
VueJS can incorrectly change the URL in the browser to "http://example.com/404.htm" - this is NOT a correct solution for search engines, since this is purely client-side (in-browser) "trick".
The other think it can do is to execute fancy redirect, as shown here Vue-router redirect on page not found (404) :
Vue.component("page-not-found", {
    template: "",
    created: function() {
        // Redirect outside the app using plain old javascript
        window.location.href = "/404.htm";
    }
}

This will make the browser to reload the /404.htm page from the server and if the server (Apache / Nginx) is configured correctly, it will send "correct" 404 code to the client.
However I don't think Google and MSN will recognize that http://example.com/here_is_news_from_blabla.htm is a 404 page.
Am I missing anything?

*

*Is there another way VueJS might handle this situation?

*How VueJS websites gets indexed from search engines like Google and MSN?

*Off topic bonus question - can VueJS generate visible HTML code that contains the article?

A: With client side routing, real 404 errors are hard to create. Luckily, Google is very good at detecting soft 404 errors (when your application shows "not found" text with a 200 status.) Google treats soft 404 errors just like real 404 errors. The only additional thing that would help there is adding <meta name="robots" content="noindex"> to error pages using JavaScript.
A slightly better workaround is to configure your web server to serve one page with a real 404 status. Then you can have your client side routing change the URL to that any time it detects missing content. When used in conjunction with server side rendering (SSR), even crawlers that can't process JavaScript will usually end up getting redirects to a 404 page. Server side rendering is the process of running JavaScript on the server to show rendered HTML to non-JavaScript-capable clients and all first page views.  See SSR in Vue Vue's documentation on how to set that up.
Reference: Google's recommendation for 404 errors in their crawling and indexing SEO basics guide

A: If that's a single page application, you can set up dynamic route matching with parameters with vue-router. And dynamically update your meta tags with javascript. I am using quasar vue framework, which handles all of this SEO feature.
I added slug data to the article saved in the database and use it as a route parameter.
https://quasar.dev/vue-composables/use-meta
https://router.vuejs.org/guide/essentials/dynamic-matching.html
You can use quasar vue framework, develop vue app in SSR mode and deploy it to the server.
https://quasar.dev/quasar-cli-vite/developing-ssr/handling-404-and-500-errors


text:
Q: Alembic --autogenerate producing empty migration I am trying to use Alembic for the first time and want to use --autogenerate feature described here
My project structure looks like
project/
       configuration/
                    __init__.py
                    dev.py
                    test.py
       core/
           app/
              models/
                    __init__.py
                    user.py
       db/
          alembic/
                  versions/
                  env.py
          alembic.ini

I am using Flask and SQLAlchemy and their Flask-SQLAlchemy extension. my model User looks like
class User(UserMixin, db.Model):
    __tablename__ = 'users'
    # noinspection PyShadowingBuiltins
    uuid = Column('uuid', GUID(), default=uuid.uuid4, primary_key=True,
                  unique=True)
    email = Column('email', String, nullable=False, unique=True)
    _password = Column('password', String, nullable=False)
    created_on = Column('created_on', sa.types.DateTime(timezone=True),
                        default=datetime.utcnow())
    last_login = Column('last_login', sa.types.DateTime(timezone=True),
                        onupdate=datetime.utcnow())

As described here, I modified env.py to look like
from configuration import app

alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = app.config['SQLALCHEMY_DATABASE_URI']
engine = engine_from_config(
    alembic_config,
            prefix='sqlalchemy.',
            poolclass=pool.NullPool)

and
from configuration import db

target_metadata = db.metadata

where configuration.__init__py looks like
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import dev

app = Flask(__name__)
app.config.from_envvar('SETTINGS_PT')
db = SQLAlchemy(app)

Now when I run migration
$alembic revision --autogenerate -m "Added user table"
INFO  [alembic.migration] Context impl PostgresqlImpl.
INFO  [alembic.migration] Will assume transactional DDL.
  Generating /Users/me/IdeaProjects/project/db/alembic/versions/55a9d5
  35d8ae_added_user_table.py...done

but file alembic/versions/55a9d5 has empty upgrade() and downgrade() methods
"""Added user table

Revision ID: 1b62a62eef0d
Revises: None
Create Date: 2013-03-27 06:37:08.314177

"""

# revision identifiers, used by Alembic.
revision = '1b62a62eef0d'
down_revision = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###

How come it is not able to understand that there is a new User model?
Please help

A: Everything was much simplier, just from starting read the doc i solved my issue with auto generating the migrations.
Don't forget to change
target_metadata from None to  Base.metadata in your env.py file.
target_metadata = Base.metadata

along with the import of the all models you want to track in your __init__.py of your module that consist all db models that inherits from Base model. Then you just need to import these Base in your env.py
from app.database.models import Base

that's it!

A: As per @zzzeek, after I included the following in my env.py, I was able to work with --autogenerate option
in env.py under run_migrations_online()
from configuration import app
from core.expense.models import user # added my model here

alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = app.config['SQLALCHEMY_DATABASE_URI']
engine = engine_from_config(
    alembic_config,
    prefix='sqlalchemy.',
    poolclass=pool.NullPool)

then I ran alembic revision --autogenerate -m "Added initial table" and got
def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('uuid', sa.GUID(), nullable=False),
    sa.Column('email', sa.String(), nullable=False),
    sa.Column('password', sa.String(), nullable=False),
    sa.Column('created_on', sa.DateTime(timezone=True), nullable=True),
    sa.Column('last_login', sa.DateTime(timezone=True), nullable=True),
    sa.PrimaryKeyConstraint('uuid'),
    sa.UniqueConstraint('email'),
    sa.UniqueConstraint('uuid')
    )
    ### end Alembic commands ###

Thank you Michael for all your help!

A: If you don't want your flake8 throwing unused import errors, then you can also add the Record to __all__ in your models file.
At the end of users.py
__all__ = Users

More information at - https://docs.python.org/3/tutorial/modules.html#importing-from-a-package

A: I encountered the same problem and I solved it by importing class from file (note file from directory) as following:
from db.db_setup import Base
from db.models.user import User
from db.models.course import Course

And then droped all tables and autogenerated file then run alembic revision --autogenerate again.

A: I think it's worth pointing out here that I had the same problem in the current version (0.8.4), but the method of setting metadata appears to have become more explicit: In addition to importing a model, you need to also set target_metadata (which is present in env.py but defaults to None).
The documentation suggests importing something they called Base, but it's not clear what exactly that is; importing the DeclarativeBase instance my models inherit from did nothing for me (same result as OP).
The actual comments in the code, though, suggest setting target_metadata using an actual model (ModelNameHere.metadata), which did work for me (using one model's metadata resulted in all of them being detected).

A: In my case problem was i already had target table created in database.
After i dropped this table, revision command produced filled upgrade and downgrade functions.

A: If anyone still has this problem for fastAPI on Postgresql database, do not forget to have your server running that is your uvicorn servers should be running. Then just change this line on alembic ini
sqlalchemy.url = driver://user:pass@localhost/dbname

to this
sqlalchemy.url =

Then you set the sqlalchemy url in the env.py inside the alembic folder using this just below the config = context.config:
db_string = f"postgresql+psycopg2://postgresusername:12345678@localhost:5432/mydatabase"
config.set_main_option("sqlalchemy.url", db_string)

Then import your models for example from db.base_class import Base  just before target_metadata = None , and change the target to this:
target_metadata = Base.metadata

So my ```env.py`` looks like this:
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool
from core.config import settings

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

db_string = f"postgresql+psycopg2://postgresusername:12345678@localhost:5432/mydatabase"
config.set_main_option("sqlalchemy.url", db_string)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
# target_metadata = None

from db.base_class import Base

target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.

def run_migrations_offline() -> None:
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online() -> None:
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)

        with context.begin_transaction():
            context.run_migrations()

if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()


text:
Q: Initialisation of MapFragment in Activity Failing I use the following XML code to create a MapFragment:
<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.hashcoder.eegoomain.CustomerHomeActivity"/>

And in my onCreate() method, I use the following code to initialize the map:
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_customer_home);
    createNavigationDrawerFunction();
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);  }

But, when I run this code on my phone (Redmi Note 4), it shows the following exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hashcoder.eegoomain/com.hashcoder.eegoomain.CustomerHomeActivity}: android.view.InflateException: Binary XML file line #61: Binary XML file line #61: Error inflating class fragment

And this code works fine in other devices. What am I doing wrong?


text:
Q: Qt: create a library to connect to an external resource and use it in different applications I am trying to implement a library to connect to an external resource and interact with it via an XML-based API. However I don't know how to get all the data before processing it. I am using QTcpSocket on Windows.
The way I have to interact with the resource is as follow:

*

*Connect to the server

*Send an XML message with credentials

*Get the response from the server

*Parse the XML response to extract the session ID

*Send other requests in XML with the session ID in it and parse the XML responses.

*Use the result in my application

Of course, depending on the request the message will not have the same structure so I need to parse the XML in the same function, right? And if so, how can I wait for all the data to arrive before parsing it?
Furthermore, as mentioned, it is under a Windows environment so I cannot use "waitForReadyRead" since as stated in the documentation:

This function may fail randomly on Windows. Consider using the event loop and the readyRead() signal if your software will run on Windows.

How does it work?
Thanks,
Fred
Edit
Here is my current code:
Client.cpp
#include "client.h"

#include <pugixml.hpp>

#include <map>
#include <sstream>
#include <string>

#include "task.h" // Generate the API message, not relevant

Client::Client(const QString& server, const QString& port, QObject* parent):
    QObject(parent)
{
    connectToServer(server, port);
    connect(&socket_, &QTcpSocket::readyRead, this, &Client::getResult);
}

void Client::connectToServer(const QString& server, const QString& port)
{
    bool ok;
    int portNumber = port.toInt(&ok);

    if (ok) {
        if (socket_.state() == QTcpSocket::SocketState::ConnectedState)
            socket_.disconnectFromHost();
        socket_.connectToHost(server, portNumber);
    } else {
        throw tr("Cannot connect to server %1 on port %2. Make sure the provided information are correct.")
            .arg(server)
            .arg(port);
    }
}

void Client::throwOnError(const pugi::xml_document& doc)
{
    pugi::xpath_node_set errors = doc.select_nodes("/EXECUTION/TASK/RESULTSET/RESULT/MESSAGE");

    std::string error_message = "";
    for (pugi::xpath_node_set::const_iterator it = errors.begin(); it != errors.end(); ++it)
    {
        pugi::xml_node node = it->node();
        if (std::string(node.attribute("type").value()) == "Error" ||
            std::string(node.attribute("type").value()) == "Warning")
            error_message += node.child_value();
    }

    if (!error_message.empty())
        throw std::exception(error_message.c_str());
}

void Client::sendMessage(const QString &message)
{
    outMessage = message;
    result_.clear();
    socket_.write(message.toUtf8());
}

void Client::getResult()
{
    emit startReading();
    while (socket_.bytesAvailable() > 0) {
        result_.append(socket_.readAll());
        socket_.flush();
    }

    resultMessage = QString(result_);
    emit finishedReading();
}

void Client::login(const QString& user, const QString& password, const QString& project)
{
    std::map<QString, QString> whereFields {{"userName", user}, {"password", password}};
    QString request = prepareMessage("Login", "Security", std::map<QString, QString>(), whereFields); // Generates the XML message for the API
    sendMessage(request);

    // Wait for data to arrive - How ?

    std::stringstream xmlResult = getXmlData(result_); // Remove the header from the API response and convert the QByteArray to a std::stringstream

    pugi::xml_document doc;
    pugi::xml_parse_result result = doc.load(xmlResult);

    throwOnError(doc);

    pugi::xpath_node session = doc.select_node("/EXECUTION/TASK/RESULTSET/DATASETS/DATASET/secId");
    sessionId_ = QString::fromStdString(session.node().first_child().value());
    projectName_ = project;

    emit taskCompleted();
}

Client.h
#ifndef Client_H
#define Client_H

#include <QObject>
#include <QTcpSocket>
#include <QByteArray>

#include <map>
#include <set>

#include "pugixml.hpp"

class Client : public QObject
{
    Q_OBJECT
public:
    Client(QObject* parent = 0) : QObject(parent) {}
    Client(const QString& server, const QString& port, QObject* parent = 0);

    // Connection
    void connectToServer(const QString& server, const QString& port);
    void login(const QString& user, const QString& password, const QString& project);
    void logout();

    QString const getSessionId() { return sessionId_; }

    void throwOnError(const pugi::xml_document& doc);

    QString sessionId() const { return sessionId_; }

    QString outMessage;     // For testing
    QString resultMessage;  // For testing

signals:
    void ready();
    void startReading();
    void finishedReading();
    void taskCompleted();

private slots:
    void getResult();

private:
    void sendMessage(const QString& message);

    QTcpSocket socket_;

    QString sessionId_;
    QString projectName_;

    QByteArray result_;

};

#endif // Client_H


text:
Q: jQuery UI Dialog Titlebar too tall I am using a jQuery UI Dialog to pop-up some supplementary information on one of my pages.  For some reason, in Chrome 11 and Firefox 4, the titlebar is ridiculously tall.  For some reason it is ok in IE 9.  Here's a screenshot of what it looks like:

I have tried manually setting the height of the title bar, which only resizes the colored area of the title bar, but does not adjust the position of the title text or paragraph text.  Inspecting in Chrome developer tools reveals no odd margins or padding that could be causing this issue.  Anyone have an idea as to what could be causing this?  Below I have included the script and markup for this dialog.  As far as I can tell, there is no special CSS being applied to this dialog box (other than the standard jQueryUI CSS)  In case it matters, I am using ASP.Net/C# with jQuery 1.5.2 and jQueryUI 1.8.12.
ASP/HTML:

    <asp:Label ID="lblSsn" runat="server" CssClass="input-label" AssociatedControlID="tbSsn">Social Security Number (More Info)</asp:Label>
    <asp:TextBox ID="tbSsn" runat="server" CssClass="input" />

SSN disclosure is highly recommended if you have one. The University is required by federal law to report your SSN and other pertinent information
        to the Internal Revenue Service pursuant to the reporting requirements imposed by the Taxpayer Relief Act of 1997. The University will use the SSN you provide to
        verify the identity of each applicant, to link to the Payroll Office to verify amounts paid to students receiving teaching assistantships and research assistantships,
        and to link financial awards and admission data to registration histories and student records. This record-keeping system was established before January 1, 1975,
        pursuant to the authority of the Regents of the University of California under Article IX, Section 9 of the Constitution of the State of California. This notification
        is provided to you as required by the Federal Privacy Act of 1974.

Script:
$(function() {
    //hide ssn disclosure dialog box
    var $ssnDialog = $('#ssn-disclosure-text').hide().dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
    width: 500,
    title: 'SSN Disclosure'
    });

    //binding for ssn disclosure dialog
    $('#show-ssn-disclosure').click(function(e) {
        e.preventDefault();
        $ssnDialog.dialog('open');
    });
});

Any viable suggestions for fixes would be much appreciated.

A: You can always style it with:
.ui-dialog .ui-dialog-titlebar
{
    height: 40px; /* or whatever you want */
}

I would add that I tested FF4.01 and Chrome 11 and your code works for me, see working jsFiddle demo.

A: Just add the below attribute to the dialog's parent class, to solve this dialog header issue
.ui-dialog { clear: both; }

A: Add this :
position:absolute;
overflow:hidden

to class .ui-dialog :)

A: I don't know if it makes a difference, but you could try using a title attribute directly on your div instead of setting it in code:

   ...

It could be that you have a cascading style issue. I use Chrome's developer tools to track these kinds of issues down. You can isolate the title element generated by jQuery-ui and examine the classes that it has inherited.


text:
Q: Display Images from internet in a windows phone 7 app? I am making an application which gets urls of images through my web services.I want to diplay that images in the application backgound.How can i do it? Is it required to download all images before displaying? Please explain.

A: You can display images via an Image control, which you can position wherever you like. In order to display an image from a URL, you can do the following:
Uri uri = new Uri("http://dilbert.com/dyn/str_strip/000000000/00000000/0000000/000000/80000/5000/100/85108/85108.strip.print.gif", UriKind.Absolute)
image1.Source = new BitmapImage(uri);

As per this question:
Silverlight Windows Phone 7: Load Images From URL


text:
Q: In Scala, how to create a TypeTag from a type that is serializable? In Scala reflection, the TypeTag can usually be constructed from a Type using a TypeCreator:
object TypeUtils {

  import ScalaReflection.universe._

  def createTypeTag[T](
      tpe: Type,
      mirror: reflect.api.Mirror[reflect.runtime.universe.type]
  ): TypeTag[T] = {
    TypeTag.apply(
      mirror,
      NaiveTypeCreator(tpe)
    )
  }

  case class NaiveTypeCreator(tpe: Type) extends reflect.api.TypeCreator {

    def apply[U <: reflect.api.Universe with Singleton](
        m: reflect.api.Mirror[U]): U#Type = {
      //          assert(m eq mirror, s"TypeTag[$tpe] defined in $mirror cannot be migrated to $m.")
      tpe.asInstanceOf[U#Type]
    }
  }

Unfortunately, it turns out the output of createTypeTag is not serializable, unlike the typeTag created from compile-time inference:
import java.io.{ByteArrayOutputStream, ObjectOutputStream}

import org.apache.spark.sql.catalyst.ScalaReflection
import org.scalatest.FunSpec

class TypeTagFromType extends FunSpec {

  import ScalaReflection.universe._

  it("create TypeTag from reflection") {

    val ttg = typeTag[String]

    val ttg2 = TypeUtils.createTypeTag(ttg.tpe, ttg.mirror)

    Seq(
      ttg -> "from static inference",
      ttg2 -> "from dynamic type"
    ).foreach {
      case (tt, k) =>
        println(k)

        val bos = new ByteArrayOutputStream()
        try {
          val out = new ObjectOutputStream(bos)
          out.writeObject(tt)
          out.flush()
          val array = bos.toByteArray
        } finally {
          bos.close()
        }
    }
  }
}

This gives the output:
from static inference
from dynamic type

scala.reflect.runtime.JavaMirrors$JavaMirror$$anon$2
java.io.NotSerializableException: scala.reflect.runtime.JavaMirrors$JavaMirror$$anon$2
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)

Indicating that the second TypeTag is not serializable, while the first one is.
So my question is: how to make the second TypeTag to be serializable like the first one?
I'm using scala 2.12.10 at the moment.

A: Based on How to create a TypeTag manually?

if you need a serializable TypeTag and performance isn't your main
  concern

then consider
import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox

def createTypeTag(tp: Type): TypeTag[_] = {
  val toolbox = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
  val ttree = toolbox.parse(s"scala.reflect.runtime.universe.typeTag[$tp]")
  toolbox.eval(ttree).asInstanceOf[TypeTag[_]]
}

val ttg = typeTag[List[String]]
val ttg2 = createTypeTag(ttg.tpe)
...


text:
Q: Maths book recommendation for two advanced readers I want to get a book for my maths teachers. They are both very able: one has a PHD in maths from Cambridge University in the UK, and the other was at the IMO. Because of this, I am unsure of which books are the right difficulty, as the books I do are much easier (e.g. Calculus by Spivak)
One has a particular interest in Analysis, so any recommendation on that would be appreciated. The other specialised in Combinatorics at university, so something along those lines would probably be best. However, any recommendations of books at the right difficulty would be great.
Thank you!!
Edit: having read the comments, I will probably ask them if they have the book before buying it.


text:
Q: How can I check to see if a file descriptor was closed? In a POSIX environment when using system calls to manipulate text files (open(), close(), read(), write()), is there a way to to check to see if I actually closed a file descriptor when using close(file_descriptor)?
Example:
int main(int argc, char **argv)
{
    int input_file; // file descriptor for input file
    int output_file; // file descriptor for output file
    input_file = open(argv[1], O_RDONLY));
    ouput_file = open(argv[2], ...file properties & permissions and crap.....);

    // blah blah blah...

    close(input_file);
    close(output_file);

    // what can I code here to check if the file descriptor was actually closed?
}

A: The easiest way is probably to just check the return value of your first close.
if (close(input_file)) {
    perror("close");
} else {
    // all good
}

This is the only thread-safe way.  In a multi-threaded program, another thread could get a new file descriptor that recycles the fd number of the one that was just closed.

In single-threaded code only, where nothing can recycle an fd between close and  check:
If you wish to check whether a file descriptor is valid afterwards then you can use any function that consumes a file descriptor and check it's error code. The most non-intervening and light weight is probably fcntl/F_GETFL
if (fcntl(fd, F_GETFL) < 0 && errno == EBADF) {
    // file descriptor is invalid or closed
}

You could also just call close a second time and it can also fail with EBADF.
if (close(fd) && errno == EBADF) {
    // file descriptor is invalid or closed
} else {
    // we successfully closed fd *now* (e.g. first close failed with EINTR)
    // or there was a different error
}

close doesn't modify errno on success, but we only read errno when close returns non-zero, meaning it has been set.

A: You can check the return value of close() and the error number accordingly.
from http://pubs.opengroup.org/onlinepubs/009695399/functions/close.html

Upon successful completion, 0 shall be returned; otherwise, -1 shall
      be returned and errno set to indicate the error.
[...]
The close() function shall fail if:
[EBADF]
The fildes argument is not a valid file descriptor.

A: The only save method to check whether a file descriptor is invalid is to explicitly set it to (for example) -1 on definition and every time it successfully has been closed.
The could be done using macro:
#define FD_INVALID (-1)

#define FD_CLOSE_AND_INVALIDATE(fd) \
do { \
  if (-1 == close(fd)) \
  { \
    perror("close failed"); \
  } \
  else \
  { \
    (fd) = FD_INVALID; \
  } \
} while (0)

int main(int argc, char ** argv)
{
  int input_file = FD_INVALID; /* Properly initialise file descriptor for input file */
  int output_file = FD_INVALID; /*  Properly initialise file descriptor for output file */

  input_file = open(argv[1], O_RDONLY));
  ouput_file = open(argv[2], ...);

  /* Do something. */

  FD_CLOSE_AND_INVALIDATE(input_file);
  FD_CLOSE_AND_INVALIDATE(output_file);

  /* To check if the file descriptor was actually closed just test for FD_INVALID. */
}


text:
Q: How to extract data from archive with signature 789C? Google say what is this zip archive, but I cannot its extract by ICSharpCode.SharpZipLib and Zlib.net libraries.

A: That is a zlib (RFC 1950) header.  You can use the zlib library to decompress it.

A: I found offzip.exe at http://aluigi.altervista.org/mytoolz.htm to be super helpful to expand RFC 1950s.


text:
Q: Will User.Identity.Name generates the same data as Membership.GetUser().UserName As per my question. Will this generates the same username for anonymous and logged in user?
EDIT: sorry for the confusing question. What I'm trying to find out is that if User.Identity.Name is a reliable way to get the username of currently logged in user. Trying to avoid Membership.GetUser().Username as GetUser() might return null for anonymous user.

A: I'm not sure Generate is the best word.  I'm going to assume you meant Return the same data.
The answer is not always.
User.Identity is an IIdentity instance (typically a GenericIdentity or a WindowsIdentity).
Membership.Getuser() will return a instance of MembershipUser.
Both of these mechanisms can be customized and technically can return completely different information.
Updated for Edit
First, this question is starting to sound like an XY Problem.  I highly suggest you let us know what you are actually trying to solve.
Although Membership.GetUser() should return null for anonymous users, User.Identity.Name normally returns string.Empty for anonymous users which also isn't technically correct.
Typically the recommended way is to do something like:
(taken directly from the in the ASP.Net MVC 3 Template starter)
@if(Request.IsAuthenticated)
{
  <text>Welcome <b>@Context.User.Identity.Name</b>!
  [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else
{
  @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}


text:
Q: What are all the facilities provided by Facebook to an application? I'm not going to integrate my application into Facebook platform
I just registered my app to get the api key
In that case what are all the facilities i can avail from facebook apart from using facebook for  authentication
1. Can i get users friends list
2. will my application be allowed to send notification or messages or emails to users friends

Thanks

A: The obvious place to start to find out what the Facebook API offers would be the Facebook API documentation.
You'll be interested in the Friends.get and Notifications.send methods.
In other words, the answers to your questions are Yes and Yes.


text:
Q: How to programmatically change title bar colour to hex value? Is it possible to change the colour of the title text within the action bar to a colour of a hex value? I'm only aware of the following and have no idea if this can be achieved:
setTitleColor(Color.Green);

A: Android < 4.0
You can simply do setTitleColor(Color.parseColor("#000000"));.
Android >= 4.0
Check this answer https://stackoverflow.com/a/10592561.

A: You can add hex color values on your color.xml. Then on your activity you try to add this line of code:
setTitleColor(getResources().getColor(R.color.hex_color_id));


text:
Q: Curses window.getstr() I'm trying to learn curses for Python on Windows XP. I can get the window.getkey command to work correctly but the command window.getstr not only fails but the program exits. Here are sample code lines:
x = window.getkey()  # this works
y = window.getstr()  # this fails

Obviously, to get the first line to work I have correctly imported curses and have done the stdscr = curses.initscr() command. My window is defined and working. I've tried placing the window coordinates within the getstr parens and I've used window.move. Neither works.
Any ideas why getstr doesn't work?
Here's more info following the first suggestion:
First, the suggestion to run the program in a command prompt window instead of from the desktop is a good one because the window was indeed disappearing.
Here's the entirety of the program:
# program = testcurses
import curses
stdscr = curses.initscr()

window = stdscr.subwin(23,79,0,0)
window.box()
window.refresh()
window.addstr(2,10, "This is my line of text")
window.addstr(4,20,"What happened? ")
window.refresh()

mykey = window.getkey(5,20)
mystr = window.getstr (6,20)
#window.addstr (7,1, "Key data should be here: ")
#window.addstr (7,33, mykey)
window.addstr (8,1, "Str data should be here: ")
window.addstr (8,33,mystr)
window.refresh()

I remarked the lines pertaining to the display of the key data since that works OK.
Here's the relevant part of the Traceback message:
window.addstr (8,33,mystr)
TypeError: must be str, not bytes.
Tom

A: The traceback tells you, that the variable mystr is a bytes object not a string. This means you have to decode it first, before you can use it as a string, which is needed by addstr().
Here's the change you need to make:
mystr = window.getstr(6,20).decode(encoding="utf-8")

This is a Python 3 problem ONLY! I tested this with Python 2.7 as well, which works without this change. The problem arises due to different bytes/string handling between Python 2 and 3. I assume you followed through a py2 tutorial while using py3 yourself.


text:
Q: sequence of primes in arithmetic progression The question is:
Suppose $p_1<p_2<...<p_{15}$ is a sequence of prime numbers in arithmetic progression, with common difference $d$. Prove that $d$ is divisible by $2,3,5,7,11$ and $13$.
Let $p_n = a+(n-1)d$, by the definition of an arithmetic sequence. It is easy to see that $a$ is odd, and I can prove that $d$ is even easily enough.
I could then show $d$ is divisble by 3 by using the technique of letting $d=3x+c$, and $a=3y+d$, and by going through each possible value of c and d, d not equal to zero, I showed that the only solution where a and d were still prime was when $c=0$ or $3$.
While I could do the same thing for showing d is divisible by 5,7,11 and 13, this is a very laborious process that takes quite a long time. Are there any faster ways of proving this? I feel there is a way to do it using modular arithmetic, but I'm not very competent with regards to modular arithmetic, so I can't think of anything.

A: Hint: if $q$ is a prime and $d$ is not divisible by $q$, then $p_i  \equiv p_j \mod q$   only if $i-j$ is divisible by $q$.  There are only $q-1$ nonzero residue classes mod $q$...

A: First we show that $d$ divides all of $2, 3, 5, 7$. Take some $q$ in the set $\{2, 3, 5, 7\}$. Since $2q < 15$ we know that there is a sub-sequence of terms of length $2q$ in our arithmetic progression. Now, if $q$ does not divide $d$, because $q$ is a prime, $d$ and $q$ must be coprime. So there must be two numbers in our progression of $2q$ terms that divide $q$. Which contradicts the fact that all are distinct primes. Call this result (1).
Now, for the cases of $q$ in the set $\{11, 13\}$. If $q$ divides $d$, then we're done. So suppose it doesn't, towards a contradiction. Well, then, we again have the case that $q$ and $d$ must be coprime. Because $q < 15$, there is always a sub-sequence of $q$ terms in our sequence. And because $d$ and $q$ are coprime, one of these terms must divide $q$. But being prime, it must actually equal $q$. Now, suppose this $q$ appears as the first term in our main sequence i.e. $p_1 = q$. Then we know there is a sub-sequence of $14$ terms in sequence to the right, and so because of coprime $d$ and $q$ one of them must also equal $q$, which is a contraction. So there is always a term to the left of $q$, call it $p_i$. Now, $p_i$ is positive, and we have that $p_i + d = q$ by our definition of arithmetic progression. And $d$ is positive, by our assumption. So $d < q$. But we know that $q \leq 13$. So $d < 13$. But we know from our earlier result (1) that $d$ divides $2, 3, 5, 7$. So $2 \times 3 \times 5 \times 7 \leq d$. Which implies $2 \times 3 \times 5 \times 7 < 13$. This is clearly false.

Note: we only needed 14 terms in our arithmetic progression for this proof to work. This result can be generalised: given any progression of $p + 1$ or more primes, for some prime $p$, then the common difference $d$ of the progression divides all primes less than or equal to $p$. For the first few primes $2, 3, 5, 7$ we need to tweak the above proof a bit. In the the general case, we rely on a lower bound for the primorial (product of all primes up to a given prime). The bound is $2^{\frac{n(n+1)}{2}}$ for some prime $p \geq 2^{n}$. This bound can be derived from Bertrand's postulate.

A: The $p_i$ are given by $p_1 = a + nd$ for $a = p_1 - d$ and $n = 1, \dots, 15$. Suppose $p \leq 13$ is prime and $p\nmid d$. Then there exists some $d'$ with $d'd\equiv 1\pmod{p}$. There exists some $0 < m < p$ with $m\equiv -ad' \pmod{p}$. Then $p_m = a + md \equiv 0\pmod{p}$. But $p_m$ is prime, so $p_m = p$.
Now note that the only three-term arithmetic progressions among primes less than $15$ are $3, 5, 7$ and $3, 7, 11$. It follows that if $p_m = p$, then $p + m < 15$. But then $p_m$ and $p_{m+p} = p_m + pd$ are both divisible by $p$, contradicting the fact that the $p_i$ are prime.