text:
Q: Comparing regression coefficients of different regions I have to regress the average length of stay in a hospital $(Y)$ against infection risk $(X)$ for hospitals in four different regions with a linear regression model. With the lm function in R, I have found the regression coefficients for each of the regions but now they ask to check if the regression lines have the same coefficients. So I now constructed a model that makes a linear regression model for all the regions by using the following code in R:
combinedRegions.model  <-   lm(Stay ~ Region2Boolean + Region3Boolean
                            + Region4Boolean +  Infection + Infection:Region2Boolean + Infection:Region3Boolean + Infection:Region4Boolean, data = Data)

If I now want to check if the regression lines of the different regions have the same slopes, is it good to construct the following model
sameSlopes.model <- lm(Stay ~ Infection + Region2Boolean
                    + Region3Boolean + Region4Boolean, data= Data)

and then perform an anova test on these models?


text:
Q: What is meant by saying that events happened before we started listening to them? While reading for Javascript Promises, I have come across few blogs/articles where the Promise implementation is first compared with the Javascript Event model and then the callback pattern.
While comparing with the Event model, it is commonly mentioned that 'it's possible that the events happened before we started listening for them' OR 'you need to ensure that all appropriate event handlers are added before the first time an event occurs'
I'm trying to wrap my head around this and I'm not quite sure howz that possible from code standpoint. How can an event occur before we add the handlers ? Can anyone provide concrete examples to explain this ?

A: They mean pretty much what they literally said: The event occurred before we started listening for it. For instance, suppose we show a button, but there's a delay of two seconds before we add an event handler listening for clicks on that button. If the user clicks within those two seconds, the event occurs before we were listening for it.
Example:

function run() {
  // Show a button
  document.getElementById("btn").style.display = "inline";

  // Wait two seconds before we hook up a handler
  setTimeout(function() {
    document.getElementById("btn").addEventListener("click", function() {
      console.log("Got a click");
    }, false);
  }, 2000);

  // If the user clicks within those two seconds, the event happened
  // before we were listening for it.
}

// This is just stuff to make sure the user is ready before showing the button
var counter = 4;
tick();

function tick() {
  if (counter == 0) {
    document.getElementById("get-ready").style.display = "none";
    run();
  } else {
    document.getElementById("countdown").innerHTML = counter--;
    setTimeout(tick, 1000);
  }
}

Get ready, a button will appear in , click it as soon as it appears, then again a couple of seconds later:

<input style="display: none" type="button" id="btn" value="Click me as soon as I appear, and again a couple of seconds later">

What I was looking for was some generic cases where events are fired before we attach listeners.

Well, the above is quite generic: Consider the usual practice of putting your JavaScript in a script tag at the end of the document body, just before the closing  tag, or using the async or defer attributes on it. That means there is a brief period of time when any buttons on the page can be clicked, but we haven't hooked up handlers on them yet. If there's a temporary network glitch, for instance, and it takes two seconds instead of the usual ~65ms to load your JavaScript file, your users would click the button (trigger the event) before you hooked your handler (were listening for it).
Alternately, this used to be a good example, but no longer happens on modern browsers as far as I can tell Kaiido says it still does on WebKit browsers, although I couldn't make it happen on iOS Safari: Adding an img to a document and expecting to get the load event from code like this:
var img = document.createElement("img");
img.src = "path/to/the/image.png";
img.addEventListener("load", function() {
    // Handle the fact it loaded
}, false);
img.addEventListener("error", function() {
    // Handle the fact it failed
}, false);
someOtherElement.appendChild(img);

On the surface, it looks like there's no race condition there because of JavaScript's run-to-completion semantics and the fact that by default our JavaScript code runs on a single UI thread. But there is a race condition there, because while our code will follow a single thread, the browser is not single-threaded. So this can happen:

*

*img.src = "path/to/the/image.png";.

*The browser's resource management code goes looking for the image.

*Resource management finds it in cache and doesn't need to re-verify, so associates the image data with the element and triggers the load event.

*The event system goes to queue tasks for callbacks to any load event handlers that are present on the element, doesn't find any, and doesn't queue any tasks.

*We attach our handlers and append the element.

*Our code runs to completion.

*We never get either a load or error event callback.

In contrast, if we hook first and then set src:
var img = document.createElement("img");
img.addEventListener("load", function() {
    // Handle the fact it loaded
}, false);
img.addEventListener("error", function() {
    // Handle the fact it failed
}, false);
img.src = "path/to/the/image.png";          // <=== Moved
someOtherElement.appendChild(img);

Then the same scenario plays out like this:

*

*We attach our handlers.

*img.src = "path/to/the/image.png";.

*The browser's resource management code goes looking for the image.

*Resource management finds it in cache and doesn't need to re-verify, so associates the image data with the element and triggers the load event.

*The event system goes to queue tasks for callbacks to any load event handlers that are present on the element. It finds one, so it queues a task to call it when the task queue is next empty.

*We append the element.

*Our code runs to completion.

*The task loop picks up the next task from the queue, which happens to be our load callback.

*The task loop calls our callback.

Now, it happens that this behavior was sufficiently irksome that modern browsers don't do it anymore (although Kaiido says it still does on WebKit, I can't confirm that). Although I still code as though it does (the second example), because it could, it's a valid way for the browser to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Official PHP:Apache Docker Image - Getting MySql Plugins to Work I am using the official docker php:apache image but I can't use mysqli with php.
I get 'Class "mysqli" not found' whenever I try this:
$conn = new mysqli($servername, $username, $password, $dbname);

I see a ton of stuff everywhere talking about adding an install for mysqli to the dockerfile.
I am really not sure if this is necessary for a few reasons:
When I open bash on my container, I see that mysqlnd is installed as a php module.
Here's the snippet from my docker-compose.yml:
lamp-www:
  depends_on:
  - db
  image: php:apache
  volumes:
  - "./www:/var/www/html"
  ports:
  - 8080:80

When I do a PhpInfo(), I see "--enable-mysqlnd" and I see a mysqlnd section.
It states version name: "mysqlnd 8.0.10".
I haven't seen anything indicating that the syntax is different between the old mysqli and mysqlnd, it suggests it's the same. I've tried using "mysqlnd" and "mysql" instead, but they all generate the same error as "mysqli".
I also am not seeing anything that indicates you can use a DockerFile when using "image: php:apache". I also don't want to go into my container to install or change things, and re-commit, I'd like use the official image.
Can I make a DockerFile when I use the "image" parameter in my docker-compose.yml?
Is there a cleaner way to do this, like just adding a parameter to my compose that installs whatever mysterious thing I'm missing?
Final question: This is the official php image, and the installed modules seem to indicate that  mysql is supported from php. Am I just trying to use functions/classes that aren't recommended? If so, what should I be using instead?

A: According to the docs here, it says:

What it is not
Although MySQL Native Driver is written as a PHP extension, it is
important to note that it does not provide a new API to the PHP
programmer. The programmer APIs for MySQL database connectivity are
provided by the MySQL extension, mysqli and PDO MYSQL. These
extensions can now use the services of MySQL Native Driver to
communicate with the MySQL Server. Therefore, you should not think of
MySQL Native Driver as an API.

Basically, mysqlnd is in a layer below mysqli or pdo_mysql, it does not add functions/classes in PHP for you to connect to a MySql db.
This can be checked running a few commands (I'm assuming a flavor of Linux or WSL):
docker pull php:apache                 #downloading the official image
docker run --rm -it php:apache bash    #and running it in a temporal container

once inside the container:
php -m     #checking the modules for php
php -a     #executing a php interactive console

(note that in the output of php -m, mysqlnd is present but mysqli or pdo_mysql are not)
then, run these lines inside the php console:
$conn = new mysqli('localhost', 'root', 'pass', 'db');              //connecting to a MySql db with mysqli
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); //and the same with pdo_mysql

Both lines will throw an error:
Warning: Uncaught Error: Class "mysqli" not found in php shell code:1     //mysqli
Warning: Uncaught PDOException: could not find driver in php shell code:1 //pdo_mysql

Even in standard installations of php in the wild, neither mysqli nor pdo_mysql are bundled by default, because you may want to use other databases (PostgreSQL, SQLite, Oracle, etc...) or none at all, so you need to install the specific driver for your db.
Installing a MySQL driver with a Dockerfile
Q: Which one should you use, mysqli or pdo_mysql?
A: Nope, i'm not touching this one, go with the one you personally feel most comfortable with. This question is on par with "tabs or spaces?", "vi, vim or emacs?", "pineapple on pizza?", "Were Ross and Rachel on a break?" or "Was The Dress blue and black or white and gold?" in terms of divisiveness, both have their pros and cons, and there are no wrong answers (unless you put pineapple on a pizza, seriously, what's is wrong with you?).
To install any, or both drivers you need to create a Dockerfile that creates a new image with php and the drivers ready to use. You don't need to start from scratch or go into the container everytime you run it, since you can base your image on the official one and extend it.
There are instructions to do so in the readme of the official image, where they mention the helper commands inside the image, but i already did the legwork:
#this uses the official image as a starting point
FROM php:apache

#humblebrag
MAINTAINER gorchestopher-h

#install both modules from source, you can delete the one you aren't using
RUN docker-php-ext-install mysqli pdo_mysql

that's it! now you have a Dockerfile that you need to save in a file with the name Dockerfile (no extension) preferably in a directory right next to your docker-compose.yml file, please.
Now that you have this file, you could execute the docker build command and create it, but since you're using docker-compose, you're already a few steps ahead with automatization, so you only need to edit your compose file and the first time you run docker-compose up with the new configuration it will do the job for you.
But here's the catch, the way the image key works is:

If the image does not exist, Compose attempts to pull it, unless you
have also specified build, in which case it builds it using the
specified options and tags it with the specified tag.

So, that means we can set the build key inside the the compose file to build our Dockerfile. But! it needs to have an unique name so it doesn't get confused with the already existing php:apache image in your system and the official repository.
This can be done using both image and build keys:
lamp-www:
  depends_on:
      - db
  image: gorchestopher-h/php-mysql:apache           #the resulting image gets named this
  build: ./name-of-the-directory-next-to-the-yml    #where to find the Dockerfile file
  volumes:
      - "./www:/var/www/html"
  ports:
      - 8080:80

And that's it, now the first time you docker-compose up this compose file, the image gets built since it can't be found, and if you modify the Dockerfile and spin it up again. It does nothing since the image already exists, you need to execute docker-compose build lamp-www (the name of the service is optional, if you skip it, it builds every build key) to recreate it, and also docker image prune after you spin up the new image to free the unused old one.
To check that everything went well, you can repeat the commands from before.
docker run --rm -it gorchestopher-h/php-mysql:apache bash #run the container with the awesome new name

inside the container you can run
php -m #check the installed modules, it should have mysqli and/or pdo_mysql
php -a #executes a php terminal

and on the php terminal you can test the connection again
$conn = new mysqli('localhost', 'root', 'pass', 'db');              //connecting to a MySql db with mysqli
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); //and the same with pdo_mysql


text:
Q: unassigned expression in function I am going through 'Python Cookbook' by Beazley and Jones and I came across the following code:
# Token processing functions
def t_NUM(t):
 r'\d+'
 t.value = int(t.value)
 return t

What I don't understand is what the purpose of r'\d+' is. The above example is part of a larger code which I don't expect anyone to dig into. So, consider the following MRE:
def func():
    1

This appears to be a legal function, even though 1 is not assigned. What, then, is the point of such syntax/statements inside a function?

A:
What I don't understand is what the purpose of r'\d+' is.

As others have mentioned, generally speaking it's a docstring, the string gets attached to the function object and can be displayed by tools like pydoc/help, or documentation systems like Sphinx.
As the name indicates, it's a documentation string, the content would usually be an explanation of the purpose and interface (input / output / exceptions) of the function e.g. this example from the standard library.
Docstrings can be define as the first statement of a class or function, at the top of a module (the rules for these are a bit more complicated), or right after some assignments ("attribute docstrings"), though most tools have trouble with the last one.
However in this specific case

The above example is part of a larger code [...]

is extremely relevant: this is a parser example using  ply, which leverages the docstring as a tokenization pattern.

When a function is used [nb: tp specify a token], the regular expression rule is specified in the function documentation string. The function always takes a single argument which is an instance of LexToken.

So for this specific Cookbook snippet the purpose of r'\d+' is not documentation but to define what kind of input is considered a NUM token.


text:
Q: explain plan meanings in mysql i use explain plan,but i am confused what is its real meaning.
explain extended
select *
from (select type_id from con_consult_type cct
      where cct.consult_id = (select id
                              from con_consult
                              where id = 1))
      cctt left join con_type ct on cctt.type_id = ct.id;

the results is

i google the derived is temporary table,but what is its sql of the temporary table?is ctt table?
and the step 2,is result of cctt left join con_type ct on cctt.type_id = ct.id?
the FK_CONSULT_TO_CONSULT_TYPE is consult_id refer con_consult id column,
how to use the index in the sql?
get all results of ctt,and then use the index filter?
please help me explain what the explain meanings.

A: This is a bad query to learn the basics of the explain output, there is simply too much happening with all the sub queries, and joins.
I can give a run down of some of the essentials;

*

*'rows' column: Less is better, it shows how many rows had to be scanned by the database, anything less than a couple of hundred is good, generally indicates how well it is able to find your data from the indexes;

*'possible_keys': and 'keys': If 'rows' is big, you may have to tweek your keys to provide the engine with some help finding your data

*'type': Type of join

To answer some of your questions;

*

*'sql of the temporary table' - it's the first subquery in your sql

*With FK_CONSULT_TO_CONSULT_TYPE you dont have to do anything, the engine has allready picked this up as an index which is what the explain is saying.

*Queries are broken into 3 essentials steps; select data, filter, and join. Each row in the explain is a detail into one or more of these operations, it may not necessarily relate to a specific section of your SQL as the engine may have combined various parts into one.


text:
Q: Get process parameters form afterProcessStarted API of ProcessEventListener I have a code, where I am inserting some parameters within the process(Jbpm) and then starting the process and also I am adding an EventListener(which extends DefaultProcessEventListener) to the knowledge session
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

Map<String, Object> input = new HashMap<String, Object>();
input.put("payload", payloadObject);
input.put("caseNo", caseNoString);

EventListner listner = new EventListner();
ksession.addEventListener(listner);
ksession.startProcess(strategyName,input);

Now I want the input map within the Listner class
public class EventListner extends DefaultProcessEventListener{

@Override
public void afterProcessStarted(ProcessStartedEvent startEvent) {
    //NEEDED HERE
}

@Override
public void afterProcessCompleted(ProcessCompletedEvent arg0) {
    //NEEDED HERE
}

How...??? Need help

A: I just happened to be working on this same problem. Here is my code that I got working
public void afterNodeLeft(ProcessNodeLeftEvent event) {
    RuleFlowProcessInstance rfpi = (RuleFlowProcessInstance)event.getProcessInstance();
    RuleFlowProcess rfp = rfpi.getRuleFlowProcess();
    VariableScope scope = rfp.getVariableScope();
    for(Variable var : scope.getVariables()) {
        Object obj = rfpi.getVariable(var.getName());
        String value = null;
        if (obj != null) {
            value = obj.toString();
        }
        System.out.printf("\tVariable name: %s, Value: %s%n",var.getName(),value);
    }
}

I found that if you try to access the variables directly through process the result is always null. Accessing process variables through the ProcessInstance appears to work.


text:
Q: How to use 0 as an identifier for a workspace in awesome wm? Is it possible to use 0 as an identifier for a workspace in awesome wm? By default it only allows the numbers from 1 to 9. I would like to switch to the workspace just like any other (e.g. mod + 0).
Ideally it would be added after the 9th workspace and not appended to the front.

A: Assuming you are coming from the default rc.lua search for something like this in it and let the for loop run until 10 instead of 9.
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it work on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do

You have set up the key bindings, now create an additional tag. Somewhere you can find something like this. Add a "0" to the list.
awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9"}, s, awful.layout.layouts[1])


text:
Q: Response time benchmarks for Salesforce APIs For all the various APIs exposed by Salesforce like Bulk, Composite etc. each have their own developer guides which include like how to use them, and various limits applicable to them.
But I didn't find any published response time benchmarks. For eg: in Bulk API, if Insert operation is performed for Contact object, for an batch size of XXXX (with say XX fields) what is the average/least time taken for batch to complete.
Help out if I have missed discovering the right documentation.

A: There's no way to know, because (a) customizations can increase the time, and (b) system load does have some impact.
The minimal amount of time for a pristine org is about 1ms per record (1/1,000th of a second), and can easily be over 10,000ms per record.
If you're really curious, try a load late at night and one at noon. That should give you theoretical minimums and maximums for your org.


text:
Q: Sending intents from receiver to service with a delay I have a Receiver for BOOT_COMPLETED intent and it will start a Service by calling startService with an intent and the Service processes that intent in onStartCommand function by spawning a thread that does a HTTP post to a server.
On powerup, sometimes it takes 3 to 5 seconds to get the active data connection on phone, when this happens Service fails to do HTTP post as there is no data connection. Is it possible for the Receiver to send the intent to Service using startService with a delay.? so that when onStartCommand of Service is called data connection is ready to post data.

A: Can't you use an asynctask to do the HTTP request and then maybe catch an exception within the asynctask to check for a timeout exception?
If the asynctask times out then return gracefully and make your service spawn a new asynctask until you get a connection?

A: Before doing any data communication, make a loop which will poll Android's TelephonyManager.getDataState() with exponential backoff to not use up too much CPU or waste the user's battery. Keep trying until you get the DATA_CONNECTED flag, or until you reach some sort of timeout to stop trying.


text:
Q: How to control ggplot's plotting area proportions instead of fitting them to devices in R? By default, each plot in ggplot fits its device.
That's not always desirable. For instance, one may need to make tiles in geom_tile to be squares. Once you change the device or change the number of elements on x/y-axis, the tiles are no longer squares.
Is it possible to set hard proportions or size for a plot and fit the plot in its device's window (or make the device width and height proportional to those of the plot)?

A: Here's an easy device to treat your plot with respect,
library(ggplot2)
p = qplot(1:10, (1:10)^3)
g = ggplotGrob(p)
g$respect = TRUE
library(grid)
grid.draw(g)

A: You can specify the aspect ratio of your plots using coord_fixed().
> library(ggplot2)
> df <- data.frame(
+     x = runif(100, 0, 5),
+     y = runif(100, 0, 5))

If we just go ahead and plot these data then we get a plot which conforms to the dimensions of the output device.
> ggplot(df, aes(x=x, y=y)) + geom_point()

If, however, we use coord_fixed() then we get a plot with fixed aspect ratio (which, by default has x- and y-axes of same length). The size of the plot will be determined by the shortest dimension of the output device.
> ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed()

Finally, we can adjust the fixed aspect ratio by specifying an argument to coord_fixed(), where the argument is the ratio of the length of the y-axis to the length of the x-axis. So, to get a plot that is twice as tall as it is wide, we would use:
> ggplot(df, aes(x=x, y=y)) + geom_point() + coord_fixed(2)

A: A cleaner way is to use the theme(aspect.ratio) argument e.g.
library(ggplot2)
d <- data.frame(x=rnorm(100),y=rnorm(100)*1000)
ggplot(d,aes(x,y))+
geom_point() +
theme(aspect.ratio=1/10) #Long and skinny

coord_fixed() sets the ratio of x/y coordinates, which isn't always the same thing (e.g. in this case, where the units of x and y are very different.


text:
Q: CodePipeline unable to locate SAM template yaml file I'm attempting to setup AWS Codepipeline with a Cloudformation SAM stack that deploys to a Lambda and am doing this via the Pipeline console.  The pipeline passes the clone from Codecommit process and the build process with Codebuild, however fails on the deploy with Cloudformation.
I get the following error message:
Action execution failed
Invalid TemplatePath: MyAppBuild::samTemplate.yml
I've been following the documentation (http://docs.aws.amazon.com/lambda/latest/dg/automating-deployment.html) pretty closely and in field 16 of the codepipeline setup form (Template File) I have been putting samTemplate.yml.
I also have samTemplate.yml in the root of my repo (which is also the root of the project).
I've matched the Codebuild output artifact name with the Cloudformation input artifact name and they match exactly.
Am I missing something here?  How do I get the Cloudformation deploy process to recognize the sam template?
EDIT 1 I've switched to using Codestar instead of directly using CodePipeline.  Nothing special in my buildspec.yml, but it's below if anyone's interested.
version: 0.2

phases:
  install:
    commands:
      - echo "install"
  pre_build:
    commands:
      - echo "pre_build"
  build:
    commands:
      - aws cloudformation package --template template.yml --s3-bucket $S3_BUCKET --output-template template-export.json
artifacts:
  type: zip
  files:
    - template-export.json

One thing to keep in mind for anyone new to CodeBuild, the zip file that gets created as a result is of the root level directory of your build operations and IS the zip file that gets transferred to final deployment (in my case, Lambda).

A: You need to add aws cloudformation package command in you buildspec.yml.
 aws cloudformation package --debug --template-file <YourSamTemplate.yml> --s3-bucket <YourbucketName> --output-template-file <YourOutputSamTemplate.yml>

where YourSamTemplate.yml is the name of samTemplate.yml in your project root.
and YourOutputSamTemplate.yml is the new name which you eant to give your output file after cloud formation package command is done.
Then in the next stage you need to define your input-artifact as output of your aws codebuild stage and then use this input-artifact to map your template.
build-output::YourOutputSamTemplate.yml

A: I believe the output of the build stage is what needs to be passed into the CloudFormation action.
In the tutorial the build output is called NewSamTemplate.yaml
So try updating your TemplatePath to MyAppBuild::NewSamTemplate.yml

A: In my case, the error was in the filename. Instead of template.yml the actual file was template.yaml


text:
Q: Hide add to cart button based on custom field value - woocommerce In content-product.php, products from the current category page have a "add to cart"-button if the item has a price.
I want to remove this button, BUT only on the items that returns true on the if statement around it.
I tried:
$showBuyButtonNo = get_field('show_buy_button');
    if ($showBuyButtonNo) {
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }

BUT this does it to all items.

A: add_action( 'woocommerce_after_shop_loop_item', 'remove_add_to_cart_buttons', 1 );

function remove_add_to_cart_buttons() {
  // replace a_category and another_category with the slugs of the categories you'd like to have the button removed from
  if( is_product_category( array( 'a_category', 'another_category'))) {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
  }
}

Reference: https://www.wpblog.com/add-to-cart-button-in-woocommerce-store/
Reference: https://gist.github.com/rynaldos/560c621714b9680433cddf18e6a50305

A: You can update default WooCommerce content-product.php as below:


text:
Q: PowerShell: Using Microsoft Windows 10 Built-in OCR (Windows.Media.Ocr.dll) with Inline CSharp While I've found 2 ways to use Win10's OCR in PowerShell, the issue is that I want to process the list BoundingRect provided by OcrLine.Words, and C# seems consistently 3 times faster than PowerShell.  Now I could do the OCR in PowerShell and call C# to process the BoundingRects, but it just seems like it would be a lot cleaner to do both in C#.
But every attempt to reference the Windows.Media.Ocr assembly has failed to even find the assembly, with the exception of the following code - which complains it can't open it.
$OCRDLL = (Get-Command -Name "Windows.Media.Ocr.DLL" -CommandType 'Application' -ErrorAction SilentlyContinue).Source
if($OCRDLL) {
    $Assemblies = ($OCRDLL)
    Add-Type -ReferencedAssemblies $Assemblies -Language CSharp @"
using Windows.Media.Ocr;

public static class OCR {
    public static async string RecognizeOCR(string fullFilePath) {
        var ocrEngine = Windows.Media.Ocr.OcrEngine.TryCreateFromLanguage(new Windows.Globalization.Language("en"));
    }
}
"@
    $Temp = [OCR]::RecognizeOCR( "$PSScriptRoot\20000111-p001.jpg")
    $Temp
}

Error:
Add-Type : (0) : Metadata file 'c:\Windows\System32\Windows.Media.Ocr.dll' could not be
    opened -- 'An attempt was made to load a program with an incorrect format.
    'd -- 'An attempt was made to load a program with an incorrect format. '

I guess I need someone to either tell me how it's done, or to tell me it can't be done.
Thank you for any help you can provide!


text:
Q: how to use harvard (authoryear) style to format citation call-outs The paper is required to format citation call-outs with the harvard style (aka authoryear style) like:

The content of my *.tex file is like this:
 ...
 \usepackage{natbib,stfloats}
 \begin{document}%

 \citet{ananthanarayanan2011scarlett} create more replicas for hot files
 to simplify the scheduling decision-making. EC (erasure
 coding) to alleviate the low storage efficiency of multi-replicas in
 HDFS~\citep{sathiamoorthy2013xoring, subedi2015finger, xia2015tale}. The
 benefits of data prefetching have been widely
 discussed~\citep{prajapati2014locality,chen2012data}.

 \bibliographystyle{agsm}
 % \bibliographystyle{abbrvnat}
 % \setcitestyle{authoryear,open={(},close={)}}
 \bibliography{refs}
 \end{document}

The final result is not as I want. The problems are:

*

*for two authors the format is not (A and B, year) but (A & B year)

*for three or more authors is not (A et al., year) but ( A et al. year)

*groups of call-outs should be listed first alphabetically and then chronologically, but the formatted result is  (Zaharia et al. 2008, Magalhães et al. 2015), not first alphabetically, and call-outs are not separated by ';'.
An example shows the formatted result:

I then turned to set the bibliography style to abbrvnat:
  \bibliographystyle{abbrvnat}
  \setcitestyle{authoryear,open={(},close={)}}

The formatted result changes to:

But it still has the first alphabetically problem, and it induces another problem that the call-outs are not surrounded by "()" but by "[]".
Can someone help me out of this problem? Is the problem of the cite command or the configuration of bst, so can anyone can give an short cite and config example to format paper as required. thank you!

A: For the approach with the abbrvnat bibliography style, try issuing the instruction
\setcitestyle{authoryear,round,semicolon}

after loading natbib. Thus, omit the open={(},close={)} part. By the way, whenever one makes changes to the argument of \setcitestyle, one should recompile the document fully -- LaTeX, BibTeX, and LaTeX twice more -- to propagate all changes.
As far as I can tell, both the natbib and the harvard citation management packages order the formatted citation call-outs in the ordering provided in the input (\citep and \citet). Thus, I'm afraid it's up to you to list the arguments of \citep in the desired ordering.


text:
Q: How to generate code when compiling Is there any way to generate code when compiling.
For example:
I write an Activity
public class XXActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        doSomething();
    }

    private void doSomething() {

    }
}

I want to log the time before and after method doSomething():
public class XXActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        Log.i("XX", "start:" + System.currentTimeMillis()); // auto generate when compiling
        doSomething();
        Log.i("XX", "finish:" + System.currentTimeMillis()); // auto generate when compiling
    }

    private void doSomething() {

    }
}

How to achieve the effect like example above, any idea is appreciated.

A: You should create custom annotation. For beginning take look at this tutorial:
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   StringBuilder builder = new StringBuilder()
           .append("package com.stablekernel.annotationprocessor.generated;nn")
           .append("public class GeneratedClass {nn") // open class
           .append("tpublic String getMessage() {n") // open method
           .append("ttreturn "");

   // for each javax.lang.model.element.Element annotated with the CustomAnnotation
   for (Element element : roundEnv.getElementsAnnotatedWith(CustomAnnotation.class)) {
       String objectType = element.getSimpleName().toString();

       // this is appending to the return statement
       builder.append(objectType).append(" says hello!\n");
   }

   builder.append("";n") // end return
           .append("t}n") // close method
           .append("}n"); // close class

   try { // write the file
       JavaFileObject source = processingEnv.getFiler().createSourceFile("com.stablekernel.annotationprocessor.generated.GeneratedClass");

       Writer writer = source.openWriter();
       writer.write(builder.toString());
       writer.flush();
       writer.close();
   } catch (IOException e) {
       // Note: calling e.printStackTrace() will print IO errors
       // that occur from the file already existing after its first run, this is normal
   }

   return true;
}


text:
Q: Set up unit testing with Mocha on an AngularJs app I'm trying to setup unit testing on my webapp using mocha. My webapp uses AngularJs and since I'm still new to this framework, I'm having a hard time to setup this.
In fact, is there a way to setup this by using nothing else than mocha? I mean, is it possible to setup my unit tests without Karma or any other test runners (and no browser)?
Here's my code to test :
define(['angular'], function (angular) {
var module = angular.module('MyModule', []);

module.controller('MyController', ['$scope', '$window', function ($scope, $window) {
        $scope.test = function () {
            $window.alert('Not implemented yet.');
        };
    }]);

    return module;
});

And here's my test code:
require("chai");
require('../lib/angular/angular-mocks');

describe("Unit testing example", function() {

    beforeEach(angular.mock.module('MyModule'));

    it('should test nothing', function() {
        expect(true).to.be.true;
    })

});

When I try to execute this, I receive this error:
angular.mock = {};
^
ReferenceError: angular is not defined

Thank you for your help!

A: Yes, you need something that will provide some sort of browser environment for your Angular code. There are multiple options:

*

*jsdom.

*Headless solutions like PhantomJS.

*Actual browsers.
Each of these solutions provide a browser environment which is progressively closer to the "real thing".
What you need exactly depends on:

*

*That minimum AngularJS requires. I don't use AngularJS so I don't know what this minimum is.

*What minimum your own code requires.
For instance, I've used jsdom for unit tests for code that just navigates up and down the DOM tree. Jsdom was perfect for this. However, when I tried to use jsdom to test code that uses MutationObserver, that did not work because jsdom does not provide this API. I've had to use real browsers to perform these tests.
A word of caution: if you care at all about cross-browser compatibility nothing replaces testing code against actual browsers. Just yesterday I diagnosed a problem that happened only in Safari. There was no way to catch this problem using anything else than Safari to test the offending code.

A: For those facing this issue with jsdom for testing
Adding the following solve it for me seach for a day
require('mutationobserver-shim')
global.MutationObserver = global.window.MutationObserver

of course you need to npm yarn install mutationobserver-shim
Hope this helps


text:
Q: Check strings equality without direction? I'm trying to compare two strings, while on one of them I'm doing some bidi manipulation:
const a = "\u202B" + "hi" + "\u202C"

console.log(a === 'hi') // false
console.log(a == 'hi') // false

The output on the screen will look the same while it's actually not. Is there a way to check for equality while not taking bidi into account (so the result of the equality check above will return true)?


text:
Q: Spring MVC type conversion : PropertyEditor or Converter? I am looking for the easiest and simplest way to bind and convert data in Spring MVC. If possible, without doing any xml configuration.
So far I've been using PropertyEditors like so :
public class CategoryEditor extends PropertyEditorSupport {

    // Converts a String to a Category (when submitting form)
    @Override
    public void setAsText(String text) {
        Category c = new Category(text);
        this.setValue(c);
    }

    // Converts a Category to a String (when displaying form)
    @Override
    public String getAsText() {
        Category c = (Category) this.getValue();
        return c.getName();
    }

}

and
...
public class MyController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Category.class, new CategoryEditor());
    }

    ...

}

It is simple : both conversion are defined in the same class, and the binding is straightforward. If I wanted to do a general binding across all my controllers, I could still add 3 lines in my xml config.

But Spring 3.x introduced a new way to do it, using Converters :

Within a Spring container, this system can be used as an alternative
  to PropertyEditors

So let's say I want to use Converters because it is "the latest alternative". I would have to create two converters :
public class StringToCategory implements Converter<String, Category> {

    @Override
    public Category convert(String source) {
        Category c = new Category(source);
        return c;
    }

}

public class CategoryToString implements Converter<Category, String> {

    @Override
    public String convert(Category source) {
        return source.getName();
    }

}

First drawback : I have to make two classes. Benefit : no need to cast thanks to genericity.
Then, how do I simply data bind the converters ?
Second drawback : I haven't found any simple way (annotations or other programmatic facilities) to do it in a controller : nothing like someSpringObject.registerCustomConverter(...);.
The only ways I've found would be tedious, not simple, and only about general cross-controller binding :

*

*XML config :
<bean id="conversionService"
  class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="somepackage.StringToCategory"/>
            <bean class="somepackage.CategoryToString"/>
        </set>
    </property>
</bean>

*Java config (only in Spring 3.1+) :
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToCategory());
        registry.addConverter(new CategoryToString());
    }

}

With all these drawbacks, why using Converters ? Am I missing something ? Are there other tricks that I am not aware of ?
I am tempted to go on using PropertyEditors... Binding is much easier and quicker.

A: The simplest (assuming that you are using a persistence framework), but not the perfect way is to implement a generic entity converter via ConditionalGenericConverter interface that will convert entities using their metadata.
For example, if you are using JPA, this converter may look if the specified class has @Entity annotation, and use @Id annotated field to extract information and perform the lookup automatically using the supplied String value as an Id for lookup.
public interface ConditionalGenericConverter extends GenericConverter {
    boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);
}

ConditionalGenericConverter is an "ultimate weapon" of Spring convertion API, but being implemented once it will be able to process most of entity convertions, saving developer time - it's a great relief when you just specify entity classes as parameters of your controller and never think about implementing a new converter(except for custom and non-entity types, of course).

A:
With all these drawbacks, why using Converters ? Am I missing
  something ? Are there other tricks that I am not aware of ?

No, I think you have very comprehensively described both PropertyEditor and Converter, how each one is declared and registered.
In my mind, PropertyEditors are limited in scope - they help convert String to a type, and this string typically comes from UI, and so registering a PropertyEditor using @InitBinder and using WebDataBinder makes sense.
Converter on the other hand is more generic, it is intended for ANY conversion in the system - not just for UI related conversions(String to target type). For eg, Spring Integration uses a converter extensively for converting a message payload to a desired type.
I think for UI related flows PropertyEditors are still appropriate especially for the case where you need to do something custom for a specific command property. For other cases, I would take the recommendation from Spring reference and write a converter instead(for eg, to convert from a Long id to an entity say, as a sample).

A: *

*For to/from String conversions use formatters (implement org.springframework.format.Formatter) instead of converters. It has print(...) and parse(...) methods, so you need only one class instead of two.
To register them, use FormattingConversionServiceFactoryBean, which can register both converters and formatters, instead of ConversionServiceFactoryBean.

*The new Formatter stuff has a couple of additional benefits:

*

*Formatter interface supplies the Locale object in its print(...) and parse(...) methods, so your string conversion can be locale-sensitive

*In addition to the pre-registered formatters, FormattingConversionServiceFactoryBean comes with a couple of handy preregistered AnnotationFormatterFactory objects, that allow you to specify additional formatting parameters via annotation.
For example:
@RequestParam @DateTimeFormat(pattern="MM-dd-yy") LocalDate baseDate ...
It's not very difficult to create your own AnnotationFormatterFactory classes, see Spring's NumberFormatAnnotationFormatterFactory for a simple example.
I think this eliminates the need in controller-specific formatters/editors. Use one ConversionService for all controllers and customize the formatting via annotations.

*I agree that if you still needs some controller-specific string conversion, the simplest way is still to use custom property editor. (I tried to call 'binder.setConversionService(...)' in my @InitBinder method, but it fails, since the binder object comes with the 'global' conversion service already set. Seems like per-controller conversion classes are discouraged in Spring 3).

A: You can sort of work around the need for having two separate Converter classes by implementing the two Converters as static inner classes.
public class FooConverter {
    public static class BarToBaz implements Converter<Bar, Baz> {
        @Override public Baz convert(Bar bar) { ... }
    }
    public static class BazToBar implements Converter<Baz, Bar> {
        @Override public Bar convert(Baz baz) { ... }
    }
}

You would still need to register both of them separately, but at least this cuts down on the number of files you need to modify if you make any changes.


text:
Q: Python Tinker Sqlite3 Retrieve Data and Show on Tkinter GUI I have a database with various tool components. I also have a page with fields that I would like to populate with data from the database. I have looked at a lot of docs for both Tkinter and Sqlite3, and can't figure out how to do this. It seems like it would be a simple thing to do, but nothing I try has worked. The code for the window I would like to populate is below. Can someone please show me an example of how I could get specific table data from the database to populate these fields? Thanks in advance.
Here is my code so far:
    from tkinter import *
    import sqlite3

    data = Tk()
    data.title("WellSav | Data")
    data.geometry("1400x800")

    conn = sqlite3.connect('well_sav.db')
    c = conn.cursor()

    # Tools Frame Insert Data Into Fields

    tools_frame = LabelFrame(data, text="Tools Data", padx=5, pady=5)
    tools_frame.grid(row=0, column=0, padx=10, pady=10)

    tools_type_label = Label(tools_frame, text="Tool Type")
    tools_type_label.grid(row=0, column=0,)
    tools_type_entry = Entry(tools_frame)
    tools_type_entry.grid(row=0, column=1)

    tools_length_label = Label(tools_frame, text="Tool Length")
    tools_length_label.grid(row=1, column=0)
    tools_length_entry = Entry(tools_frame)
    tools_length_entry.grid(row=1, column=1)

    tools_inside_diameter_label = Label(tools_frame, text="Tool ID")
    tools_inside_diameter_label.grid(row=2, column=0)
    tools_inside_diameter_entry = Entry(tools_frame)
    tools_inside_diameter_entry.grid(row=2, column=1)

    tools_outside_diameter_label = Label(tools_frame, text="Tool OD")
    tools_outside_diameter_label.grid(row=3, column=0)
    tools_inside_diameter_entry = Entry(tools_frame)
    tools_inside_diameter_entry.grid(row=3, column=1)

    data.mainloop()

A: A ttk.Treeview without the tree part can be used to display a table:
tree = ttk.Treeview(master, columns=('Position', 'Name', 'Score'), show='headings')

Then set the column labels with
tree.heading(<column>, text="Label")

and add rows with
tree.insert("", "end", values=(<position>, <name>, <score>))

The first argument is the item's parent, since you want a table, all items have the same parent, the root "". The second argument is the position of the new item in the tree.
Full example:

import tkinter as tk
from tkinter import ttk
import sqlite3

def show():
    cr=sqlite3.connect('database_name')
    c.cursor()
    c.execute("select * from table_name")

    tempList = c.fetchall()
    tempList.sort(key=lambda e: e[1], reverse=True)

    for i, (name, score) in enumerate(tempList, start=1):
        listBox.insert("", "end", values=(i, name, score))

scores = tk.Tk()
label = tk.Label(scores, text="High Scores", font=("Arial",30)).grid(row=0, columnspan=3)
# create Treeview with 3 columns
cols = ('Position', 'Name', 'Score')
listBox = ttk.Treeview(scores, columns=cols, show='headings')
# set column headings
for col in cols:
    listBox.heading(col, text=col)
listBox.grid(row=1, column=0, columnspan=2)

showScores = tk.Button(scores, text="Show scores", width=15, command=show).grid(row=4, column=0)
closeButton = tk.Button(scores, text="Close", width=15, command=exit).grid(row=4, column=1)

scores.mainloop()

You can find more details about the Treeview widget here.


text:
Q: C++ Printing Odd numbers instead of Prime Numbers I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:
Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.
I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!
int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}

A: In addition to Sumit Jindal's answer inner for loop can be done by this way as well:
for(int j=2; j*j<=i ; j++)

If we think about every (x,y) ordered pair that satisfies x*y = i, maximum value of x can be square root of i.

A: The problem lies in the if-else branch. Your inner loop will be run exactly once because it will break out of the inner loop as a result of your if else branch.
When you first enter the inner loop the value of j is 2. Your condition will test if variable i is divisible by 2. If it is it breaks. Other wise (your else branch) will print the value of i and breaks out.
Hence printing odd numbers.
Break out of the inner loop and check whether j equals i in outer loop. You have to make j available for outer loop.

A: Your print statement is within the inner loop, and it should not be - it's only a prime if you run all the way through the inner loop without finding a divisor.
As a second point, you only need to check for divisors up to the square root of i, not all the way up to i.

A: You are breaking the inner loop after the first iteration itself, which is checking if the number(ie i) is different from j and is  divisible by 2 or not (since j=2 for the first iteration)

I am getting 2,3,5,7,9 as my output

This is because every odd number fails the if and is printed in else condition

A: A minor correction in your code, adding a flag. Also you don't need to run the inner loop i times, infact only i/2 times is sufficient. This is simple mathematics, but will save significant number of CPU cycles (~5000 iterations lesser in your case)
#include <iostream>

int main()
{
    int n = 10;
    for(int i=2; i<=n; i++){
        bool isPrime = true;
        for(int j=2; j<=i/2; j++){
            if(i!=j && i%j==0){
                isPrime = false;
                break;
            }
        }
        if(isPrime)
            std::cout << i << " ";
    }
    return 0;
}

A: Another version, if you don't mind output in reverse order.
int n = 10;

for (int i = n; i > 1; --i)
{
    int factorCount = 0;
    for (int j = 2; j <= n; ++j)
    {
        if (i % j == 0)
            factorCount++;

        if (factorCount > 1)
            break;
    }
    if (factorCount == 1)
        cout << i << endl;
}

A: int main() {

    for (int i = 2; i <= 100; i++) {
        for (int j = 2; j < i; j++) {
            if (i%j == 0)
                break;

            if (j==i-1) // means has never run previous if blog
                cout << i << endl;
        }
    }

    return 0;
}


text:
Q: Need to merge 2 xml in xslt based on a common key I have 2 source variables which need to be merged based on a common key in XSLT
Variable 1:I have added few properties for each employee.
<EmpDetails>
<Emp>
<ID>1</ID>
<Name>A</Name>
<Address>abc 123</Address>
<Contact>1234567890</Contact>
<DOB>01/01/1989</DOB>
<Emp>
<Emp>
  <ID>2</ID>
   <Name>B</Name>
   <Address>ASDF</Address>
   <Contact>123456</Contact>
   <DOB>02/02/1990</DOB>
   <Emp>
   </EmpDetails>

Variable 2:
<EmpAgeDetails>
<EmpAge>
   <ID>1</ID>
   <Age>27</Age>
  <EmpAge>
  <EmpAge>
    <ID>2</ID>
   <Age>26</Age>
  <EmpAge>
 </EmpAgeDetails>

Expected output:
 <EmpDetails>
 <Emp>
   <ID>1</ID>
   <Name>A</Name>
   <Address>abc 123</Address>
   <Contact>1234567890</Contact>
   <DOB>01/01/1989</DOB>
   <Age>27</Age>
  <Emp>
  <Emp>
      <ID>2</ID>
      <Name>B</Name>
      <Address>ASDF</Address>
      <Contact>123456</Contact>
      <DOB>02/02/1990</DOB>
      <Age>26</Age>
     <Emp>
      </EmpDetails>

I am using a template to copy all elements from Variable 1 which is working fine.
But now I need to merge that extra element of Age.
Any help is appreciated

A: Using XSLT 3.0 and xsl:merge, as supported in the latest Altova XMLSpy/Raptor or Saxon 9.7 EE, you can use
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:math="http://www.w3.org/2005/xpath-functions/math" xmlns:array="http://www.w3.org/2005/xpath-functions/array" xmlns:map="http://www.w3.org/2005/xpath-functions/map" exclude-result-prefixes="array fn map math xs">

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:param name="doc1">
        <EmpDetails>
            <Emp>
                <ID>1</ID>
                <Name>A</Name>
                <Address>abc 123</Address>
                <Contact>1234567890</Contact>
                <DOB>01/01/1989</DOB>
            </Emp>
            <Emp>
                <ID>2</ID>
                <Name>B</Name>
                <Address>ASDF</Address>
                <Contact>123456</Contact>
                <DOB>02/02/1990</DOB>
            </Emp>
        </EmpDetails>
    </xsl:param>

    <xsl:param name="doc2">
        <EmpAgeDetails>
            <EmpAge>
                <ID>1</ID>
                <Age>27</Age>
            </EmpAge>
            <EmpAge>
                <ID>2</ID>
                <Age>26</Age>
            </EmpAge>
        </EmpAgeDetails>
    </xsl:param>

    <xsl:template match="/" name="xsl:initial-template">
        <EmpDetails>
            <xsl:merge>
                <xsl:merge-source select="$doc1/EmpDetails/Emp">
                    <xsl:merge-key select="ID"></xsl:merge-key>
                </xsl:merge-source>
                <xsl:merge-source select="$doc2/EmpAgeDetails/EmpAge">
                    <xsl:merge-key select="ID"></xsl:merge-key>
                </xsl:merge-source>
                <xsl:merge-action>
                    <xsl:copy>
                        <xsl:apply-templates select="current-merge-group()[1]/*, fn:current-merge-group()[2]/Age"/>
                    </xsl:copy>
                </xsl:merge-action>
            </xsl:merge>
        </EmpDetails>

    </xsl:template>

</xsl:stylesheet>

Using XSLT 2.0 you could group:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>

    <xsl:param name="doc1">
        <EmpDetails>
            <Emp>
                <ID>1</ID>
                <Name>A</Name>
                <Address>abc 123</Address>
                <Contact>1234567890</Contact>
                <DOB>01/01/1989</DOB>
            </Emp>
            <Emp>
                <ID>2</ID>
                <Name>B</Name>
                <Address>ASDF</Address>
                <Contact>123456</Contact>
                <DOB>02/02/1990</DOB>
            </Emp>
        </EmpDetails>
    </xsl:param>

    <xsl:param name="doc2">
        <EmpAgeDetails>
            <EmpAge>
                <ID>1</ID>
                <Age>27</Age>
            </EmpAge>
            <EmpAge>
                <ID>2</ID>
                <Age>26</Age>
            </EmpAge>
        </EmpAgeDetails>
    </xsl:param>

    <xsl:template match="/" name="main">
        <EmpDetails>
            <xsl:for-each-group select="$doc1/EmpDetails/Emp, $doc2/EmpAgeDetails/EmpAge" group-by="ID">
                <xsl:copy>
                    <xsl:copy-of select="current-group()[1]/*, current-group()[2]/Age"/>
                </xsl:copy>
            </xsl:for-each-group>
        </EmpDetails>
    </xsl:template>

</xsl:stylesheet>


text:
Q: How to use expandos in backtick shell command In my .muttrc I have attribution set to emulate Outlook-style message quoting like this:
set attribution="\n\n-----Original Message-----\nFrom: %f\nSent: %d\n%t\nSubject: %s\n"

However, the %t expando evaluates to "To Persons_Name" with no colon after the "To" so I'd like to run it through a shell command to add the colon. I can use backticks to run a shell command but I can't figure out how to get the value of the %t expando in the shell command. I've tried this but it doesn't work:
set attribution="\n\n-----Original Message-----\nFrom: %f\nSent: %d\n`echo %t | sed s/^To/To:/`\nSubject: %s\n"

A: The shell commands are executed when the config setting is read, not every time you reply. You can see that by entering
 set attribution="Date: `date`"

It never changes. And of course, expandos aren't expanded at that moment.
There is way: if you end the string with a |, mutt assumes it is a command and just executes it and uses its output (the documentation says it pipes the arguments through the first word, but that's a lie).
The problem is, there isn't any unix command (that I know of) which applies a regex to its arguments and outputs the result. sed, for instance, only works on files or stdin.
You have to create that command yourself. In Perl, it would be something like that:
#!/usr/bin/perl

my $regexp = shift;
my @out;
for (@ARGV) {
  eval $regexp;
  push @out, $_;
}

print join " ", @out;

Let's say you put this in your path and name it r.pl (remember to chmod-x it), then you can set your attribution this way:
set attribution="r.pl 's/^To /To: /m' 'From: %n\n%t\netc...\n'|"

Take a look into man perlre to find out why you need to end the regexp with /m.
HTH.


text:
Q: A meaning of "hit the ground running" What's the meaning of this phrase in this sentence?
"The plan is to hit the ground running for the next year."
Also, can I use the phrase with "to"? like this↓?
"I am going to hit the ground running to start the plan"
Sorry for gramatically incorrect sentences cuz I'm not a native.

A: The phrase is a metaphor. It is becoming what was designated many years ago by Fowler as a dead metaphor in that it refers to an image that is no longer clear or even relevant.
The idea behind the image is that if you are on some military mission involving jumping out of a vehicle and immediately springing into action, then you are "hitting the ground running" as distinct from gathering yourself together, making sure you have all your kit with you, have consulted your map, have spoken to your superior officer et cetera et cetera.
Unless you are certain that your superiors like that kind of language, you would be advised to say something like "I am ready and will start putting the plan into action immediately".

A: The dictionary meaning on google is "start something and proceed at a fast pace with enthusiasm."
In your example "The plan is to hit the ground running for the next year" I'm sure the speaker means to say that they plan to be ready to start and make quick/significant progress next year. However, the use of "for" makes it unclear if they intent to start today and make progress that will set them up for next year.
Your second example, "I am going to hit the ground running to start the plan" is redundant - "Hitting the ground running" already involves the idea that you're starting something. It would be more colloquially correct to say "For this plan, we want to hit the ground running"


text:
Q: Appending one URL to another as a link What I am trying to do (and failing miserably at it) is create a link...  and that link should open up a specific page with the current page appended to it.  For example... If the user is on a page called www.bar.com and click the link... he would go to www.foo.com?link=www.bar.com
Here is my sorry little attempt at this...

I could do this in PHP but I can not use PHP for this particular page.  Can someone please help?
EDIT:  I completely botched up my question be cause I added code here that i was in the middle of editing on accident.  I was trying to alter that a href code to place a specific image in that place instead ...for example

becomes...

Sorry for my ignorance.

A: It's best to wrap your img with a tag and then change its attribute : (and use + and not . for chaining strings ! )

A: Try this


text:
Q: moment.js and moment-timezone-with-data.js gives arror Unknown Provider - Moment Provider I am trying to use moment.js and moment-timezone-with-data.js in my application to display the dates in any timezone.
I have included the cdn for both of these js files in my index.html and added moment as required in my controller.
It gives -

Error: [$injector:unpr]
  http://errors.angularjs.org/1.5.7/$injector/unpr?p0=momentProvider%20%3C-%20moment%20%3C-%20manageScheduleController

My Code:
index.html - cdn for both these js files.
Controller:
.controller('manageScheduleController', function($http,$scope,sessiontracker,
     $window,$filter, $dialogs, Upload, $timeout,moment)

A: moment-timezone-with-data is Javascript library on the top of momentjs. You can directly use it inside angular application by just using moment variable. (You could consider creating wrapper constant for the same so that you can mock at the time of testing the same).
There you don't need to inject moment inside controller factory function as dependency. Removing moment parameter from controller function will fix the problem.

Note: Make sure you had reference moment-timezone-with-data.js on your index.html page.


text:
Q: Why do I need more than one node in order to simple index document? I'm trying to study elasticsearch and test it with python.
I'm running with the following versions:

*

*windows 10

*elasticserach 7.5.1

*python 3.7.3
I run elastic search (double click on bin/elasticsearch.bat) and run the following python script:
(which I tooked from https://elasticsearch-py.readthedocs.io/en/master/0
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()

doc = {
    'author': 'kimchy',
    'text': 'Elasticsearch: cool. bonsai cool.',
    'timestamp': datetime.now(),
}
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)

But I'm getting exceptions:
Python37\lib\site-packages\urllib3\connectionpool.py", line 421, in _make_request
    six.raise_from(e, None)
....
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
... Python37\lib\site-packages\elasticsearch\connection\http_urllib3.py", line 238, in perform_request
    method, url, body, retries=Retry(False), headers=request_headers, **kw
...exceptions.ReadTimeoutError: HTTPConnectionPool(host='localhost', port=9200): Read timed out. (read timeout=10)...

when I check localhst:9200 is seems that elasticsearch is not running
If I'm running another node:
elasticsearch.bat-Epath.data=data2 -Epath.logs=log2

I can see it run (localhst:9200) and getting no exceptions.
It seems so simple, but what am I doing wrong ? Why do I need to run more than one node ?


text:
Q: Slow in writing data from webserver to Local DB in Android I am trying to pull data from my webserver and add them to Local DB in background using a service.. Data is getting stored to Local DB without any issues but while this is happening the phone becomes slow (there is some dragging). Just wondering if I am doing things correctly in writing to DB or is there better and faster way to do it.
I am using AsyncHttpClient library to pull data from webserver.
final RequestParams requestParams = new RequestParams();
        final String uploadWebsite = url_acc_details;

        AsyncHttpClient client = new AsyncHttpClient();
        client.post(uploadWebsite, requestParams, new JsonHttpResponseHandler()
        {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response)
            {
                try
                {
                    success = response.getInt(TAG_SUCCESS);

                    if (success == Integer.parseInt(getResources().getString(R.string.successvalue)))
                    {
                        details = response.getJSONArray(TAG_DETAIL);
                        for (int i = 0; i < details.length(); i++)
                        {
                            JSONObject c = details.getJSONObject(i);

                            acc_iD = c.getString(TAG_ACC_ID);
                            acc_nAme = c.getString(TAG_ACC_NAME);
                            acc_Image = c.getString(TAG_ACC_IMAGE);
                            acc_active = c.getString(TAG_ACC_ACTIVE);
                            acc_priority = c.getString(TAG_ACC_PRIORITY);
                            acc_creator = c.getString(TAG_ACC_CREATOR);

                            dblocal.setAccDetails(Integer.valueOf(acc_iD), acc_nAme, acc_Image, acc_active, acc_priority, acc_creator);
                        }
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
                stopSelf();

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse)
            {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                stopSelf();
            }
        });

Similarly I am starting three services running in bankground at the same time with same above logic but for getting different details.
It would be great if somebody could let me know the way to do the above process faster and better?

A: First, you should use Singleton pattern for your AsyncHttpClient. This way, you don't have to redefine a new resource for each and every request.
public class MyAsyncHttpClient extends AsyncHttpClient {
    private static MyAsyncHttpClient client;

    private MyAsyncHttpClient() {

    }

    public static MyAsyncHttpClient getClient() {
        if (client == null) {
            client = new MyAsyncHttpClient();
            // do whatever, setCookieStore, addHeader, etc
        }

        return client;
    }
}

Then in your asyncTask
replace new AsyncHttpClient()
with MyAsyncHttpClient.getClient()
Second, do your database operation in background as well.
Declare an interface:
public interface DatabaseOperationListener {
    public void perform();
    public void onFinish();
}

...

client.post(uploadWebsite, requestParams, new JsonHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response)
    {
        new DatabaseTask(new DatabaseOperationListener() {
            @Override
            public void perform() {
                DatabaseManager dblocal = DatabaseManager.getInstance();
                dblocal.setAccDetails(Integer.valueOf(acc_iD), acc_nAme, acc_Image, acc_active, acc_priority, acc_creator);

            }

            @Override
            public void onFinish() {
                // do something, perform another request, etc
            }
        }).execute();

   @Override
   public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable error) {
       super.onFailure(statusCode, headers, errorResponse, error);
       // do something
   }
});

Do note that I also have a Singleton instance for the database.


text:
Q: Power BI Capacity/Tenant/Gateway - where does the data sit and flow? I have a scenario with Power Bi Premium where it has been very difficult to get a straight answer or find information that answers the question.
Our Power BI tenant is located in Australia, our Power BI Premium capacity is located in Switzerland, our on premise data is located in UK.
When configuring the on-premise data gateway, you are forced to create the connection in the default tenant region, this being Australia.
If you are a Swiss users with a workspace configured to use the Swiss hosted capacity is all data now flowing from UK > Australia > Switzerland Capacity?
Are reports rendering from a swiss user perspective;

*

*Via the PBI service in Aus using the swiss capacity directly?

*in the same datacentre location as the capacity?

I'm not sure how else to describe it and hope it makes sense. This just seems like a non enterprise ready setup perfornace wise and hope I've miss interpreted what I've been reading.
Thanks


text:
Q: how to validate with minor fixes only if (textbox1.Text.Length == 0)
        {
            textbox1.Text = "*cannot be empty";
        }
        else
        {

            int checkNumber;
            if (int.TryParse(textbox1.Text, out checkNumber) == false)
            {
                textbox1.Text = "NUMBERS ONLY!";
                return;
            }
            else
            {

                if (textbox1.Text.Equals(0))
                {
                    textbox1.Text = "Invalid";
                }
                else
                {
                    textboxl.Text = "";
                }
            }
        }

This is my code and i have tested it and works. But I want to put a validation services, web service.
Is there a way to do it without having to change majority of the code. I just want to make it simple enough so that i can understand step by step.
my plan is to cut and paste this code into the web service with not too much of coding. This isnt for a real website by the way. just doing some simple testing so i dont mind if the security is weak.
It would be a great help if you could provide a step-by-step explanation.

A: As per my understanding, you should be doing something like below
public string ValidateInputString(string input)
{
   // Your Logic Here
   return responseString;
}

Call this method in the same place from UI where you have writeen this code.
Hope this Helps!!


text:
Q: Gray Level Co-occurence Matrix I try to implement the GLCM method with the formula from wikipedia, but I have problems to fill my GLCM due to indices problems with matlab.
I have also used NitdepthQuantisation to reduce the number of Gray Levels, but for now I use the full 8 bit.
function [C] = GLCM(img, level, theta, delta)

 % Quantisation of the input Image to desired value
 imgQ = ImageQuantisation(img, level);
 [m n] = size(imgQ);

 % Get the number of gray levels
 maxGV = max(img(:));

 % Create GLCM initial Matrix
 C = zeros(maxGV, maxGV);

 % Positions
 delta_x = ceil(delta*cos(theta));
 delta_y = ceil(delta*sin(theta));

 %% Find Occurences
 for i = delta_x+1:m-delta_x
   for j = delta_y+1:n-delta_y
     if(imgQ(i, j) == imgQ(i+delta_x, j+delta_y))

        C(, ) = C(, ) + 1;
     end

   end
  end

end

A: The answer can be found by ensuring the inner nested double for loops have the correct indices to access the image.  They were using the outer most pair of for loops for indices rather than the inner ones.  The OP has commented that this has slight differences between what MATLAB gives to calculate the GLCM but it is good enough for the OP to overlook:
 for o = 1:maxGV
    for p = 1:maxGV
        if(imgQ(i, j) == o & imgQ(i+delta_x, j+delta_y) == p)
            C(o, p) = C(o, p) + 1;
        end
    end
 end


text:
Q: Unicode, _stprintf() and mixed text directions I'm working on refactoring some legacy c++ code to support Unicode and I am experiencing problems when a _stprintf is used with a format string of _T("%s %s") and the arguments are: arabic text(right-to-left) followed by some digits stored in a character array. Here is a code snippet:
auto buf = std::make_unique<TCHAR>();
TCHAR Text[]{_T("حبيبيحبيبيحبيب")};
TCHAR Number[]{_T("12345678h90")};

_stprintf(buf.get(), _T("%s %s"), Text, Number);

What I get in buf is حبيبيحبيبيحبيب 12345678h90, but what I want to get is the contents of the Text array followed by the contents of the Number array. (I tried to paste it here but it got automatically formated in the same way as the _stprintf does it...).
I know that the reason for this is that arabic text is a strong character type and all of the numbers are weak types and I have a relatively simple solution - overload _stprintf , check if a parameter string begins with digits and prepend the U+200E (\u200E) control character. However, I can't help but think that there might be a simpler solution that I don't know about like a global setting or something?  Is there something like that?
These strings that are being passed to SetWindowText and are displayed in the wrong order because of the arabic. My main goal is to get them to render properly in the UI.


text:
Q: arrayList swap a number? I am following some pseudo code, I am currently stuck on this part:
Input: A list (permutation) of size N
1) Let i=j=0
2) While i=j
3)    Let i = UI(1,|T|)
4)    Let j = UI(1,|T|)
5) End While
6) Let temp = ti, Let ti = tj, Let tj = temp
Output: Changed list T
static ArrayList<Integer> newSmallChange(ArrayList<Integer> list){
    int i = 0;
    int j = 0;
    while (i == j){
        i = CS2004.UI(1, list.size());
        j = CS2004.UI(1, list.size());
    }
    int temp = list.get(i);
}

This is the code that i've developed thus far, I am literally just stuck on step 6 as i am unsure how to write that part out.

A: int temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);


text:
Q: Regular Expression for testing length of string part Hi I need a regular expression which is accepting the following strings:
[A-Z]-[A-Z]{3-5}[0-9]{2-4}

for example X-ABC123 or Y-AB1234
The problem now is that the total length of the string on the right side of the hyphen must always be 5 chars in length. Is there a chance to check that with regular expressions only?

A: Just add this after the hyphen :
/(?=[A-Z\d]{5}$)/

Resulting in :
/^[A-Z]-(?=[A-Z\d]{5}$)[A-Z]{3,5}[0-9]{2,4}/

This assumes that your input strings are the strings you posted.
X-ABC123 -> fails
Y-AB1234 -> fails
A-ABD12  -> matches
A-ABV111 -> fails

If the string is part of another string you can replace the $ anchor with \s|$ for example.

A: I think it's definitely possible, from a language theory point of view. Just group it and add the constraint :
I just need to know which language is specifying the regex but something like this :
[A-Z]-(^[A-Z][A-Z0-9]4)

I had the feeling you wanted the right part to start with one char for sure, then either chars or numbers

A: First the problems in your regex
The quantifier is {3,5} and not {3-5} (this would match literally "{3-5}")
You want 3 to 5 letters and 2 to 4 digits and in total 5 letters and digits ==> the only valid combination is then 3 letters followed by 2 digits.
In general you can use a positive lookahead for this
^[A-Z]-(?=.{5}$)[A-Z]{3,5}[0-9]{2,4}$

See it here on Regexr
The (?=.{5}$) part is just looking, if there are from its position to the end ($) 5 characters.
But as said before, if the 3-5 and 2-4 and overall 5 is valid you can just do
^[A-Z]-[A-Z]{3}[0-9]{2}$


text:
Q: Write a RGBA8 image as a R32UI I have an image with the format R8G8B8A8 (Unorm).
I want to write uint data on it (to be able to use atomic function).
So, when I want to "write" it, I am using in the glsl :
layout(set = 0, binding = 2, r32ui) restrict writeonly uniform uimage3D dst;

However, when I am performing something like
imageStore(dst, coords, uvec4(0xffffffff));

RenderDoc (and my app as well) tells me that all my values are 0 (instead of 1.0 (255 unorm)).
If I replace the r32ui by rgba8 everything works fine but I can not use atomic values. So I wonder if it is possible to do such thing. (However, if I use a r32f instead of rgba8, it works fine as well).
Do you have any solution?

A: Vulkan specification guarantees that atomic operations must be supported for storage images (VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT) with only R32_UINT and R32_SINT formats. Implementations may add such support for other formats as well but it's not obligatory. So it's nothing strange that atomic operations don't work with rgba8 format.
Next. You can create an image view with a different format than the format of the image. In such case the image view's format must be compatible with the image's format. In case of the R8G8B8A8 format, both SINT and UINT R32 formats are compatible (have the same number of bits). But to be able to create an image view with a different format, image itself must be created with a VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT flag.
One last thing - there is a note in the specification about format compatibility/mutable images:

Values intended to be used with one view format may not be exactly
  preserved when written or read through a different format. For
  example, an integer value that happens to have the bit pattern of a
  floating point denorm or NaN may be flushed or canonicalized when
  written or read through a view with a floating point format.
  Similarly, a value written through a signed normalized format that has
  a bit pattern exactly equal to -2^b may be changed to -2^b + 1 as
  described in Conversion from Normalized Fixed-Point to Floating-Point.

Maybe this is the problem? Though it seems that there should be no conversion between rgba8 (unorm) and r32 (uint). Did validation layers report any warnings or errors? What layout is Your image in when You try to store data in it? Don't forget that:

Load and store operations on storage images can only be done on images
  in the VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR or VK_IMAGE_LAYOUT_GENERAL
  layout.


text:
Q: RESTSharp Max post Size We are currently using:
request.JsonSerializer = new RestSharpJsonNetSerializer(jsonSerializer);

to serialize our JSON POST request. Our JSON is approximately 4.5MB when created. It appears that when the JSON is serialized it is getting truncated therefore it is failing when it gets to our API endpoint.
Is there is a way to set the max size of a JSON POST for RestSharp?


text:
Q: Django cannot find GDAL on windows 10 64 bit I am using PyCharm and Python 3.8 - 64 bit. I am trying to learn to implement GeoDjango and Leaflet with a Postgis database. I have a postgresql database with postgis extension. I also have psycopg2 installed following the comments from this earlier thread of mine. psycopg2 not detected by postgres django
In settings.py,
DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'my-database',
        'USER': 'my-user',
        'PASSWORD': 'my-password',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

When I try to run python manage.py makemigrations I get the following error.
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    django.setup()
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\models\base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\models\base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\db\utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 6, in <module>
    from .features import DatabaseFeatures
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\db\backends\postgis\features.py", line 1, in <module>
    from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\db\backends\base\features.py", line 3, in <module>
    from django.contrib.gis.db.models import aggregates
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\db\models\__init__.py", line 3, in <module>
    import django.contrib.gis.db.models.functions  # NOQA
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\db\models\functions.py", line 4, in <module>
    from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\db\models\fields.py", line 3, in <module>
    from django.contrib.gis import forms, gdal
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\forms\__init__.py", line 3, in <module>
    from .fields import (  # NOQA
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\forms\fields.py", line 2, in <module>
    from django.contrib.gis.gdal import GDALException
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\gdal\__init__.py", line 28, in <module>
    from django.contrib.gis.gdal.datasource import DataSource
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\gdal\datasource.py", line 39, in <module>
    from django.contrib.gis.gdal.driver import Driver
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\gdal\driver.py", line 5, in <module>
    from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 9, in <module>
    from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
  File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 40, in <module>
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal203", "gdal202", "gdal201", "gdal20", "gdal111"). Is GDAL installed? If it is, try setting GDAL_LIBR
ARY_PATH in your settings.

I have looked at a lot of threads but I couldn't find a solution.

A: It looks like you don't have GDAL library installed at all.
Try installing it and do makemigrations.
pip install GDAL

It looks like you can try the solutions mentioned in this page.
https://realpython.com/lessons/create-nearbyshops-app/

A: Solved from this thread GeoDjango on Windows: "Could not find the GDAL library" / "OSError: [WinError 126] The specified module could not be found" .
1. Basically go to this site https://trac.osgeo.org/osgeo4w/ .
2. Download the 32 bit or 64 bit package as per your requirements.
3. During installation, select Web-GIS Install and click next.
4. Under selected packages, select GDAL, MapServer. Select Apache if it allows.
5. There will be a prompt to install some additional dependencies. Allow them.
6. Agree to all the terms and conditions prompts.
7. After installation, go to settings.py and add the following before INSTALLED_APPS = [...]
if os.name == 'nt':
    import platform
    OSGEO4W = r"C:\OSGeo4W"
    if '64' in platform.architecture()[0]:
        OSGEO4W += "64"
    assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W
    os.environ['OSGEO4W_ROOT'] = OSGEO4W
    os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal"
    os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj"
    os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH']

*Run python manage.py commands to check if it is working.


text:
Q: Same logic used in Java doesn't work in Python I've been practicing a little bit doing the exercises from this website. My question concerns exercise #19 where the following is asked:

I actually ran the same logic mentioned below in Java and it worked, but I can't understand why it won't work in Python.
import os

List = [0,1,2,3,4,5,6]

for i in List:

    if i==0 or i==6:
        for j in range(1,5):
            print "*",
        print("")
    if i==3:
        for k in range(1,4):
            print "*",
        print("")
    else:
        print "*",

print("")

os.system("pause")

A: Try something like this:
for i in range(7):
    if i in [0,6]:
        print('*' * 5)
    elif i == 3:
        print('*' * 4)
    else:
        print('*')

*

*instead of List = [0,1,2,3,4,5,6] use range(7)

*you had an error in the if statements, you pair them with if, elif, else. The else statement in your code was only pairing with the second if statement

*printing print "*", still omits a space, you can avoid that with doing '*'*5

*rewrite if i==0 or i==6 into if i in [0,6], this is a bit easier to read and easier to extend

A: The solution for #19 on that website is terrible.
If you're going to keep a static list, keep a static list of number of stars to print per line:
num_stars = [5, 1, 1, 4, 1, 1, 5]
for num in num_stars:
    print('*' * num)

Also worth noting that if you would rather store the input as a string first and print it out, you can use a simple str.join() with a list comprehension in it:
e = '\n'.join(['*' * num for num in num_stars])
print(e)


text:
Q: How to get the column value based on multiple rows? I want to check rows where uid equal both 1 and 2 and if they do, return cid. In this example there will only ever be 2, but if you know a way to return the CID for more than 2, that would be great too.
How can I most easily get the value where cid = 5 when I know both uid values? (1,2).
 cid | uid |
------------
  5  |  1  |
  5  |  2  |
  6  |  1  |
  6  |  3  |
  7  |  1  |
  7  |  4  |

For pseudo sql, I am thinking something like SELECT cid WHERE uid = 1 or uid = 2
This returns all rows where uid has a 1 or a 2. How can I limit to an OR statement and an AND?
SELECT cid WHERE uid = 1 AND uid = 2 (but in multiple rows)
Any ideas?

A: As far as i understand you're looking for a way to apply a condition to multiple rows, a way to do that is through agrupation functions. try this:
Select CID
from YourTable where uid IN (1,2)
group by cid
having count(uid) = 2

in this example i'm using IN instead of two OR and i'm grouping the rows by CID, and after that i'm limiting the results to those rows that match with UID equals to 1 and 2.
There are many tricky ways of achieve the same result, for example you can also do something like:
Select CID
from YourTable where uid IN (1,2)
group by cid
having sum(uid) = 3

in this example i'm suming the UID column, if UID is 1 and 2 the sum of both will result on 3, I assume that you can't have 3 rows with the UID 1 and the same CID

A: According to given details, Try this. Let's say you have a table called docs;
SELECT d1.cid
FROM docs AS d1
LEFT JOIN docs AS d2 ON d1.cid = d2.cid
WHERE d1.uid = 1
AND d2.uid = 2


text:
Q: How to change justify depending on the size of the screen in Vuetify? In my application, I use the end justified button by justify="end". If there is a smaller screen (e.g. tablet) I want to change it to center justification - justify="center".
My code:
<template>
  <v-row  justify="end" >
    <v-col cols="5">
      <v-btn
        to="/"
        >Back</v-btn
      >
    </v-col>
  </v-row>
</template>

I also tried to use css styles something like this but it doesn't work:
<style scoped>
@media (max-width: 800px) {
  .justify{
    justify: center;
  }
}
</style>

A: instead of the props you can use built in flex classes in vuetify like .justify-md-center
have a look at this link in the vuetify documentation:
vuetify flex classes documentation


text:
Q: Getting State environment in a monadic context in an interpreter I wanna get used to working monad transformers so I thought I'd write a simple interpreter using ExceptT and State, where my state is Map Ident Int, Ident being an alias for Strings.
My syntax definition looks like
data BinOp
  = Plus
  | Minus
  | Times
  | Div
  deriving (Eq, Show)

data Stmt
  = CompoundStmt Stmt Stmt
  | AssignStmt Ident Exp
  | PrintStmt [Exp]
  deriving (Eq, Show)

data Exp
  = IdentExp Ident
  | NumExp Int
  | OpExp Exp BinOp Exp
  | SeqExp Stmt Exp
  deriving (Eq, Show)

but that's not that relevant. I got to evaluating identifier expressions when I realized I have no idea how to actually fetch my environment:
interpIdentExp :: (MonadState Env m, MonadError EvalError m) => Ident -> m Int
interpIdentExp ident = do
  env <- get
  fromMaybe (throwError IdNotDefined) (M.lookup ident env)

was my first go at it, but env is actually Map Ident (m Int), whereas I just wanna deal with plain Ints and I'm not exactly sure how to make it work.

A: I assume the last bit is a misprint, and Env is defined as Map Ident Int rather than Map Ident (m Int).
The following should work:
interpIdentExp :: (MonadState Env m, MonadError EvalError m) => Ident -> m Int
interpIdentExp ident = do
  env <- get
  maybe (throwError IdNotDefined) return (M.lookup ident env)

though some might prefer to make it more obvious how the state is being accessed by writing:
interpIdentExp :: (MonadState Env m, MonadError EvalError m) => Ident -> m Int
interpIdentExp ident = do
  mval <- gets (M.lookup ident)
  maybe (throwError IdNotDefined) return mval

Personally, I think the more verbose case statement makes the error handling easier to read, so I'd favor:
interpIdentExp :: (MonadState Env m, MonadError EvalError m) => Ident -> m Int
interpIdentExp ident = do
  mval <- gets (M.lookup ident)
  case mval of
    Just val -> return val
    Nothing -> throwError IdNotDefined


text:
Q: mvc 5 forms authentification error I would like to implement form authorization is my application.
In my controller i set:
 FormsAuthentication.SetAuthCookie(loginVm.use_email, loginVm.RememberMe);

Then in my view:
if (Request.IsAuthenticated)

I got my Request.IsAuthenticated always false, so i tried to add those lines below in the webconfig.
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
  </system.web>

However, I came across the error:
 It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

I am running in debug mode localhost, what should i do to try to make it works according to you
Thanks for your helps
Cheers

A: I found the answer, somehow i got another web.config file in the view folder so i remove it :), it works fine now


text:
Q: Magento 2: Unable to upgrade Magento 2.1.3 I'm trying to upgrade from Magento 2.1.2 to 2.1.3 on my Linux Server. On my Local WAMP it's working fine.
I'm upgrading in Developer Mode.
I got below error.
root@magento-2:/var/www/html/magento# composer update
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Gathering patches for root package.
Loading composer repositories with package information
The "https://packagist.org/packages.json" file could not be downloaded: failed to open stream: Connection timed out
https://packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date
Updating dependencies (including require-dev)

  [Composer\Downloader\TransportException]
  The "http://packagist.org/p/symfony/filesystem%24c13f449735d971527daf30626fd921d452706653964a6736a4e50c29258b693d.json" file could not be downloaded (HTTP/1.1 302 Found)

update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [--with-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-i|--interactive] [--root-reqs] [--] [<packages>]...

[SOLUTION]
Magento 2: Composer Update is Not Working [Failed to open stream: Connection timed out]


text:
Q: Do I have to take the trace over gamma matrices in Yukawa vertex correction? Given the Yukawa coupling $\mathcal{L}_{\text{int}}=g\phi\bar{\psi}\psi$, if I want to compute the correction to one loop to the vertex, I would write something like this
$$\Lambda\sim  g\int\frac{d^dk}{(2\pi)^d}\frac{i}{(q\!\!/+k\!\!/)- m}\frac{i}{(p\!\!/-k\!\!/)-m}\frac{i}{k^2-M^2}$$
Do I have to take the trace over gamma matrices?


text:
Q: First time Updating a table I was recently given permissions to update a single table in our database but this is not something I have done before and I do not what to mess anything up. I have tried searching for something online that was similar to what I am wanting to do with no success.
The table name is dbo.Player_Miles and it only has two columns of data Player_ID and Miles both of which are set as (int,null).
Currently there are about 300K records in this table and I have a csv file I need to use to update this table. In the file there are 500k Records so I need to be able to:
INSERT the new records ~250k records
UPDATE the records with that have new information ~200K records
Leave untouched and record that has the same information(although updating those to the same thing would not hurt the database would be a resource hog I would guess) ~50K records
Also leave untouched any records in the table currently that are not in the updated file. ~50k records
I am using SSMS 2008 but the Server is 2000.

A: You should use SSIS (or DTS, which was replaced by SSIS in SQL Server 2005).
Use the CSV as your source and "upsert" the data to your destination table.
In SSIS there are different ways to get this task done.
An easy way would be to use a lookup task on Player_ID.
If there's a match update the value and if there's no match just insert the new value.
See this link for more informations on lookup-pattern-upsert

A: You could approach this in stages...
1) Backup the database
2) Create a temporary SQL table to hold your update records
create table Player_Miles_Updates (
    PlayerId int not null,
    Miles int null)

3) Load the records from your text file into your temporary table
bulk insert Player_Miles_Updates
   from 'c:\temp\myTextRecords.csv'
   with
     (
        FIELDTERMINATOR =' ,',
        ROWTERMINATOR = '\n'
      )

4) Begin a transaction
begin transaction

5) Insert your new data
insert  into Player_Miles
select  PlayerId, Miles
from    Player_Miles_Updates
where   PlayerId not in (select PlayerId from Player_Miles)

6) Update your existing data
update  Player_Miles
set     Player_Miles.Miles = pmu.Miles
from    Player_Miles pm join Player_Miles_Updates pmu on pm.Player_Id = pmu.Player_Id

7) Select a few rows to make sure what you wanted to happen, happened
select  *
from    Player_Miles
where   Player_Id in (1,45,86,14,83) -- use id's that you have seen in the csv file

8a) If all went well
commit transaction

8b) If all didn't go well
rollback transaction

9) Delete the temporary table
drop table Player_Miles_Updates