text:
Q: Late 1950s short story in an anthology titled something like "100 Best Science Fiction Stories" Circa 1958, I read a short story in a sci-fi anthology in which the protagonist is (possibly) the last human on earth.  Stumbling about the ruins of a city he spots something alive – a chicken.  He's about to kill the chicken when he is suddenly vaporized.  The scene shifts to the inside of a spaceship hovering above, a spaceship whose captain is avian, and a bird-captain certain that he/she/it has just saved the last important species on Earth.
Can anyone identify the story and author? Heinlein, maybe?  Can't recall, I was twelve at the time.

A: Circa 1958, I read a short story in a Sci-Fi anthology
Perhaps "Quietus", a short story by Ross Rocklynne, first published in Astounding Science-Fiction, September 1940, which is available at the Internet Archive. If you read it in an anthology around 1958, it must have been one edition or another of Famous Science-Fiction Stories: Adventures in Time and Space, edited by Raymond J. Healy and J. Francis McComas.
in which the protagonist is (possibly) the last human on earth.
He seems to be the last human male, and is pursuing the last human female when the avian aliens arrive:

For five days Tommy followed the lead of the girl with a grim determination. He knew now that it was a woman; perhaps—indeed, very probably—the only one left alive. He had only the vaguest of ideas why he wanted her—he thought it was for human companionship, that alone. At any rate, he felt that this terrible hunger in him—he could give it no other word—would be allayed when he caught up with her.
She was fleeing him, and staying just near enough to him to make him continue the chase, he knew that with a fierce exaltation. And somehow her actions seemed right and proper. Twice he had seen her, once on the crest of a ridge, once as she swam a river. Both times she had easily outdistanced him. But by cross-hatching, he picked up her trail again—a bent twig or a weed, a footprint, the skin of a dead rabbit.

Stumbling about the ruins of a city he spots something alive – a chicken. He's about to kill the chicken when he is suddenly vaporized.
This is the part you must be misremembering if "Quietus" is your story. The story is set in the woods, not in a city. The bird was not a chicken; it was Tommy's talking crow, Blacky:

"Tommy" was what he called himself. A long time ago, he remembered, there used to be a great many people in the world—perhaps a hundred—many of whom, and particularly two people whom he had called Mom and Pop, had called him by that name. They were gone now, and the others with them. Exactly where they went, Tommy did not know. But the world had rocked one night—it was the night Tommy ran away from home, with Blacky riding on his shoulder—and when Tommy came out of the cave where he had been sleeping, all was in flames, and the city on the horizon had fallen so that it was nothing but a huge pile of dust—but in the end it had not mattered to Tommy. Of course, he was lonesome, terrified, at first, but he got over that. He continued to live, eating, drinking, sleeping, walking endlessly, and Blacky, his talking crow, was good company. Blacky was smart. He could speak every word that Tommy knew, and a good many others that he didn't. Tommy was not Blacky's first owner.

Tommy is about to kill Blacky in a rage after Blacky scares the girl away, but an avian alien intervenes to save the crow:

"It's all your fault, Blacky!" Tommy raged. He picked up a rock the size of his fist. He started to throw it, but did not. A tiny, sharp sound bit through the air. Tommy pitched forward. He did not make the slightest twitching motion to show that he had bridged the gap between life and death. He did not know that Blacky swooped down and landed on his chest; and then flung himself upward, crying, "Oh, Tommy, I could spank you!" He did not see the girl come into the clearing and stoop over him; and did not see the tears that began to gush from her eyes, or hear the sobs that racked her body. But Tark saw.
Tark wrested the weapon from Vascar with a trill of rage.
"Why did you do that?" he cried. He threw the weapon from him as far as it would go. "You've done a terrible thing, Vascar!"
Vascar looked at him in amazement. "It was only a beast, Tark," she protested. "It was trying to kill its master! Surely, you saw it. It was trying to kill the intelligent bird-creature, the last of its kind on the planet."

The scene shifts to the inside of a spaceship hovering above, a spaceship whose captain is avian, and a bird-captain certain that he/she/it has just saved the last important species on Earth.
The two aliens are of different opinions about what happened on Earth. The female believes she was right to kill the "beast" that was threatening to kill the "intelligent bird"; the male, who is driving the spaceship, has doubts.

The spaceship of the creatures from Alcon left the dead planet Earth. It darted out into space. Tark sat at the controls. The ship went faster and faster. And still faster. Fled at ever-increasing speed beyond the Solar System and into the wastes of interstellar space. And still farther, until the star that gave heat to Earth was not even visible.
Yet even this terrible velocity was not enough for Tark. Vascar looked at him strangely.
"We're not in that much of a hurry to get home, are we, Tark?"
"No," Tark said in a low, terrible voice; but still he urged the ship to greater and greater speed, though he knew it was useless. He could run away from the thing that had happened on the planet Earth; but he could never, never outrun his mind, though he passionately wished he could.

The spacefaring aliens were described early in the story:

Tark nodded. He was truly a bird, for in the evolutionary race on his planet, distant uncounted light-years, his stock had won out over the others. His wings were short, true, and in another thousand years would be too short for flight, save in a dense atmosphere; but his head was large, and his eyes, red, small, set close together, showed intelligence and a kind benevolence. He and Vascar had left Alcon, their planet, a good many years ago, but they were on their way back now. Their outward-bound trip had taken them many light-years north of the Solar System; but on the way back, they had decided to make it one of the stop-off points on their zigzag course. Probably their greatest interest in all this long cruise was in the discovery of planets—they were indeed few. And that pleasure might even be secondary to the discovery of life. To find a planet that had almost entirely died was, conversely, distressing. Their interest in the planet Earth was, because of this, a wistful one.


text:
Q: How to Custom group notify for blocks of functions
Asynchronous block be called in function, add these multiple functions into a group,process all results of blocks when all block execute completely.Is there a common and smart method to implement?
  like dispatch_group_notify ,completionBlock

A: dispatch_group_t _blockTaskGroup;
.....

if (!_blockTaskGroup) {
    _blockTaskGroup = dispatch_group_create();
}

dispatch_group_notify(_blockTaskGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSLog(@"finally!");
});

....

dispatch_group_enter(_blockTaskGroup);
[XXXXX computeInBackground:xx completion:^{
    NSLog(@"1 done");
    dispatch_group_leave(group);
}];
//
dispatch_group_enter(_blockTaskGroup);
[XXXXX computeInBackground:xx completion:^{
    NSLog(@"2 done");
    dispatch_group_leave(_blockTaskGroup);
}];
//
dispatch_group_enter(_blockTaskGroup);
[XXXXX computeInBackground:xx completion:^{
    NSLog(@"3 done");
    dispatch_group_leave(_blockTaskGroup);
}];

redpajama_set_name: RedPajamaStackExchange


text:
Q: Boto EMR creation gives "Log Uri is not in the required format" error The following code gives the error message
EmrResponseError: EmrResponseError: 400 Bad Request <ErrorResponse xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-03-31">   <Error>
    <Type>Sender</Type>
    ValidationError
    <Message>Log Uri is not in the required format</Message>   </Error>   <RequestId>1c3d0221-4420-11e4-a09e-5113f30a0036</RequestId> </ErrorResponse>

no matter sort of S3 URI I try. I've tried a trailing slash, s3n:// s3:// and all other combinations with no luck.
Here's the code:
import boto.emr

conn = boto.emr.connect_to_region('us-east-1')

job_parameters = {"log_uri":"s3n://shadoop/logs/new-log",
        "ec2_keyname":"XXXXXX",
        "availability_zone":"us-east-1e",
        "master_instance_type":"m1-medium",
        "slave_instance_type":"m1-medium",
        "num_instances":"2",
        "keep_alive":"True",
        "enable_debugging":"True",
        "hadoop_version":"2.4.0",
        "ami_version":"3.1.0",
        "visible_to_all_users":"True"
    }
jobid = conn.run_jobflow("test_cluster",job_parameters)

A: In order to get this to run I had to pass the input variables individually as opposed to a dictionary. The following code works:
jobid = conn.run_jobflow(cluster_name,log_uri="s3n://shadoop/logs/new-log",\
            ec2_keyname="XXXXX",\
            availability_zone="us-east-1e",\
            instance_groups=instance_groups,\
            num_instances=str(num_instances),\
            keep_alive="True",\
            enable_debugging="True",\
            hadoop_version="2.4.0",\
            ami_version="3.1.0",\
            visible_to_all_users="True",\
            steps=[hive_step],\
            bootstrap_actions=[bootstrap_impala])


text:
Q: How do I filter a (json) array in Powershell? I have this array:
[
{id: 1, name: 'foo'},
{id: 2, name: 'bar'}
]

I'm trying to filter it, but get in return all records. What am I doing wrong?:
> cat c:\temp\test.json | ConvertFrom-Json | ? { $_.name -eq 'bar'}

id name
-- ----
 1 foo
 2 bar


text:
Q: MySQL - Grouping using MIN not working as expected I have the following union query where i'm setting a dummy row number:
SELECT @row_num:=2 as row_num, id, name, admin1, admin3, admin4
  FROM locations
 WHERE feature_class IN ('P', 'A')
   AND name LIKE 'cornwall%'
UNION ALL
SELECT @row_num:=1 as row_num, id, name, admin1, admin3, admin4
 FROM locations
WHERE feature_class = 'L' AND feature_code = 'RGN'
  AND name LIKE 'cornwall%'

This returns the following results:
row_num   |   id       |     name    |   admin1   |   admin3   |  admin4
-------------------------------------------------------------------------
   2      |   2652355  |   Cornwall  |   ENG      |            |
   1      |   11609029 |   Cornwall  |   ENG      |            |

Now when I add this query as a subquery and use MIN to select row with the lowest row_num I get incorrect results:
 SELECT MIN(t0.row_num),
   t0.id,
   t0.name,
   t4.name AS town_admin4,
   t3.name AS county_admin3,
   t1.name AS admin1
  FROM (
           SELECT @row_num:=2 as row_num, id, name, admin1, admin3, admin4
            FROM locations
           WHERE feature_class IN ('P', 'A')
             AND name LIKE 'cornwall%'
           UNION ALL
           SELECT @row_num:=1 as row_num , id, name, admin1, admin3, admin4
            FROM locations
           WHERE feature_class = 'L' AND feature_code = 'RGN'
             AND name LIKE 'cornwall%'
      ) t0
  LEFT JOIN locations t1 ON t1.admin1 = t0.admin1 AND t1.feature_code = 'ADM1'
  LEFT JOIN locations t3 ON t3.admin3 = t0.admin3 AND t3.feature_code = 'ADM3'
  LEFT JOIN locations t4 ON t4.admin4 = t0.admin4 AND t4.feature_code = 'ADM4'
  GROUP BY t0.name,
           t4.name,
           t3.name,
           t1.name
  ORDER BY t0.name

I get the following results:
MIN(t0.row_num)   |   id       |     name    |   town_admin4   |   county_admin3   |  admin1
--------------------------------------------------------------------------------------------
       1          |   2652355  |   Cornwall  |                 |                   |  England

As you can see the above is incorrect. Row 1 should be record with id 11609029
Why is it behaving like this - why is the MIN operator not working as expected?


text:
Q: Paypal Return and Review My client has recently moved server and Paypal is not returning the customers anymore to the site for review in the middle of the order and return ( to confirm a successful tx) like it used to. What are the factors which control this? What URL should we give to paypal so that the customer gets a this return at the end saying there was a successful transaction. A bit confused because if we give for instance the home page then the customer would not get the successful transaction message but there was no CMS page set up to achieve this either, so it must have been generated by paypal.
We are using Paypal standard.
Also there is the use SSL setting in the Paypal standard settings. Is this supposed to be yes or not. Client has an SSL cert.

A: You should set your site url in website preference in paypal account and ipn url of site in ipn url in your paypal profile.
And keep auto return on in paypal profile.


text:
Q: How to make Http request load on time before table view cell I may be missing a design or simple detail here as I'm new to iOS, but can't figure this one out:
I've got a func called getWeatherData(), that based on the location received from another view controller, gets weather conditions from a http request and assigns it to HikeModel. This function is called in method of ViewDidLoad().
After func gets the weather conditions, it passes this to a child view controller. Which Child VC is a Table View Controller.
Problem is my TableViewCell loads faster than the http request takes to be done, in the parent view controller. And when the cell labels and images try to retrieve information that should have values assigned, theirs is nothing, since the http request hasn't finished on time.
I also attempted using DispatchQueue.main.async but no difference was shown.
I'm doing a native http request with Swift4.
For more detail on the structure of my project, I'm doing based on this work: https://medium.com/@phillfarrugia/re-creating-the-siri-shortcuts-drawer-interaction-9b2bc94e0b05
In ViewDidLoad
let group = DispatchGroup()

group.enter()

DispatchQueue.main.sync {
    self.getWeatherData(hikeLocation: self.startHikeLocationString)
    group.leave()
}

Method sending information fillDrawer, with what should contain weather vars assigned to HikeModel.
private func configureDrawerViewController() {
    let compressedHeight = ExpansionState.height(forState: .compressed, inContainer: view.bounds)
    let compressedTopConstraint = view.bounds.height - compressedHeight
    containerViewTopConstraint.constant = compressedTopConstraint
    previousContainerViewTopConstraint = containerViewTopConstraint.constant

    // NB: Handle this in a more clean and production ready fashion.
    if let drawerViewController = children.first as? DrawerViewController {
        //send distnace too
        drawerViewController.delegate = self
        drawerViewController.fillDrawer(hike: self.hikeModel, userLocation: self.userLocation)
    }

TableView CellsForRowAt
cell.temperature.text = hikeModel.temperature
cell.weather.text = hikeModel.weather
cell.weatherIcon.text = hikeModel.weatherIcon
cell.humidity.text = hikeModel.humidity
cell.barometer.text = hikeModel.barometer
cell.sunrise.text = hikeModel.sunrise
cell.sunset.text = hikeModel.sunset

I expect the tableViewCell in child controller to load after the http request is done in parent view controller.

A: Your code is incomplete to identify issue but you should have to do like:
1) load data from webservice then,
2) reload tableView
In your ViewDidLoad
let group = DispatchGroup()
        group.enter()

        DispatchQueue.main.sync {
            self.getWeatherData(hikeLocation: self.startHikeLocationString)
           group.leave()
        }

add line after complete process of data modeling and it should be in mainQueue
yourtable.reloadData()


text:
Q: How to change the footer content in WordPress Sparkling theme I need to change the footer content (copyright). I tried to change the extras.php file, but it does not work for me. Can anyone suggest how to do this?

A: Appearance >> Customize >> Sparkling Options >> Footer. This form supports HTML for URLs and other formatting. You can also change Footer background, text, link color via Theme Options.

A: Editing extras.php is the most convenient way. Comment out or remove part of code which prints out default copyright text. Which is:

Theme by Colorlib Powered by WordPress

function sparkling_footer_info() {
        global $sparkling_footer_info;
/**
        printf( esc_html__( 'Theme by %1$s Powered by %2$s', 'sparkling' ) , 'Colorlib', '> Customize >> Sparkling Options >> Footer


text:
Q: Integration of nonnegative function Can someone explain the results of
Plot[
  ((E^(-.6 *x))^(-1 + 38) (1 - E^(-.6*x))^(-1 + 160) *.6)/Beta[-1 + 38., 160.],
  {x, 1/.6, 4.5}]

and
1/Beta[-1 + 38., 160.]
  Integrate[0.6*(E^(-0.6*x))^(-1 + 38)*(1 - E^(-0.6*x))^(-1 + 160), {x, 2, 4.}]

?

A: This is a problem of precision with large numbers.
nint = 1/Beta[-1 + 38., 160.]*
          NIntegrate[(E^(-.6 *x))^(-1 + 38) (1 - E^(-.6*x))^(-1 +
                      160) *.6, {x, 2, 4}]

(*    0.999858    *)

int = 1/Beta[-1 + 38, 160]* Integrate[
            Rationalize[(E^(-.6 *x))^(-1 + 38) (1 - E^(-.6*x))^(-1 + 160) *.6,
            0], {x, 2, 4}]

(*  A very large output ...   *)

N[int]

(*    -1.35051*10^66    *)

Block[{$MaxExtraPrecision = 500}, N[int, 10]]

(*    0.9998583622    *)


text:
Q: How can I set scale_fill_gradient for both columns in dodge_position? How can I add scale_fill_gradient for both columns in dodge_position?
Code:
 ggplot(df, aes(x=msc, y=as.integer(value), fill=variable)) +
        geom_col(position='dodge')+
        theme(legend.position = "bottom")+
        labs(x = "Miesiąc",y="Ilość zapytań")+
        theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1,size = 11),
              axis.title = element_text(size = 12))+
        geom_text(aes(label=value),position =position_dodge(width = 1),vjust = -0.2) +
        scale_fill_manual("legend", values = c("unikalne_zapytania" = '#009999', "zapytania" = '#4d0099')) +
        ggtitle("Wykres zapytań za ostatni rok") +
        guides(fill=guide_legend(title='Rodzaj'))

Final example:

A: Without a minimal reproducible example it's difficult to help you, but I think the thing you ask for is impossible. You are using the categorical variable variable to group the bars, but now you want to use a continuous variable to color the same bars. Anyway, here is a suggestion how to achieve something similar as your request:
library(ggplot2)
mtcars %>%
  mutate(group = sample(c("A", "B"), nrow(mtcars),  replace=TRUE)) %>%
  group_by(group, cyl) %>%
  summarise(mean_mpg = mean(mpg),
            mean_disp = mean(disp)) %>%
ggplot(aes(factor(cyl), mean_mpg)) +
  geom_bar(aes(color=group, fill = mean_disp), position = "dodge", stat="identity")

Resulting in this figure:


text:
Q: Código sem efeitos coloridos quando nome do arquivo inicia com upper-case Estou utilizando o Intellij IDEIA para desenvolver usando Flutter mas quando eu nomeio uma nova classe com seu nome iniciando em letra maiúscula o código digitado permanece com a mesma cor sem destacar variáveis, keywords e etc.
Esta imagem ilustra o código em uma classe iniciando com low-case chamada: odoo_services.dart. Nota-se que o código digitado possui os efeitos coloridos.

Agora, a imagem ilustra o código da classe chamada: OdooServices.dart e o código sem os efeitos coloridos.

Obs.: O código compila e funciona corretamente, o único problema é os efeitos de cor no código.

A: A linguagem dart diferencia as classes(cores) pela primeira letra da palavra, no caso no meu visual studio code ela fica verde quando eu coloco a primeira letra maiúscula.
É mais ou menos uma obrigação para manter o código de acordo com as boas praticas kkk

A: Flutter é escrito em Dart, e pelas boas práticas do Dart o nome de arquivos deve começar sempre com letra minúscula e em "snake_case", segue referência:
https://www.dartlang.org/guides/language/effective-dart/style#do-name-libraries-and-source-files-using-lowercase_with_underscores
O "erro" que você tem na sua IDE deve ser alguma forma do editor de texto te alertar que fugiu do padrão da linguagem.


text:
Q: Module compiled with Swift 5.0 cannot be imported by the Swift 5.1 compiler: Getting this error while import AudioKit in my new project in XCODE 11 latest version.
How to solve this issue?

A: Unless you need Swift 5.1 or something specific to Xcode 11, I'd recommend staying on Xcode 10.x and moving over device support files so you can debug on iOS 13 devices.
https://github.com/filsv/iPhoneOSDeviceSupport
Or, if you've already downloaded Xcode 11.x, just move everything you want from
/Applications/{XCODE11}.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
to
/Applications/{XCODE10}.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
This is probably better advice for someone like me stuck using a closed source module built in Swift 5.0, but you're the first SO result on Google for this error message.


text:
Q: How to create separate source tree for unit tests Its a very basic question though I can not figure out the way.
How to create a structure where

have classes in the same package and have them in different trees,

*

*src/main/Example.java

*src/test/TestExample.java

  Is it possible to create this structure using Idea 8.0?

I was trying to create this folder structure. It turns out that it becomes different packages.
As I intend to test functions that are visible only package level.

A: Yes this is possible.  The mistake you probably made is you marked your src folder as a source root in your project settings.  Instead, you want to mark the main folder as the source folder and the test folder as your test folder.  Here's a screenshot showing where to change this:

Make sure you click on the right colors in the right folders.
But why are you using Idea 8?  You know Idea 12 is out and the community edition is free?


text:
Q: Above the fold plugin error "The Proxy Cache directory contains n cache entries." I've just starting using this plugin with a site that I did not code or configure. I'm getting this error:
"The Proxy Cache directory contains n cache entries. This may indicate that
auto-capture captures a script with a changing url that causes a new cache
entry to be created on each request.

The Proxy configuration page shows a solution to capture scripts with a
changing url using a JSON config object."

The referenced Proxy configuration page solution offers this:
JSON Proxy Config Object

JSON config objects enable advanced file based proxy configuration. JSON
objects can be used together with simple file entry and must be placed on
one line (no spaces are allowed).

JSON config objects must contain a target url (the url that will be
downloaded by the proxy). Regular expression enables to match a source URL
in the HTML, e.g. an URL with a cache busting date string (?time) or an url
on a different host. Valid parameters are url, regex, regex-flags, cdn and
expire (expire time in seconds).

Example:
{"regex": "^https://app\\.analytics\\.com/file\\.js\\?\\d+$", "regex-
flags":"i", "url": "https://app.analytics.com/file.js", "expire": "2592000"}

I've found an older link with someone having the same problem as me, where the developer replied like so:
"If you use auto capture to proxy any script and if the website contains a
script with a changing url, e.g. a timestamp query string, a new cache entry
will be created for each request causing the cache directory to fill. The
configuration page shows a solution to capture such scripts by using a JSON
config object."

My issue is that unfortunately I have no idea whatsoever what any of that means. I don't even know where to start with fixing it.
Can anyone tell me how to find out which script is causing this issue? Once I know what that is, any suggestions on how I work out what my specific regex should be for the JSON Proxy Config Object?


text:
Q: State true or false: vectoriel space Hello can someone tell me, please, if I anwered the questions correctly.
1- false: The set of rational numbers with the usual addition and multiplication operations by a scalar is a vector space on the real ones.
2-True: All polynomials of degree greater than or equal to 3 with the usual operations are a vector space.

A: 1)
W = {(x, x+1)} is not a subspace of R^2. One reason is that (2,3)+(2,3) = (4,6) is not in W, so it is not closed under addition. Another reason could be that (0,0) is not in W.
2)
W = {p(x) : p(x) in P_n and p(3) = 0}.
These are all single variable polynomials of degree at most n (over some field) that have a factor of (x-3). Note that if you add or scale such polynomials it will still have a factor of (x-3). Note also that the 0 polynomial satisfies 0(3) = 0. So yes, it is a subspace of P_n.
3)
W = {p(x) : p(x) in P_4 and p(2) = 3}
The constant polynomial 3 is in W and 3(2) = 3 by virtue of it being constant.
On the other hand 3+3 = 6 does not satisfy 6(2) = 3, so W is not closed under addition.
Thus W is not a vector subspace of P_4. An easier argument is simply to note that the origin of P_4, i.e. the 0 polynomial, is not an element of W.
Do the rest yourself. A subspace of a vector space V is a subset that is closed under addition, scalar multiplication, and contains the original origin.


text:
Q: Possibly incorrect spider/exporter example code in scrapy docs Can someone check whether the code below is correct?
The code is found at
http://readthedocs.org/docs/scrapy/en/0.14/topics/exporters.html
I believe it is incorrect because:

*

*The class keeps track of multiple simultaneously open files for multiple spiders, however:

*The exporter (which depends on the file) is overwritten each time a new spider is opened.

Thanks for any assistance.
class XmlExportPipeline(object):

    def __init__(self):
        dispatcher.connect(self.spider_opened, signals.spider_opened)
        dispatcher.connect(self.spider_closed, signals.spider_closed)
        self.files = {}

    def spider_opened(self, spider):
        file = open('%s_products.xml' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporter = XmlItemExporter(file)
        self.exporter.start_exporting()

    def spider_closed(self, spider):
        self.exporter.finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

A: I think this question should be asked in scrapy-users group.
AFAIK, since v0.14 Scrapy doesn't suppport multiple spiders in one process (related discussion), so this code will work fine. And obvious fix for multiple spiders is to make exporters dict with spider keys:
class XmlExportPipeline(object):

    def __init__(self):
        dispatcher.connect(self.spider_opened, signals.spider_opened)
        dispatcher.connect(self.spider_closed, signals.spider_closed)
        self.files = {}
        self.exporters = {}

    def spider_opened(self, spider):
        file = open('%s_products.xml' % spider.name, 'w+b')
        self.files[spider] = file
        self.exporters[spider] = XmlItemExporter(file)
        self.exporters[spider].start_exporting()

    def spider_closed(self, spider):
        self.exporters[spider].finish_exporting()
        file = self.files.pop(spider)
        file.close()

    def process_item(self, item, spider):
        self.exporters[spider].export_item(item)
        return item


text:
Q: How to make subplots with grouping by country I have 4 columns in a dataframe format: year, country, city, temperature.
I want to make a plot with subplots for each country. In each subplot I want a couple of lines which will be cities belonging to this country and y axis will be temperature.
For instance if I had 2 countries USA and UK, and cities Boston, NY, London and Liverpool, then I would like an output of 2 subplots with 2 lines on each.
I can do the plot with no distinction for cities with:
ax=df.plot.line(subplots=True, grid=True,layout=(3, 3))

A: You can also use groupby:
fig, axes = plt.subplots(1,2)

for (country, g), ax in zip(df.groupby('country'), axes.ravel()):
    sns.lineplot(data=g, hue='city', x='year', y='temperature', ax=ax)

Output:


text:
Q: A real upper-triangular matrix commutes with its transpose then the matrix is diagonal. Let $A$ be a real, upper-triangular, $n\times n$  matrix
that commutes with its transpose. How can I show that $A$ is diagonal?
I want to show that $A-A^t =0$ but I can't. Please help me.

A: Hint: One approach applies the following observation: if $A$ is block upper-triangular with
$$
A = \pmatrix{B & C\\0 & D}
$$
Then
$$
A^TA = \pmatrix{B^TB & B^TC\\C^TB & C^TC + D^TD}\\
AA^T = \pmatrix{BB^T + CC^T & CD^T\\D^TC & DD^T}
$$
By taking the trace of each side, show that
$$
C^TC + D^TD = DD^T \implies C = 0
$$

A: $A^TA = AA^T$ means that the matrix $A$ is normal. This implies $\|Ax\| = \|A^Tx\|, \forall x\in\mathbb{R}^n$.
We have
$$|a_{11}|^2 = \|\text{first column of } A\|^2 = \|Ae_1\|^2 = \|A^Te_1\|^2 = \|\text{first row of } A\|^2 = \sum_{j=1}^n |a_{1j}|^2$$
so it follows that $a_{12} = a_{13} = \cdots = a_{1n} = 0$.
Continuing we get
$$|a_{22}|^2 = \|\text{second column of } A\|^2 = \|Ae_2\|^2 = \|A^Te_2\|^2 = \|\text{second row of } A\|^2 = \sum_{j=2}^n |a_{2j}|^2$$
so it follows that $a_{23} = a_{24} = \cdots = a_{2n} = 0$.
Continuing inductively we get that $A$ is diagonal.


text:
Q: Java 9 ServiceLoader runtime module loading and replacement I just read about Java 9 module system and I'd like to ask about ServiceLoader. Is there any way how to add service implementation when the application is already started? How about removing some service implementation?
Use case: I will have some application that calculates something. The calculation algorithm will be defined in some service(Java 9 module). Are there any steps that can be done to replace this algorithm without stopping the application? When will I replace the jars is it just that the calculation will fail and I will need to catch the error and restart when the module is done loading?
Is there any other project that can support such use case?

A: Lets Assume BankController is your service .
If you want to load its implementation dynamically from dynamic path,create a new module layer and load implementation.
private final BankController loadController(final BankConfig config) {
    System.out.println("Loading bank with config : " + JSON.toJson(config));
    try {
        //Curent ModuleLayer is usually boot layer. but it can be different if you are using multiple layers
        ModuleLayer currentModuleLayer       = this.getClass().getModule().getLayer(); //ModuleLayer.boot();
        final Set<Path> modulePathSet        = Set.of(new File("path of implementation").toPath());
        //ModuleFinder to find modules
        final ModuleFinder moduleFinder      = ModuleFinder.of(modulePathSet.toArray(new Path[0]));
        //I really dont know why does it requires empty finder.
        final ModuleFinder emptyFinder       = ModuleFinder.of(new Path[0]);
        //ModuleNames to be loaded
        final Set<String>  moduleNames       = moduleFinder.findAll().stream().map(moduleRef -> moduleRef.descriptor().name()).collect(Collectors.toSet());
        // Unless you want to use URLClassloader for tomcat like situation, use Current Class Loader
        final ClassLoader loader             = this.getClass().getClassLoader();
        //Derive new configuration from current module layer configuration
        final Configuration  configuration   = currentModuleLayer.configuration().resolveAndBind(moduleFinder, emptyFinder, moduleNames);
        //New Module layer derived from current modulee layer
        final ModuleLayer    moduleLayer     = currentModuleLayer.defineModulesWithOneLoader(configuration, loader);
        //create new instance of Implementation, in this case org.util.npci.coreconnect.CoreController implements org.util.npci.api.BankController
        final BankController bankController  = ServiceLoader.load(moduleLayer, BankController.class);
        return bankController;
    } catch (Exception e) {BootLogger.info(e);}
    return null;
}


text:
Q: Serialization and Deserialization When References Are Involved in C# I have a singleton class called Manager that holds a list of object instances:
static class Manager
{
    static List<Foo> Foos = new List<Foo>();
}

I then have a collection of object instances using a class called Meter that uses references to items in the list Foos:
class Meter
{
    public Foo MyFoo = null;
}

...

public void CreateMeter(int UserChoice)
{
    Meter MyMeter = new Meter();
    MyMeter.MyFoo = Manager.Foos[UserChoice];
}

When the application saves a project file it serializes the instances of Foo in Foos along with all the instances of Meter.
My problem is how to deserialize this arrangement. Currently I do the following:

*

*Deserialize the project-wide instances of Foo to reconstruct Manager.Foos

*Deserialize a meter instance which includes an instance of Foo for the MyFoo property

*Search Manager.Foos and find the matching reference for MyMeter.MyFoo and then assign the reference from Manager.Foos.

This seems to me clunky and not too easy to extend. I would rather that the Meter factory doesn't need to search Manager.Foos during deserialization because in future Meter might take it's refence to a Foo instance from other places, not just Manager.
Is there a simple but flexible alternative solution to this deserialization problem where references to objects can be easily reconstructed?

A: Serialisation is hard :)
Doing this automatically in a way that doesn't mess with the format is a pain. A common trick here is to assign an unrelated opaque key while de/serialising, using a central map. You can see this in DataContractSerializer by enabling reference-tracking in the constructor. This key is then used to check for existing objects as a substitute.
Personally, when it gets that complex IMO it is time to use a pre-canned aerializer; Even inside a dedicated library it is a bit challenging. The approach I use (protobuf-net) is pretty similar, but harder to read (binary dense output, etc).

A: in Manager class add
public static ulong IdProvider=0
in Foo class add
public ulong MyId
in Foo ctor add
MyId=Manager.IdProvider++;
each Foo class will have a unique id ( up to 2^64-1 instances), just save the IdProvider so you could continue to add unique ids upon reconstruction.
You might want to consider changing the Meter class to hold the Foo's unique id and provide a property (get;set) to link to the "Foos" in the Manager class.
I haven't completely understood what you want but from this point of view you've made quite a mess :p

A: Thanks Marc and everyone else for the suggestions. Based on Marc's key idea and Henk's object id generator here is what I have so far.
Foo defines a Guid property which contains a unique Guid. This is generated in the constructor but can also be saved/restored with serialization/deserialization.
class Foo
{
    public Guid TheGuid = Guid.NewGuid();
}

Meter no longer uses a reference, instead it uses a Guid:
class Meter
{
    public Guid FooGuid;
}

When a meter is created the Guid establishes the connection:
public void CreateMeter(int UserChoice)
{
    Meter MyMeter = new Meter();
    MyMeter.FooGuid = Manager.Foos[UserChoice].TheGuid;
}

When Meter is serialized/deserialized the Guid is stored/loaded.
One downside is when the Foo instance associated with a meter needs to be accessed. Instead of directly using the reference a lookup has to be performed which will incur a performance hit:
class Manager
{
    public List<Foo> Foos = new List<Foo>();

    public Foo GetFooFromGuid(Guid SearchGuid)
    {
        // search Foos and return instance with Guid == SearchGuid
    }
}

A benefit of this approach is that now I can create a delegate and have multiple sources of Foo to associate with meters:
Func<Guid, Foo> FooSource;

FooSource ManagerFooSource = Manager.GetFooFromGuid;


text:
Q: Extract item from json with javascript or jquery I have this json link that is generated auttomatically by a software and I was trying a lot of methods to extract that number. I can't extract this 301191004942
var listingID = 'http://shared1.ad-lister.co.uk/GetListingDetails.aspx?id=43baf400-dbe1-4238-b608-38303e65faea&contextId=c9d56aca-506c-40be-9068-037d0fba62c9';

adn this is the result
{"ListingId":"301191004942"}

any help, please?

A: Assuming the server allows cross-domain AJAX:
$.get(listingID, function(data) {
    var listing = data.ListingId;
    // Do something with listing
}, "json");

A: Use AJAX,
$.ajax({
     type: "GET",
     url: "http://shared1.ad-lister.co.uk/GetListingDetails.aspx",
     data: {id:'43baf400-dbe1-4238-b608-38303e65faea',contextId:'c9d56aca-506c-40be-9068-037d0fba62c9'},
     dataType:"json",
     success:function(data,textStatus,jqHXR) {
         alert(data.ListingId); //now you've got it, you can do what you want.
     }
});

Note that this will happen asynchronously, so the code in success may run a couple seconds after the rest of the AJAX code.

A: Here you go (jQuery solution below, hope you're using jQuery)-
    $.ajax({
type: 'GET',
dataType: 'text',
crossDomain: true,
url:'http://shared1.ad-lister.co.uk/GetListingDetails.aspx?id=43baf400-dbe1-4238-b608-38303e65faea&contextId=c9d56aca-506c-40be-9068-037d0fba62c9',
success : function(data){

       var item = JSON.parse(data);
        console.log(item.ListingId);

        }
});


text:
Q: Basic service test I have a service like :
login.service.ts
import { Injectable } from 'angular2/core';
import { Http, Response, Headers } from 'angular2/http';
import { Config } from '../common/config';

@Injectable()
export class LoginService {

    constructor(public http: Http) { }
    response: JSON;
...

    getAuthenticate( username, password ) {
        let headers = new Headers();
        const REST_BASE_URL = Config.GET_REST_BASE_URL;
        let query = '?userid=' + username + ' +&action=authenticate&password=' + password;
        headers.set('Accept', 'application/json');
        return this.http.get(REST_BASE_URL + query, {
        headers: headers
         }).map((res: Response) => res.json());
    }
}

I need to write a test for e.g. getAutenticate() method. No idea how I should inject that Http (mock-up vs real rest service). Here is my starting point:
import { it, describe, expect, inject, beforeEachProviders} from 'angular2/testing';
import {Http} from 'angular2/http';
import { LoginService } from './login.service';

class MockLoginService extends LoginService {
    // todo something
}

describe('login service', () => {
    beforeEachProviders(() => [
        provide(TestService, {useClass: MockLoginService}), Http
  ]);

    // beforeEachProviders(() => [LoginService, Http]);
    it('should find credentials', inject([LoginService], (myService:MockLoginService) => {
        console.log('HERE ', myService.getAutenticate('user1', 'pass1'));
        expect(true).toBe(true);
    }));
});

What would be a good approach ?

A: In fact to test your LoginService you need to mock its dependencies and not the service itself. In this case, you need to replace the XHRBackend class by the MockBackend one.
beforeEachProviders(() => {
    return [
  HTTP_PROVIDERS,
  provide(XHRBackend, { useClass: MockBackend }),
        HttpService
    ];
});

Then you can inject the XHRBackend and subscribe on its connections property to intercept requests and return your own responses.
Here is a sample with a service called HttpService:
it('test HTTP service', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
    mockBackend.connections.subscribe(
        (connection: MockConnection) => {
            connection.mockRespond(new Response(
                new ResponseOptions({
                    body: ['some content']
                })));
    });

    httpService.getMethod().subscribe(
        items => {
            expect(items).toEqual(['test']);
        },
        () => {
            console.log('error');
        });
}));

The HttpService could be the following:
@Injectable()
export class HttpService {
  constructor(private http:Http) {
  }

  getMethod() {
    return this.http.get('/test').map(res => res.json());
  }
}


text:
Q: how to copy the value of a cell to another cell by searching a column Here's what I mean:
How do I create a formula that will find and copy the first cell in the column that is a negative number?
I know this isn't correct, but it's where I'm starting.
=if(E:E,<0,?)
I've been searching for answers to this question, but I hardly even know how to ask the question.

A: This will return the first number less than 0 in column E:
=INDEX(E:E,AGGREGATE(15,6,ROW($E$1:INDEX(E:E,MATCH(1E+99,E:E)))/($E$1:INDEX(E:E,MATCH(1E+99,E:E))<0),1))


text:
Q: I want to limit the total number of product in the cart to 3 using woocommerce Do we have any options through which we can limit the number of total items that can be added to cart in woocommerce. I want to limit the total number of product in the cart to 3.

A: Have you checked out this plugin: https://wordpress.org/plugins/min-and-max-purchase-for-woocommerce/ or https://wordpress.org/plugins/maximum-purchase-for-woocommerce/ you can also see this one developed by woocommerce: http://docs.woothemes.com/document/minmax-quantities/


text:
Q: Creating TextIndex in Micronaut with reactive mongoDB I am using reactive mongoDB with Micronaut application
implementation("io.micronaut.mongodb:micronaut-mongo-reactive")

Trying to create a TextIndex and search Free text functionality
public class Product {
    @BsonProperty("id")
    private ObjectId id;
    private String name;
    private float price;
    private String description;
}

In spring data we have @TextIndexed(weight = 2) to create a TextIndex to the collection, what is the equivalent in the Micronaut application.

A: I'm afraid that Micronaut Data does not yet support automatic index creation based on annotations for MongoDB. Micronaut Data now simplifies only work with SQL databases.
But you can still create the index manually using MongoClient like this:
@Singleton
public class ProductRepository {

    private final MongoClient mongoClient;

    public ProductRepository(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    public MongoCollection<Product> getCollection() {
        return mongoClient
            .getDatabase("some-database")
            .getCollection("product", Product.class);
    }

    @PostConstruct
    public void createIndex() {
        final var weights = new BasicDBObject("name", 10)
            .append("description", 5);

        getCollection()
            .createIndex(
                Indexes.compoundIndex(
                    Indexes.text("name"),
                    Indexes.text("description")
                ),
                new IndexOptions().weights(weights)
            )
            .subscribe(new DefaultSubscriber<>() {
                @Override
                public void onNext(String s) {
                    System.out.format("Index %s was created.%n", s);
                }

                @Override
                public void onError(Throwable t) {
                    t.printStackTrace();
                }

                @Override
                public void onComplete() {
                    System.out.println("Completed");
                }
            });
    }

}

You can of course use any subscriber you want. That anonymous class extending DefaultSubscriber is used here only for demonstration purpose.
Update: You can create indexes on startup for example by using @PostConstruct. It means to add all index creation logic in a method annotated by @PostConstruct in some repository or service class annotated by @Singleton, then it will be called after repository/service singleton creation.


text:
Q: Rails 3 - vote_fu - Query for specific vote by a voter on voteable I'm trying to query for a specific vote within the vote_fu plugin so that I can destroy it. I need to do this as I've implemented the one vote per user policy, but I'd like user's to be able to remove votes.
So what I have is a Link model, which is voteable, and User as the voter. In theory, should I not be able to do something like:
@link.votes.find_by_user_id(current_user.id).destroy

Though votes is not a support method due to it not being a table I built in the db. I've read through vote_fu's documentation, and I can't really seem to find/or figure out how I'm supposed to destroying votes.
def destroy
      @vote = Vote.find(params[:id])
      @vote.destroy

      respond_to do |format|
        format.html { redirect_to(user_votes_url) }
        format.xml  { head :ok }
      end
    end

Is in vote_fu's lib, so I should be able to call a destroy on the vote, I just need to be able to find the vote.
Anyway, thanks for the help.

A: I was going about this the wrong way. My final code is as follows:
def unvote
    @link = Link.find(params[:id])
    @vote = current_user.votes.find_by_voteable_id(@link.id)
    @vote.destroy
    redirect_to :back
  end

Then in my view:
<%= link_to "Delete Vote", unvote_topic_link_path(@topic, link), :method => :delete %>

and my route if you want the whole picture of everything going on:
resources :links do
      member do
        post 'vote'
        delete 'unvote'


text:
Q: What is the recommended / best way to do this: Event calendar post/type in a block-based theme? my question is this: assume I have a php-themed WordPress site with an event calendar page template that's using post type "event", which in turn has a lot of custom fields that hold the post meta. On the front end, a long list of events is output based on a custom query. This is a very common real world scenario.
In a block based theme, what would be the best way to handle this scenario? Assuming that it's still useful to have a distinct, queryable representation of every event with its custom fields in the data base instead of a simple list of html blocks.
The introduction of the block-editor has made blocks the smallest data container, yet one that cannot be idenpendently queried and reassembled. There's also no admin UI for accessing individual blocks independent of their container posts. So for all aspects that require querying, posts are still the smallest data container in WordPress.
So what is the best way to go about this?
For the input side I can thus see two options:

*

*A custom block with a locked block template for the "event post type" to input the event info, and ideally save to post meta? I can see how it would then be possible to query even according to invisible post meta in the frontend.

*Or a lockable? block pattern for the "event post type" post which will save everything in it to post-content and potentially needs to be parsed in some way when queried/rendered. I'm not sure how invisible post meta could be/ would be handled in this scenario.
For the output side

*

*I would either (probably) need a custom output query loop block that takes care of the query and dynamic rendering (and backend representation).

*or possibly use the query block if specific event query can be supported.

I consider this one of the most common current use cases, so I'm hoping someone has already thought about this, given that everything is supposed to become block based in the future.
Thanks for your ideas and consideration!


text:
Q: Xamarin IOS custom URL Scheme not working in iOS 14 I created a Xamarin forms application and configured custom URL Scheme for iOS but it didn't fire in iOS 14.
So I created a sample native iOS project and test custom URL Scheme and it is working.
This is the sample iOS swift code.
 import SwiftUI

 @main
 struct TestApp: App {
 //@UIApplicationDelegateAdaptor var delegate: AppDelegate
 var body: some Scene {
    WindowGroup {
        ContentView().onOpenURL(perform: handleURL)
    }
 }

func handleURL(_ url: URL) {
    print("source application")
    print(url)
}

}
But how can I convert this same to Xamarin. Because how to call onOpenURL in Xamarin iOS?

A: Add info about your custom scheme in your info.plist. You can do this in your iOS Project Options:
Double-click your iOS project >> Build > iOS Application >> Advanced (tab)
At the bottom, you'll see a section URL Types. Add your info about your custom scheme there. For example:
In the "Identifier" field, enter "com.myapp.urlscheme". In the "URL Scheme" field, enter "myapp".
Next you need to override in your AppDelegate file:
public override bool OpenUrl (UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
// custom stuff here using different properties of the url passed in
return true;
}

Go ahead and set a breakpoint on "return true" in the override above
Now if you build and run on the simulator, then enter "myapp://com.myapp.urlscheme" into the url bar in Safari (on the simulator), it should launch your app, hit your breakpoint, and the "url" param will be "myapp://com.myapp.urlscheme".


text:
Q: "search?.actionView as SearchView" crashes moving to the Second Activity I am building a simple app (in Kotlin), which has a simple button in MainActivity.kt, that when clicked opens a second activity. The second activity has an array (from strings.xml). When the selected list item the result should be passed to the first activity.
When I click on the button to go to the second activity it crashes (on " val searchView : SearchView = search?.actionView as SearchView") – although it is reporting errors in the log (which I don't really understand).
I'm using the androidx.appcompat.widget.SearchView library which I had seen problems using the old library, so I don't think it is that.
Any help really appreciated - thanks.
MainActivity.kt
class MainActivity : AppCompatActivity() {

private val SEARCH_ACTIVITY_REQUEST_CODE = 1
/* THE GUTS OF IT */
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    Searchbutton.setOnClickListener {
        Log.d("TAG", "MainActivity 1- JH")
        val intent = Intent(this, SearchActivity::class.java)
        Log.d("TAG", "MainActivity 2- JH")
        startActivityForResult(intent, SEARCH_ACTIVITY_REQUEST_CODE)
        Log.d("TAG", "MainActivity 3- JH")
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    Log.d("TAG", "onActivityResult starting 100 - JH")
    super.onActivityResult(requestCode, resultCode, data)

    Log.d("TAG", "onActivityResult 101 - JH")
    if (requestCode == SEARCH_ACTIVITY_REQUEST_CODE) {
        val gotthisInt = data?.getStringExtra("result")

        Log.d("TAG", "What was received  JH = $gotthisInt")
        if (resultCode == RESULT_OK) {
            /* val gotthisInt = data?.getStringExtra("result") */
            val gotPosition = data?.getStringExtra("position")
            Log.d("TAG", "What was POSITION  JH = $gotPosition")
        }
    }
}

}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
 <androidx.constraintlayout.widget.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!-- Debug - to be deleted -->
<TextView
    android:id="@+id/textDebug"
    android:layout_width="69dp"
    android:layout_height="40dp"
    android:layout_marginBottom="104dp"
    android:text="DEBUG HETE"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/Searchbutton"
    android:layout_width="58dp"
    android:layout_height="50dp"
    android:layout_marginBottom="80dp"
    android:drawableLeft="@android:drawable/ic_menu_search"
    app:layout_constraintBottom_toTopOf="@+id/textDebug"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
SearchActivity.kt
class SearchActivity : AppCompatActivity() {
private lateinit var toolbar: Toolbar
lateinit var adapter: ArrayAdapter<*>
private lateinit var listView: ListView
private lateinit var emptyView: TextView

override fun onCreate(savedInstanceState: Bundle?) {
    Log.d("TAG", "SearchActivity OnCreate Starts JH")

    super.onCreate(savedInstanceState)

    setContentView(R.layout.search_main)

    title = "Search App"
    toolbar = findViewById(R.id.toolbar)
    listView = findViewById(R.id.listView)
    emptyView = findViewById(R.id.emptyView)

    adapter = ArrayAdapter<Any?>(this, android.R.layout.simple_list_item_1,
        resources.getStringArray(R.array.vegetables))
    listView.adapter = adapter

    listView.onItemClickListener = OnItemClickListener { adapterView, _, i, _ ->
        Toast.makeText(this@SearchActivity, adapterView.getItemAtPosition(i).toString(),
            Toast.LENGTH_SHORT).show()
    }
    listView.emptyView = emptyView
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    Log.d("TAG", "onCreateOptionsMenu Starts JH")

    menuInflater.inflate(R.menu.menu, menu)
    Log.d("TAG", "onCreateOptionsMenu 901 JH")
    val search = menu.findItem(R.id.appSearchBar)
    Log.d("TAG", "onCreateOptionsMenu 902 JH")
    /*val searchView = search.actionView as SearchView CRASH */
    val searchView : SearchView = search?.actionView as SearchView  /* This crashes for my code, works here */

    Log.d("TAG", "onCreateOptionsMenu 903 JH")

    searchView.queryHint = "Search"
    Log.d("TAG", "onCreateOptionsMenu 904 JH")

    listView.setOnItemClickListener(OnItemClickListener { parent, view, position, id ->
        val intent = Intent()
        val theItemClicked = String()
        /* Log.d("TAG", "onCreateOptionsMenu - 209 - Gets here JH")
            theItemClicked = list[position].toString() */

        intent.putExtra("result", "this one")
        intent.putExtra("position", "hello")
        setResult(RESULT_OK, intent)
        finish()
    })

    searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            return false
        }
        override fun onQueryTextChange(newText: String?): Boolean {
            adapter.filter.filter(newText)
            return true
        }
    })
    return super.onCreateOptionsMenu(menu)
}

}
Search_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SearchActivity">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorBackgroundFloating"
        android:minHeight="?attr/actionBarSize" />
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/emptyView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="No Results"
        android:textSize="20sp"
        android:visibility="gone" />

nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>

<item
    android:id="@+id/appSearchBar"
    android:icon="@drawable/ic_baseline_search_24"
    android:title="Search"
    app:actionViewClass="androidx.appcompat.widget.SearchView"
    app:showAsAction="always" />

logcat Errors
These errors are shown when I click to move to the second activity:
2021-01-27 22:54:47.956 1429-1429/com.dbtest.VegJanv20211 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dbtest.VegJanv20211, PID: 1429
kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.widget.SearchView
    at com.dbtest.VegJanv20211.SearchActivity.onCreateOptionsMenu(SearchActivity.kt:55)
    at android.app.Activity.onCreatePanelMenu(Activity.java:4074)
    at androidx.fragment.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:325)
    at androidx.appcompat.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:94)
    at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.onCreatePanelMenu(AppCompatDelegateImpl.java:3070)
    at androidx.appcompat.app.AppCompatDelegateImpl.preparePanel(AppCompatDelegateImpl.java:1895)
    at androidx.appcompat.app.AppCompatDelegateImpl.doInvalidatePanelMenu(AppCompatDelegateImpl.java:2176)
    at androidx.appcompat.app.AppCompatDelegateImpl$2.run(AppCompatDelegateImpl.java:271)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2021-01-27 22:54:48.053 1967-2079/system_process E/InputDispatcher: channel 'b8064d4 com.dbtest.VegJanv20211/com.dbtest.VegJanv20211.SearchActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2021-01-27 22:54:48.055 1967-2079/system_process E/InputDispatcher: channel '1b19412 com.dbtest.VegJanv20211/com.dbtest.VegJanv20211.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2021-01-27 22:54:49.436 2609-3310/com.google.android.gms.persistent E/ModuleIdSetter: exception when setting module id
    java.lang.IllegalStateException: Unable to get current module info in ModuleManager created with non-module Context
        at com.google.android.chimera.config.ModuleManager.getCurrentModule(:com.google.android.gms@202414022@20.24.14 (040700-319035315):2)
        at aewd.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):4)
        at aewg.b(:com.google.android.gms@202414022@20.24.14 (040700-319035315):9)
        at aeso.a(Unknown Source:0)
        at rpm.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):0)
        at rlv.c(:com.google.android.gms@202414022@20.24.14 (040700-319035315):1)
        at rlt.b(:com.google.android.gms@202414022@20.24.14 (040700-319035315):1)
        at rok.b(:com.google.android.gms@202414022@20.24.14 (040700-319035315):6)
        at rok.c(:com.google.android.gms@202414022@20.24.14 (040700-319035315):6)
        at rok.b(:com.google.android.gms@202414022@20.24.14 (040700-319035315):10)
        at rok.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):17)
        at rok.g(:com.google.android.gms@202414022@20.24.14 (040700-319035315):3)
        at sdr.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):2)
        at scr.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):10)
        at sci.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):0)
        at scl.handleMessage(:com.google.android.gms@202414022@20.24.14 (040700-319035315):28)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at aekz.a(:com.google.android.gms@202414022@20.24.14 (040700-319035315):2)
        at aekz.dispatchMessage(:com.google.android.gms@202414022@20.24.14 (040700-319035315):14)
        at android.os.Looper.loop(Looper.java:214)
        at android.os.HandlerThread.run(HandlerThread.java:67)
2021-01-27 22:54:49.910 2609-2609/com.google.android.gms.persistent E/BeaconBle: Missing BluetoothAdapter [CONTEXT service_id=111 ]
2021-01-27 22:54:49.938 2609-2609/com.google.android.gms.persistent E/BeaconBle: Scan couldn't start for Places [CONTEXT service_id=111 ]

These errors are shown while I am still in the MainActivity.kt:
2021-01-27 22:52:06.434 1967-1967/system_process E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/com.dbtest.VegJanv20211-e8K-P0xolKFD4G9UM3OUYg==/lib/x86, /system/lib, /system/product/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.app.LoadedApk.createAppFactory(LoadedApk.java:256)
    at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:370)
    at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5951)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1941)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at com.android.server.SystemServer.run(SystemServer.java:541)
    at com.android.server.SystemServer.main(SystemServer.java:349)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:908)

2021-01-27 22:52:06.546 2469-3889/com.google.android.apps.nexuslauncher E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
2021-01-27 22:52:06.818 2844-3382/com.google.android.gms E/GmsClient: unable to connect to service: com.google.android.gms.auth.key.retrieval.service.START on com.google.android.gms
2021-01-27 22:52:06.913 1783-2066/? E/installd: Failed to delete /data/app/vmdl1729715317.tmp: No such file or directory
2021-01-27 22:52:07.234 1967-1999/system_process E/system_server: Invalid ID 0x00000000.
2021-01-27 22:52:07.516 1429-1429/? E/st.VegJanv2021: Unknown bits set in runtime_flags: 0x8000
2021-01-27 22:52:08.670 1750-2559/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2021-01-27 22:52:08.676 1750-1906/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2021-01-27 22:52:09.982 1874-1874/? E/netmgr: Failed to open QEMU pipe 'qemud:network': Invalid argument
2021-01-27 22:52:10.422 1896-1896/? E/wifi_forwarder: RemoteConnection failed to initialize: RemoteConnection failed to open pipe
2021-01-27 22:52:11.551 2469-3889/com.google.android.apps.nexuslauncher E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
2021-01-27 22:52:18.366 1967-2004/system_process E/memtrack: Couldn't load memtrack module
2021-01-27 22:52:30.088 1967-2004/system_process E/memtrack: Couldn't load memtrack module
2021-01-27 22:52:35.879 2609-1687/com.google.android.gms.persistent E/memtrack: Couldn't load memtrack module
2021-01-27 22:52:47.310 2844-1688/com.google.android.gms E/memtrack: Couldn't load memtrack module
2021-01-27 22:53:02.412 1967-4198/system_process E/memtrack: Couldn't load memtrack module
2021-01-27 22:53:10.040 1874-1874/? E/netmgr: Failed to open QEMU pipe 'qemud:network': Invalid argument
2021-01-27 22:53:10.431 1896-1896/? E/wifi_forwarder: RemoteConnection failed to initialize: RemoteConnection failed to open pipe
2021-01-27 22:52:56.607 2469-3889/com.google.android.apps.nexuslauncher E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api

A: The problem's this line at the top of your error log:
kotlin.TypeCastException: null cannot be cast to non-null type androidx.appcompat.widget.SearchView

which is talking about this (which you mentioned is where it's crashing):
val searchView : SearchView = search?.actionView as SearchView

So you're trying to cast the result of the expressionsearch?.actionView (which can be null, you're null-checking it after all) to a non-null SearchView type. You're effectively telling the compiler "don't worry, this is definitely not going to be null!" but sometimes it is, and that's why the app is crashing - you're trying to cast null to a type that can't be null.
So you need to make searchView nullable, i.e. the type needs to be SearchView? not SearchView:
val searchView : SearchView? = search?.actionView as SearchView?


text:
Q: Create nib in bundle I'm new to ios, and can't get done pretty simple thing.
TableViewController *tableVC = [[TableViewController alloc] initWithNibName:@"TableView" bundle:nil andType:CONTROLLER_TYPE_FIRST];
ViewController *wizard = [[ViewController alloc] initWithNibName:@"WizardView" bundle:nil andtype:first];
UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:wizard];

Init with tableVC, works. But if I initialize with wizard i get
'Could not load NIB in bundle: 'NSBundle </Users/Mac/Library/Application Support/iPhone Simulator/6.0/Applications/60750878-E595-4A24-B0B8-F65DA78128C0/kodinisRaktas.app> (loaded)' with name 'WizardView''

What to do with this bundle nib to get it working?

A: Cases:

*

*ViewController doesnot have .xib .

*ViewController does have .xib but its name is not 'WizardView'.

Solution:
Case 1:
 ViewController *wizard = [[ViewController alloc] init];

Case 2:
use correct name of .xib file


text:
Q: How do I algebraically express a rotated triangle in terms of its original dimensions and its rotation? Given a triangle ABC. Rotate it around the origin A by -30$^\circ$ to triangle ADE. How do I algebraically express DJ (the y coordinate of D) in terms of the edges of ABC (the original 20$^\circ$ right-triangle) and/or AGI (the 30$^\circ$ right-triangle)?
The dimensions of ABC and AGI is known, so I could calculate the ratios between their edges but the trig values of 50$^\circ$ is not known.

A: Since $AGI$  and $EGH$ are proportional (Thales) :
$$\widehat{HEG}=30° \implies \widehat{DEF}=60°\implies DF = DE\sin(60°)=BC\frac{\sqrt{3}}{2}$$
Now you only have to find $FJ=HI=GI-GH$
You have $EG=GA-AC$
$AGI$ and $EGH$ are proportional (Thales) and therefore
$$GH=GI\frac{GE}{GA}$$
In the end,
$$FJ=GI\left(1-\frac{GA-AC}{GA}\right)=GI\frac{AC}{GA}$$
$$DJ=DF+FJ=BC\frac{\sqrt{3}}{2}+GI\frac{AC}{GA}$$


text:
Q: LEFT JOIN query MYSQL does not work I have 2 tables rtz_order and rtz_restaurant
From order I want purchaseprice from restaurant i want "restaurant_commission" both have a column called restaurant_id So i want to join these to tables and add the restaurant_commission tot the query. I have come up with this (the date part etc works, i was already using that but the query does not work since I added the join)
$sql = 'SELECT
    order.orderpurchase,
    order.orderdate,
    order.status,
    order.restaurant_id,
    res.restaurant_commission,
    res.restaurant_id
FROM rt_order order
    LEFT JOIN rt_restaurant res ON order.restaurant_id = res.restaurant_id
WHERE date(order.orderdate) >= date(?) AND date(order.orderdate) <= date(?)
    AND order.restaurant_id = ? AND order.status = "completed"';

I have tried diffrent things but i do not see why this is going wrong

A: ORDER is a reserved keyword.
Use backtics like:
`ORDER`

Check the complete list of reserved keywords here.

NOTE : It is better to avoid reserved keywords for column names, but if you use then wrap them with backtics.

A: Your alias order is a MySQL reserved word.
Make it either `order` using backticks, or change the alias' name.


text:
Q: cannot declare field '' to be of abstract type '' I'm trying to write asynchronous code on callbacks and stuck into this error:
error: cannot declare field 'std::_Head_base<3, Callback, false>::_M_head_impl' to be of abstract type 'Callback'
note:   because the following virtual functions are pure within 'Callback'
...
error: no matching function for call to 'std::tuple<api_add(int, int, Callback&&)::<lambda(int, int, Callback&&)>, int, int, Callback>::tuple(<brace-enclosed initializer list>)} };

My abstract class:
class Callback {
public:
    virtual void OnResult(ApiResultType res) = 0;
};

Derived class:
class ApiCallBack: public Callback {
public:
    ApiCallBack() {

    };
    virtual void OnResult(ApiResultType res) {
        std::cout << "OnResult: " << res.first << "; " << res.second << std::endl;
        ...
    }
};

main():
int main() {
    // Running API operations

    ApiCallBack Callable;
    api_add(kOperationArg1, kOperationArg2, std::forward<ApiCallBack>(Callable));
    ...
}

Asynchronous function implementation:
void api_add(int arg1, int arg2, Callback &&func) {
    std::async(std::launch::async, [](int arg1, int arg2, Callback &&func) {
                func.OnResult({"API_Mul", arg1 + arg2});
               }, arg1, arg2, std::forward<Callback>(func));
}

After spending a bit of time understanding the code I wrote I suggest that the error is in the last chunk of code (async or lambda), but can't still figure out what's actually wrong. Please help.

A: The real problem with your code is this:
std::async(std::launch::async, [](int arg1, int arg2, Callback &&func) {
        func.OnResult({"API_Mul", arg1 + arg2});
}, arg1, arg2, std::forward<Callback>(func));

The call to async that you are using has this signature:
template< class Function, class... Args>
std::future<std::invoke_result_t<std::decay_t<Function>, std::decay_t<Args>...>>
async( std::launch policy, Function&& f, Args&&... args);

The important thing to notice above is the returned future holds an invoke_result_t containing std::decay_t<Args>..., which removes references (and constness, decays arrays and functions to pointer, etc).  But removing reference is the problem you're running into, as it would try to invoke your function with those args.
Since you are passing a Callback& to the function, after decay it is Callback, and the instantiated template code attempts to hold just a Callback (base) by value.
The real fix here, if you want to keep your original approach (for the most part) is to use a std::reference_wrapper to hold your callback.  This can be done with a call to std::ref() -- which returns a reference wrapper referencing its argument.  Decaying a reference wrapper does not lose its "reference semantics":
std::async(std::launch::async, [](int arg1, int arg2, Callback &&func) {
        func.OnResult({"API_Mul", arg1 + arg2});
}, arg1, arg2, std::ref(func)); // <<<<< HERE

Of course, it's also your responsibility to ensure that the callback actually lives as long as the async code can run.

A: Use override for overriding functions.
// virtual void OnResult(ApiResultType res) { -->
void OnResult(ApiResultType res) override {
  // ...

std::forward<ApiCallBack>(Callable)) makes no sense, since Callable is not a rvalue or generic reference. Use std::move(Callable)).
The above will not fix the error, but will make the code a bit better. The solution:
int main() {
    // Running API operations

    std::unique_ptr<Callback> Callable(new ApiCallBack);
    api_add(kOperationArg1, kOperationArg2, std::move(Callable));
    ...
}

void api_add(int arg1, int arg2, std::unique_ptr<Callback> func) {
    std::async(std::launch::async, [](int arg1, int arg2, std::unique_ptr<Callback> func) {
                func->OnResult({"API_Mul", arg1 + arg2});
               }, arg1, arg2, std::move(func));
}

The better approach is using std::function<void(ApiResultType)> instead of the Callback or unique pointer.
class ApiCallBack {
public:
    void operator()(ApiResultType res) {
        std::cout << "OnResult: " << res.first << "; " << res.second << std::endl;
        ...
    }
};

int main() {
    // Running API operations

    ApiCallback Callable;
    api_add(kOperationArg1, kOperationArg2, std::move(Callable));
    ...
}

void api_add(int arg1, int arg2,  std::function<void(ApiResultType)> func) {
    std::async(std::launch::async, [](int arg1, int arg2, std::function<void(ApiResultType)> func) {
                func({"API_Mul", arg1 + arg2});
               }, arg1, arg2, std::move(func));
}


text:
Q: How to alternate service class implementation on-the-fly in component based provider? I'm still new in Angular. Currently, I have two implementation of REST service based on one abstract class in one of our component. Just like this scenario, the only difference is that I inject the service in component level:
@Component({
  selector: 'this-is-tag',
  template: htmlStr,
  providers: [{ provide: RESTToken, useClass: FirstRESTService }],
  ...

Question is, can I switch the implementation on the runtime, based on specific config? Or, should I use different approach for this problem?
EDIT:
Seems like I need to use interface, instead of abstract class here. link

A: The solution is useFactory instead of UseClass, change your code like the below example :
At first, create a factory class with a decision to DI logic:
export function myFactory() {
  if(myRule){
       return new FirstRESTService();
    }
  return new  SecondRESTService();
}

Then change your component code  to :
@Component({
  selector: 'this-is-tag',
  template: htmlStr,
  providers: [{ provide: RESTToken, useFactory: myFactory}],

Sometimes there will be a situation, you want to add some dependencies to the factory because you need it to decide whether to return serviceA or serviceB.
To satisfy this we can use deps property like this:
export function myFactory(obj:MyDependencyClass) {
  if(obj.HasMyRule){
       return new FirstRESTService();
    }
  return new  SecondRESTService();
}

also,in your component:
@Component({
  selector: 'this-is-tag',
  template: htmlStr,
  providers: [{ provide: RESTToken, useFactory: myFactory}],
  deps: [MyDependencyClass]

but don't forget to include MyDependencyClass in app.module.ts.

A: So, I ended up using interface, instead of abstract class for this solution. And also, the inheritance method fails when I tried to use base class for two of my services, like this question.
This is my working solution, both in JIT and AOT compilation:
@Component({
  selector: 'invoice-list',
  templateUrl: './invoice-list.component.html',
  providers: [{ provide: RESTToken, useClass: InvoiceRESTService }],
  ...

The service that is actually being used in the component:
@Injectable()
export class InvoiceRESTService {

    public invoiceType: InvoiceType;

    constructor(
        private _visma: VismaRESTService,
        private _fortnox: FortnoxRESTService
    ) {}

    public get instance(): RESTServiceInterface {

        if (this.invoiceType === InvoiceType.Visma) {
            return this._visma;
        } else if (this.invoiceType === InvoiceType.Fortnox) {
            return this._fortnox;
        } else {
            console.log('Please set the invoice type.');
        }
    }

}

The interface itself:
export interface RESTServiceInterface {

  getExportDataFunctionURL(): string;

  // So far, only for Visma
  getAuthUrl?(): string;

  getButtonTitlle(): string;

  synchData(instanceUid: string, code?: string): Observable<Object>;

  updateInvoice(payload: any): Observable<Object>;

  // Loading messages
  getWaitingMessage(): string;

  getSuccessMessage(): string;

  getErrorMessage(code: VismaErrorCode | FortnoxErrorCode | BKErrorCode): string;

}

The services that implement the interface:
@Injectable({
  providedIn: 'root'
})

export class FortnoxRESTService implements RESTServiceInterface {
   ...
   ...
   ...
}

@Injectable({
    providedIn: 'root'
})

export class VismaRESTService implements RESTServiceInterface {
   ...
   ...
   ...
}


text:
Q: Jquery or javascript for search I have been looking for a script or API that i could use. To be able to search through data from mysql..
I have managed to create a dialog box and load all the data from mysql into it..
what i wont to be able to do have a text  box that when u type in there username it searches the data straight away for them and being able to do this without refreshing or close the dialog box...
Anyone who has any idea on how to do this or ahs done it and has code or anything the help is greatly apprenticed and sosry for the lack in knowledge about this kinda stuff i only know the very basic

A: AutoComplete plugin is your choice


text:
Q: Is there a way to take a screenshot everytime the key ''Space'' is pressed and released? I Don't want to press printscreen everytime, I'd like to take a SS everytime space is pressed and released, and said SS saved in a folder.
I've tried with PIL using ImageGrab, but im failing to create more that one SS, to put them in order. ''Image1.jpg'' ''Image2.jpg''
from PIL import ImageGrab
while True:0
keyboard.add hotkey('space')
SS = ImageGrab.grab()
save_path = "C:\\Users\\robbie\\Desktop\\prints\\image.jpg"
SS.save(save_path)

I've started Python last week and I Am terrible at it.

A: You always just overwrite the old screenshot with the new one when you save them with the same name. You can simply add the current time to the filename to make them unique:
import datetime

import keyboard
from PIL import ImageGrab

while True:
    if keyboard.is_pressed('space'):
        SS = ImageGrab.grab()
        time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        save_path = f"C:\\Users\\robbie\\Desktop\\prints\\image{time}.jpg"
        SS.save(save_path)

I also changed this to use keyboard.is_pressed(), because that's what you actually need for this.

A: Here is another working method:
import keyboard as k
import time
from PIL import ImageGrab
while True:
    if k.is_pressed("space"):
        SS = ImageGrab.grab()
        save_path = "C:\\Users\\robbie\\Desktop\\prints\\image " + str(time.time()) + ".jpg"
        SS.save(save_path)


text:
Q: Run a python script before loading webpage from javascript/html I have an index.html which reads a csv file and displays it on a webpage using Javascript DataTables. It is as follows:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>CSV to HTML Table</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/dataTables.bootstrap.css" rel="stylesheet">

CSV to HTML Table

I have this running on an ec2 instance. I want that when this url is opened, before loading the page, first a python script called computation.py should be run that creates the above data/fatty_acid_profiles.csv file and then the page should load. How do I do I enable running the python script before loading the page?

A: You can create a simple flask app to serve the HTML file, refer Flask Documentation. In the index route, you can call computation.py's function to generate the required CSV file and then return the HTML page.


text:
Q: Open dialog with a result returned from following a url in a popUp built with magnificPopup My popup is opened successfully using this jquery code

    <link media="all" type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/magnific-popup.css">

    <button id="someid">Open popup</button>

How to open a dialog with a result returned from following a url ("someUrl" above) in a popUp built with magnificPopup?
Tried embeeding javascript function call into 'src' key of magnificPopup, however it didn't work.

A: If you are trying to open a webpage inside the magnific popup, use the type Ajax. Your code just links to a URL.
One other thing you can do is perform an ajax get and open the popup after the response. Make the response result of the ajax response as the data in your popup.


text:
Q: external monitor from imac: minidisplayport:hdmi, hdmi:displayport, not recognizing connected monitor I just got a new samsung monitor: S24E650DW and want to connect it to my imac. I had an mini-display to HDMI, and the store didn't have an mini-display to display port, so I thought I could use the hdmi-displayport.
The late 2015 imac running 10.12.6 however doesn't recognize that a external monitor i connected. In settings "displays" only show the build in retina display, and of course the samsung display show only a black screen, showing that it is set for display-port.
I have two mini-display to HDMI and tried both, so I think they should be working. Of course I tried both in both ports on the imac. The HDMI-display port-cable is brand new, and I don't have any way to test it, but I guess I must assume it works. I have tested the display on another computer at work, and it works fine.
I can't figure out what it is. that I don't understand. I read somewhere online that mini-display to display-port should work, I don't know if it is the HDMI junction that mess it up. Can anyone please help?


text:
Q: Installed Ubuntu along side Windows 10, only boots to Windows,boot gets error, then grub menu Upon boot I get [error: failure reading sector 0x0 from `hdo'.] and then it goes to Ubuntu's grub menu. I disabled secure boot, and have tried it with Windows' Legacy setting both enabled and disabled.
The only odd thing I did was gave all the available disk space to Ubuntu and limited Windows to what space it already occupies. I also enabled the encryption on the Home folder.
Edit: This may be unrelated, but I'll include it. I have an 8 TB external drive that is about 75% free space, but now Windows is reading it as completely full, with a capacity of only 2.36 TB. Did I accidently repartition and/or reformat my external drive?
Edit #2: It looks like I managed to install Ubuntu on my external Hard drive. The disk allocation on Windows wasn't changed. I suppose I will just redo the install with the external hard drive disconnected this time.

A: I "solved" this problem and am moving on to other problems. "Solved" in this case means I've learned that what I asked in my original question was based on a misunderstanding of the problem, and was not the actual problem.
What had happened was I inadvertently re-partitioned my external hard drive and installed Ubuntu there. It would only boot to Ubuntu if/when a certain combination of hard drives and flash drives were plugged into the hub at the same time. It took a while for me to figure out this pattern of events.
Unhooking all external drives was all that was needed to install Ubuntu correctly. Now both Windows and Ubuntu (with one minor exception) work perfectly. I no longer have any boot issues with Windows.
I was able to recover full use of the external hard drive by downloading and using Mini Tool Partition Wizard.
The one minor problem I'm having with Ubuntu is a series of error messages when trying to access the Windows partition and some of the partitions on the external drive. That I will research and address in new questions.
Thanks @oldfred for pointing me in the right direction.


text:
Q: suggestions for a ~20cm 2 way wireless communication between arduino like devices I am trying to build a system where, when and only when someone is within close proximity, about 20 cm or so, two arduino like devices can communicate wirelessly.
I want to be able to communicate data from the device back to the human, and data from the human to the device, probably with some kind of antenna mounted in the back of a glove.
I was looking into nfc, but it appears that nfc is one way.
What are your suggestions?
For clarification, I would like to add that there would be many devices that the user may or may not choose to use.

A: The most economical two way general communication often used for short path <1m  uses one or more optical transceivers such as IRDA and IRDA2 depending on bandwidth and nearby reflections or directional wide angle coverage.
https://www.digikey.ca/products/en/sensors-transducers/irda-transceiver-modules/538?k=IRDA&stock=1

A: Use some fast square wave edges, and let the displacement currents between 2 plates provide the data link. To avoid errors, have some pseudo-random patterns and have the receiver test the patterns of UP and DOWN spikes to validate the just-sent baud.


text:
Q: Apache2 server very slow download speed I am running Ubuntu 18.04.2 with a LAMP stack installed
The VPS running it has 16GB RAM and 6 CPU@2.2GHz, with 400Mb/s bandwidth provided, so this definitely shouldn't be maxing it out. It's also only used as the file download location of my site, downloads.example.com. Not seeing heavy usage either
The device being used to download the files is running on LTE with 7-8 MBps (megabyte not bit) internet
However, downloading a ~100MB file with either wget or curl is averaging 70KB/s
What's the issue here, and how do I solve it?


text:
Q: Does "end in" include the date? I have table with head "End in" and values as "week 5", "week 8", etc.
"End in" Week included? or may be different depending on the context?
For example:

A: In the example given, it means that you are to organize one drawer in your house each week for each of five weeks, starting with the first week and ending with the fifth.
At the conclusion of the fifth week, you will have organized five drawers in your house.  So yes, the fifth week is included.
It's possible that there is some context in which the "end in" week was excluded, but I can't think of such a context, and I imagine it would be unlikely.


text:
Q: iPhone SDK : Multiple images upload to server with SOAP request I know very well that you may count this thread as duplicate just because multiple times this question was asked in different ways. I did not find any solution from the existing questions on this forum and thus i'm going to make a new thread.
Here, I've a code for uploading multiple images at a time. So, please note down the sentence that is "multiple images upload".
I want to upload 1 or 2 or 3 or 4 images along with some text parameters and the issue that i'm facing is "same image is uploaded multiple times" mean single image having multiple times on server.
Example :
NSString *urlString = [NSString stringWithFormat:@"%@/MultipleImageUpload",soapAction];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[theRequest setHTTPShouldHandleCookies:NO];
[theRequest setTimeoutInterval:60];
[theRequest setURL:[NSURL URLWithString:urlString]];
[theRequest setHTTPMethod:@"POST"];

NSMutableData *body = [NSMutableData data];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",BOUNDARY_MULTIPART_IMAGE];
[theRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

//parameter SecurityCode
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDARY_MULTIPART_IMAGE] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"SecurityCode\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[SEC_CODE dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//parameter LoggedInUserID
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDARY_MULTIPART_IMAGE] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"LoggedInUserID\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"23433" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//parameter Device
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDARY_MULTIPART_IMAGE] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"Device\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"iPhone" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

for (int i=0; i<[arrImgs count]; i++) {
    UIImage* image = [arrImgs objectAtIndex:i];
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDARY_MULTIPART_IMAGE] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"product_photo\"; filename=\"%d.jpg\"\r\n", i] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imgData]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}

// close form
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BOUNDARY_MULTIPART_IMAGE] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the request
[theRequest setHTTPBody:body];
return theRequest;

Please let me know if anyone has the solution for this one ..
Thanks,
Nilesh M. Prajapati

A: Sorry everyone,
But i got the solution. Actually, I have to set dynamic filename in below lines.. I have to set "product_photo" as a dynamic string having random number like "product_photo1" or "product_photo2", etc..
for (int i=0; i<[arrImgs count]; i++)
{
   UIImage* image = [arrImgs objectAtIndex:i];
   NSData *imgData = UIImagePNGRepresentation(image);
   [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BOUNDARY_MULTIPART_IMAGE] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"product_photo%d\"; filename=\"%d.png\"\r\n", i,i] dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
   [body appendData:imgData];
   [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}


text:
Q: Squid: cache hits and requests I've been monitoring Squid using MRTG, and for some reason, I get, from time to time, significantly more http cache hits then requests.
Can this be explained? Do cache hits not count as a simple http request? I would guess requests should be the total of hit + miss ?
I'm using snmp to monitor this.
Cheers

A: Is it possible there is confusion with the variable name? It is worth noting that you should be comparing cacheHttpHits and cacheProtoClientHttpRequests, not cacheServerRequests which is something else entirely.

A: You are right, http requests turn into either hits or misses. You could find other kind of hits (related to HTTP requests, ICP messages between caches, the IP cache, etc.). I would suggest to use squidclient command to go deeper into internal squid statistics and understand what is really happening on squid (further than what you see from MRTG).
e.g: squidclient -h host -p 80 mgr:utilization


text:
Q: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8192 bytes) Error in php even though i gave 1024MB size in php.ini apologies in advance if answer exist already but i cant seem to find the solution
all i want is to convert csv into array and i cant seem to get rid of error no matter how much memory i provide
if (($handle =fopen('price.csv', 'r')) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $array[]=$data;
    }
    fclose($handle);
}
echo count($array);

csv file is around 3MB with around 1100 lines
how do i remove this error i tried allocating memory of 1024MB even .

A: Please try this in PHP before your Code:
ini_set('memory_limit', '2048M');

You can try whats required it's never a goof idea to modify this value in php.ini, because other PHP processes could eat up your memory.


text:
Q: Whether to use Integer/Float/Double for Calculation of price & discount I am a beginner in android. I am developing a Sales related app in which I need to do lots of calculations.
I am confused which Variables to use for processing Prices, Discounts etc.
Currently I am storing Price as INTEGER.
E.g. 180 Rs ---> 18000 Paise & while Showing I simple divide it by 100.
But I want to show price/discounts upto 2 decimal places like 150.50 Rs or 20.50Rs.
What should I use? A float Or A Double or Anything else?
Please help me out... Thanks...

A: Use integers as you are doing to make calculations on your prices: you'll avoid problems with rounding. Just divide by 100 when you want to convert to real prices. And use a java.text.NumberFormat each time you want to show the price: you'll control the exact number of decimals it'll print.


text:
Q: Can $e^{-1/zw}$ be written as a difference of holomorphic functions? I'm the teaching assistant for an undergraduate complex analysis course at my current university. I was reviewing some old prep materials to try and find some good practice problems to give to my students, and happened on the following:

Consider $\Bbb C^2$ with coordinates $z,w$. Can the function $f=e^{-1/zw}$ be written as a difference of two functions $g,h$, where $g$ is holomorphic away from $z=0$ and $h$ is holomorphic away from $w=0$? Explain your answer.

This was at the end of some final exam prep and was marked with a (*) to indicate it was supposed to be challenging. (This was also set by a professor who has since been hired away from my institution and was known for making some, uh, difficult exams.) I'm interested in finding a good solution.
The best I've been able to do so far is that if $g$ and $h$ were globally represented by power series, allowing for negative exponents for $z$ in $g$ and negative exponents in $h$, then by looking at negative-degree terms in $z$ and $w$ we ought to reach a contradiction: $\frac{1}{zw}$ cannot be represented as a sum of elements of the form $\frac{p(z,w)}{z^n}$ and $\frac{q(z,w)}{w^n}$, which should lead to what we need. But this argument feels untrustworthy - I know that if a function of one variable is entire on $\Bbb C$, I can find a global power series for it, but I'm deeply unsure about generalizing that to something like $\Bbb C\times\Bbb C^\times$, and it feels like I'm not really taking full advantage of how bad the singularities of $e^{-1/zw}$ are near $zw=0$. Can you help?

A: What you could do is to consider doing $\int_{z \in C} \int_{w \in C} u(z,w) \, dw \, dz$ to everything, where $C$ is the curve going counterclockwise one time around the origin.  If you plug in $u(z,w) = e^{-1/zw}$ you get $4\pi$, and if you plug in for $u(z,w)$ a function that is either holomorphic for $z \ne 0$ or holomorphic for $w \ne 0$, you get $0$.

A: I strongly suspect that if this is for an undergraduate course, "holomorphic" means "holomorphic function in one variable".
My guess is they are asking whether it is possible for $\exp{(\frac{1}{zw})}$ to be written as $f(z)+g(w)$, where both $f$ and $g$ are holomorphic except at $0$.
This question is, of course, a lot easier. Suppose there were such an example of $f,g$. Then immediately $(f-g)$ is a constant function and $2f(z)=\exp{(\frac{1}{z^2})}+C$, which doesn't work.
$\\$
If $f$ and $g$ are each meant to be holomorphic in two variables... yes, the answer to that question just pops out if you compare the Laurent series for $f$, $g$ and $\exp{(\frac{1}{zw})}$.
(See Section 2.7 of https://staff.fnwi.uva.nl/j.j.o.o.wiegerinck/edu/scv/scv1.pdf)
But this is far, far beyond any undergraduate syllabus.


text:
Q: Launching new activity resets ViewPager I have a ViewPager with each view being a WebView.  In the Actionbar I have a menu item, where the user can open the web page in their default browser using this code:
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl)));

However, if a user clicks on a link in the WebView, then opens the site in their default browser, then goes back to my app, they are shown the original web page, not the page they clicked to.  I thought about using startActivityForResult instead of startActivity, but that would only work if I opened a new activity in my own app, right?
This is the code for my ViewPager:
Fragment
public class Browser extends SherlockFragment {
    private String mUrl;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        activity = getActivity();

        setHasOptionsMenu(true);

        mUrl = GetUrl();

        mWebView = (WebView)getView().findViewById(R.id.webview);
        mWebView.loadUrl(mUrl);

        mWebView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {

            }

             @Override
             public boolean shouldOverrideUrlLoading(WebView view, String url) {
                  view.loadUrl(url);

                 return true;
             }
        });
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item)
    {
        if (item.getItemId() == R.id.open) {
                this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl)));
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

}

Activity
public class BrowserPager extends SherlockFragmentActivity implements Interfaces.OnBrowserSetTitle {

    @Override
    public void onCreate(final Bundle icicle)
    {
        super.onCreate(icicle);

        setContentView(R.layout.browser_pager);
    }
}

A: Nevermind, I'm an idiot.  I was resetting the ViewPager in onResume of the Activity, which was causing the webpage to reset.  Moving the code to reset the ViewPager to onCreate fixed my issue.


text:
Q: A way of median optimization (instead of mean) for skewed distribution in machine learning Let say I do the regression task(I am using the deep neural network) for some skewed distribution. Now I am using mean absolute error as loss function.
All typical approaches in machine learning are minimizing mean loss, but for skewed that is unappropriating. It is better from a practical point of view to minimize median loss. I think one way is to penalize big losses with some coefficient. And then mean will be close to the median. But how to calculate that coef for the unknown distribution type? What can you to advice?

A: The weighted penalty you are thinking of is the idea behind Quantile Regression:
https://en.wikipedia.org/wiki/Quantile_regression