text:
Q: search in restricted access folders I want to list all files and folders that my program has access to and write them to a text file. i write a method which help me do this but in some cases (folder is access denied) my program stop working.
i search here a lot and find some links that said use try/catch and sth else but i cant fix my problem yet.
string spcdirectorypath = @"C:\Users";
            string spcfiletape = "*.*";
            DirectoryInfo d = new DirectoryInfo(spcdirectorypath);//Assuming Test is your Folder
            FileInfo[] Files = d.GetFiles(spcfiletape, SearchOption.AllDirectories); //Getting Text files
            foreach (FileInfo file in Files)
                {
                    string str = file.FullName + "\n";
                    richTextBox1.AppendText(str);
                }

now how can i fix this problem? or in other hands can i access to that restricted folders? sorry for this repetitive Q and thanks for best answers :)?

A: The process under which you are running your program should have the required privileges otherwise you wont be able access the folder and enumerate the files. In your test environment make sure you run this code as an administrator.

A: Just skip those directories. If it fails, ignore:
try
{
  foreach (var file in Directory.GetFiles(spcdirectorypath))
  {
    richTextBox1.AppendText(file + "\r\n");
  }
}
catch (IOException)
{
  richTextBox1.AppendText("Failed " + spcdirectoryPath + "\r\n");
}

If the exception is not an IOException, just change it to the one that actually gets thrown.

A: You should check th permissions before trying to list the files, if you want to avoid unauthorized access exceptions.
Here I adapt for your case the example of MSDN about walking a directory tree :
void YourMethod()
{
   string spcdirectorypath = @"C:\Users";
   DirectoryInfo d = new DirectoryInfo(spcdirectorypath);

   WalkDirectoryTree(d)
}

static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
    System.IO.FileInfo[] files = null;
    System.IO.DirectoryInfo[] subDirs = null;

    // First, process all the files directly under this folder
    try
    {
        files = root.GetFiles("*.*");
    }
    // This is thrown if even one of the files requires permissions greater
    // than the application provides.
    catch (UnauthorizedAccessException e)
    {
        // You may decide to do something different here. For example, you
        // can try to elevate your privileges and access the file again.
    }

    catch (System.IO.DirectoryNotFoundException e)
    {
        // You may decide to do something different here. For example, you
        // can log soething.
    }

    if (files != null)
    {
        foreach (System.IO.FileInfo fi in files)
        {
            // In this example, we only access the existing FileInfo object. If we
            // want to open, delete or modify the file, then
            // a try-catch block is required here to handle the case
            // where the file has been deleted since the call to TraverseTree().
            string str = fi.FullName + "\n";
            richTextBox1.AppendText(str);
        }

        // Now find all the subdirectories under this directory.
        subDirs = root.GetDirectories();

        foreach (System.IO.DirectoryInfo dirInfo in subDirs)
        {
            // Resursive call for each subdirectory.
            WalkDirectoryTree(dirInfo);
        }
    }
}

A: I guess that UpdatusUser is a user on that machine. User folders have restricted permissions. Try to run your application under UpdatusUser. If you don't run your application with UpdatusUser, you may try to set permission on UpdatusUser folder for your user (right-click on folder Properties/Security).
If you still encounter issues go deeper and see what is blocking using Process Monitor.


text:
Q: How to take a Fourier transform of a $\text{sinc}$ function in the complex plane.
Full disclosure: This is technically a "homework" question but not really. What I mean is that my professor gave us free reign to use Mathematica to simply get the answer to the integral but I am trying to go the extra mile and understand the full derivation, but I'm stuck.
The problem is solving the Laplace equation for a finite strip. The solution which I've already derived is:
$$V(x,y)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{2\sin{k}}{k}e^{ikx}e^{-|k|y}dk\tag{1}$$
He asks us to try to solve this integral by hand (and if we can't, to feel free to simply use Mathematica to get the answer) which I've been working on for a couple of hours. I've gotten as far as changing the integral to:
$$V(x,y)=2\int_{0}^{\infty}dk\frac{\sin{k}}{k}e^{ikz}-2\int_{0}^{-\infty}dk\frac{\sin{k}}{k}e^{ikz^*}\tag{2}$$
Where $z\equiv(x+iy)$. This is something like the Fourier transform that takes $\text{sinc}(k)\rightarrow\tilde{\text{sinc}}(z)$ but I've never evaluated a Fourier transform in the complex plane. I know I'm on the right track as the correct answer is:
$$V(x,y)=-\frac{2}{\pi}\Im(\text{arctanh}(z^{-1}))\tag{3}$$
But I'm nevertheless stuck and would appreciate a hint or a nudge in the correct direction so that I see how to proceed.
I have an inkling that the answer involves expressing $z^{-1}$ as $z^{-1}=\frac{d}{dz}\ln{z}$ and then evaluating the integral until you get something like $\frac{1}{z^*}-\frac{1}{z}$ and expressing that as $\frac{d}{dz}(\ln(z^*)-\ln(z))=\frac{d}{dz}\ln{\frac{z^*}{z}}$ which is closely related to arctan functions as discussed here but I don't quite see how to get there.

A: Too long for a comment
Using $\sin\alpha+\sin\beta=2\sin\frac{\alpha+\beta}{2}\cos\frac{\alpha-\beta}{2}$ and noting, that only $\cos kx$ from $e^{ikx}=\cos kx+i\sin kx\,$ survives integration (the even part of the integrand), we can present the integral in the form
$$V(x,y)=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{2\sin{k}}{k}e^{ikx}e^{-|k|y}dk=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{2\sin{k}\cos kx}{k}e^{-|k|y}dk$$
$$=\frac{1}{2\pi}\int_{-\infty}^{\infty}\frac{\sin{k(x+1)-\sin k(x-1)}}{k}e^{-|k|y}dk=\frac{1}{\pi}\Im\int_0^\infty\frac{e^{-k\big(y-i(x+1)\big)}-e^{-k\big(y-i(x-1)\big)}}{k}dk$$
This is the type of Frullani integral which is, strongly speaking, applicable to a real function, but at some additional conditions can be used for a complex function as well (the discussion about the similar case, for example, here).
Supposing that these conditions are met and denoting $z=x+iy$,
$$V(x,y)=\frac{1}{\pi}\Im\ln\frac{y-i(x-1)}{y-i(x+1)}=\frac{1}{\pi}\Im\ln\frac{x+iy-1}{x+iy+1}=\frac{1}{\pi}\Im\ln\frac{1-\frac{1}{z}}{1+\frac{1}{z}}=-\frac{2}{\pi}\Im\operatorname{arctanh}\Big(\frac{1}{z}\Big)$$

A: Let $V(x,y)=\frac1{2\pi}\int_{-\infty}^\infty  \frac{2\sin(k)}{k}e^{-|k|y}e^{ikx}\,dk$ for $y\ge 0$.  Then, we can write
$$\begin{align}
V(x,y)=\frac2\pi \int_0^\infty \frac{\sin(k)\cos(kx)}{k}e^{-ky}\,dk\tag1
\end{align}$$
We use Feynman's trick to evaluate the integral in $(1)$.  Differentiating $(1)$ with respect to $y$ (valid due to the uniform convergence of the integral of the differentiated integrand for $y$ bounded away from $0$) reveals
$$\begin{align}
\frac{\partial V(x,y)}{\partial y}&=-\frac2\pi \int_0^\pi \sin(k)\cos(kx)e^{-ky}\,dy\\\\
&=\frac1\pi \left(\frac{(x-1)}{(x-1)^2+y^2}-\frac{(x+1)}{(x+1)^2+y^2}\right)\tag2
\end{align}$$
Integrating with respect to $y$, we find
$$\begin{align}
V(x,y)&=\frac1\pi \left(\arctan\left(\frac{y}{x-1}\right)-\arctan\left(\frac{y}{x+1}\right) \right)\\\\
&=\frac1\pi \left(\arctan\left(\frac{x+1}{y}\right)-\arctan\left(\frac{x-1}{y}\right)\right)
\end{align}$$
And we are done!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Login to WordPress with a Link I have a Wordpress site that authenticates against our school's web-based database system. All users have one set of login credentials set by the system. If you wanted to get in to both systems, while the user/pass is the same, you have to log in to each system individually.
What I'd like is for all of the users log in to our database first. Within the page I want to post a link to subscriber-only portions of WP. Since our database knows the user's credentials I was thinking that we could format a link to can automatically log them in.
Is this possible to do and if so, how?
Also, is this a secure way of saving the user from having to log in again (assuming that the authenticating link is behind a secure portal)?

A: You're describing a single-sign-on solution. There are several good options out there, but they all use the same basic techniques.
Since you already have a PHP environment with your wordpress installation, the easiest would probably be SAML using simplesamlPHP.
You would set it up as an Identity Provider and point it to your database of users (might require some tweaking depending on how passwords are encrypted, but if you were able to get Wordpress to use it somehow, then it should be possible)
Both your Wordpress site and your "database" (another web app I'm assuming?) would then basically trust the Identity Provider to authenticate users. The process might look a bit different to users, as they would authenticate using a new login form. You could use this plugin for WP, and I'm sure there are others.
The tricky one might be the other app. Unless it's based on some popular framework, you might have to do some coding to get it to work. SimpleSAMLphp can help you with that again - read up on Service Providers.


text:
Q: How to get CPU usage on a multi core system How to know the CPU usage in percentage on multi core system. I tried the below sample code using os npm but it does not return the result what I am actually looking into it. I am expecting the result something similar to linux top command. Any help on this will be helpful.
setInterval(function() {

    os.cpuUsage(function(v){
        console.log( 'CPU Usage (%): ' + v );
    });

}, 1000 );

A: Package os-utils is only an API to get some data from the system, you should build your interface using it to obtain something like a top command in Linux.
Instead if you want something ready to be used you can take a look at vtop package that does exactly what you need.
sudo npm install -g vtop

vtop


text:
Q: Is there altitude limit for GSM(SIM908)? I'm using GSM(SIM908) in the machine. I need to know whether there is an altitude limit for gsm to operate. Does GSM just stops working after reaching certain height? I will use SIM908 or SIM808.

A: I often have cell service at 25,000 feet. I have also launched a weather balloon with a GSM tracker and depending on your antenna, you could have service as high as 30k-40k feet. Maybe much higher depending on many variables such as humidity, antenna shape and type, cell tower position and power, local transceiver power, and your circuitry that interprets the signal. I would say 30,000 feet is very doable based on my experiences.


text:
Q: java.lang.IllegalStateException: Component ID has already been found in the view I am getting the "java.lang.IllegalStateException: Component ID  has already been found in the view" exception under certain circumstances and I do not understand why.
I have the following page where I am using a composite component four times, and there is a corresponding output text used to display the result of each:
<h:form id="aCrazyTestForm"">

   <my:jqueryautocomplete values="#{jqueryAutoCompleteBean.carListJson}" selectedValue="#{jqueryAutoCompleteBean.selectedCarOne}" field="make">
                <f:ajax execute=":aCrazyTestForm:completeOne" render=":aCrazyTestForm:completeOne" event="tagSelectedEvent" listener="#{jqueryAutoCompleteBean.selectedCarOne}" />
            </my:jqueryautocomplete>

            <h:outputText id="completeOne" value="#{jqueryAutoCompleteBean.selectedCarOne}" />

            <my:jqueryautocomplete values="#{jqueryAutoCompleteBean.carListJson}" selectedValue="#{jqueryAutoCompleteBean.selectedCarTwo}" field="make">
                <f:ajax execute=":aCrazyTestForm:completeTwo" render=":aCrazyTestForm:completeTwo" event="tagSelectedEvent" listener="#{jqueryAutoCompleteBean.selectedCarTwo}" />
            </my:jqueryautocomplete>

            <h:outputText id="completeTwo" value="#{jqueryAutoCompleteBean.selectedCarTwo}" />

            <my:jqueryautocomplete values="#{jqueryAutoCompleteBean.carListJson}" selectedValue="#{jqueryAutoCompleteBean.selectedCarThree}" field="make">
                <f:ajax  execute=":aCrazyTestForm:completeThree" render=":aCrazyTestForm:completeThree" event="tagSelectedEvent" listener="#{jqueryAutoCompleteBean.selectedCarThree}" />
            </my:jqueryautocomplete>

            <h:outputText id="completeThree" value="#{jqueryAutoCompleteBean.selectedCarThree}" />

            <my:jqueryautocomplete values="#{jqueryAutoCompleteBean.carListJson}" selectedValue="#{jqueryAutoCompleteBean.selectedCarFour}" field="make">
                <f:ajax  execute=":aCrazyTestForm:completeFour" render=":aCrazyTestForm:completeFour" event="tagSelectedEvent" listener="#{jqueryAutoCompleteBean.selectedCarFour}" />
            </my:jqueryautocomplete>

            <h:outputText id="completeFour" value="#{jqueryAutoCompleteBean.selectedCarFour}" />

</h:form>

My composite component implementation is wrapped in a span with id = "#{cc.clientId}"
I only encounter this error if I populate the form's id.If I set the form prependId="false", then I do not get the error.
With the below code I get the error:
"Unhandled Faces error: Component ID aCrazyTestForm:j_idt15 has already been found in the view". In the following snippet you can see that this is actually the id of my custom component.
<JqueryAutoComplete id="j_idt15" immediate="false" inView="true" localValueSet="false" rendered="true" required="false" transient="false" valid="true">

I thought that wrapping the composite component's implementation in a span with id="#{cc.clientId}" ensures that my component gets a unique identifier wherever it is used?

A: JSF can become confused at times with repeating elements, especially with a number of elements that repeat.  Could you try setting IDs for each my:jqueryautocomplete tag and see if the problem persists?


text:
Q: pthread_create and pthread_join for some simple functions I'm currently completing an assignment that involves using multithreading and multiprocess programming for the absolute first time. I seem to have stumbled through multiprocess programming and accidentally increased performance by around ~20% but I can't tell you that I understand it. Unfortunately I haven't even gotten lucky enough to figure out pthreads completely yet, and I am almost at a loss as to how this actually works. Without further ado, here is the code I'm trying to split correctly.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <errno.h>
#include <sys/time.h>

#define DATASIZE (4<<20)

int main()
{
double A[200][200];
double B[200][200];
double C[200][200];
int i, j, k, m;
int outfile, result, count;
unsigned seed;

struct timeval before, after;

char *buff;

buff = (char *)malloc(sizeof(char)*(16<<20));

srandom(seed);

for (i=0; i<200; i++)
for (j=0; j<200; j++) {
    A[i][j] = random()/100.0;
    B[i][j] = random()/100.0;
}

gettimeofday(&before, NULL);
for (m=0 ; m < 100; m++) {
/* Computation */
/* This is what we're trying to split into one thread*/
for (i=0; i<200; i++)
    for (j=0; j<200; j++) {
    C[i][j] = 0;
    for (k=0; k<200; k++)
        C[i][j] += A[i][k]*B[k][j];
    }

/* I/O */
/*And this is what we'll put in the other thread*/
outfile = open("testfile", O_RDWR|O_CREAT|O_APPEND, 0777);
if (outfile <= 0)
    perror("Error opening file\n");
else {
    result = write(outfile, buff, DATASIZE);
    if (result <= 0)
    perror("Error writing file\n");
}
close(outfile);
}
free(buff);
gettimeofday(&after, NULL);

count = (after.tv_sec - before.tv_sec) * 1e6;
count += (after.tv_usec - before.tv_usec);

printf("Total time for single process in usec: %d\n", count);
return 0;
};

From the few unhelpful examples I've gleamed from the internet, they show splitting these two things into external functions outside the main function. Then I'd have to pass them into pthread_create like so:
/*I would declare the pthread_t* vars higher in the code*/
pthread_create(pthread_t* first,NULL,/*function name*/,NULL);
pthread_create(pthread_t* second,NULL,/*second function name*/,NULL);
pthread_join(pthread_t* first,NULL);
pthread_join(pthread_t* second,NULL);

Is it really this "simple"? Am I required to create new external functions or can I somehow keep them in main and use pthread? Am I missing some important part of understanding how pthread works and how to use it in the future?

A: Am I required to create new external functions or can I somehow keep them in main and use pthread?
Yes, pthread_create() creates new thread within the calling process that starts execution by invoking start_routine() specified by 3. argument of this function: void *(*start_routine) (void *).
Is it really this "simple"?
Yes, it is.


text:
Q: Closing a pipe invalidates DLL's stdout handle I'm calling a function from an external DLL, which writes its output to stdout. In order to capture the output, I created a monitoring thread where I redirect the stdout to a pipe using CreatePipe and SetStdHandle (code below). The problem is that this code only works once. If executed more than once, the DLL throws and "Invalid Handle" exception when it tries to output something. I narrowed it down to the CloseHandle(PipeWrite) line. If I comment it out, it starts working as intended. Why does closing this pipe permanently invalidate DLL's stdout handle?
const
  SecConst: TSecurityAttributes = (nLength: SizeOf(TSecurityAttributes); bInheritHandle: true);
var
  Security: TSecurityAttributes;
  hStdOld, PipeRead, PipeWrite: THandle;
begin
  Security := SecConst;
  CreatePipe(PipeRead, PipeWrite, @Security, 0);
  hStdOld := GetStdHandle(STD_OUTPUT_HANDLE);
  SetStdHandle(STD_OUTPUT_HANDLE, PipeWrite);

  while not Terminated do
  begin
    if ReadPipe(PipeRead, FOutput) > 0 then
    begin
      Synchronize(SendOutput);
    end;

  end;
  SetStdHandle(STD_OUTPUT_HANDLE, hStdOld);
  CloseHandle(PipeRead);
  CloseHandle(PipeWrite); //problematic call
end;


text:
Q: Chrome, how to get element css style url() from chrome Dev Tools For example:

I try to click the right mouse button on filter parameters and select: "Open in new tab"

I can get this URL.
I searched for the keyword #goo in this URL, but it still unable to solve the filter parameters:

This URL does not describe the contents of the filter parameters, just to list the same style code as on the web page:

Example web URL.


text:
Q: How to write to file in test in Flutter? I want to test a function that resize an image.
import 'dart:io';

import 'package:image/image.dart' as img;
import 'package:path_provider/path_provider.dart';

static Future<File?> resizeImage({required File imageFile, int? width, int? height}) async {
    final img.Image? inputImage = img.decodeImage(imageFile.readAsBytesSync());

    if (inputImage != null) {
      final outputImage = img.copyResize(inputImage, width: width, height: height);

      final String localPath = await getLocalPath();
      final File outputImageFile = File('$localPath/resizedImage.png')..writeAsBytesSync(img.encodePng(outputImage));

      return outputImageFile;
    }
  }

Then in test:
const String kApplicationSupportPath = 'applicationSupportPath';

class FakePathProviderPlatform extends Fake
    with MockPlatformInterfaceMixin
    implements PathProviderPlatform {

  @override
  Future<String?> getApplicationSupportPath() async {
    return kApplicationSupportPath;
  }
}

setUp(() async {
    TestWidgetsFlutterBinding.ensureInitialized();
    PathProviderPlatform.instance = FakePathProviderPlatform();
  });

test(
    'given 3000x4000 pixel file - resize to max allowed with & height - verify size restrictions',
    () async {
      const int maxWith = 2160;
      const int maxHeight = 1440;

      const String assetPath = 'assets/test_image_gradient_black_white_3000x4000.png';
      final File imageFile = File(assetPath);

      final File resizedImageFile = await ImageUtils.resizeImage(
        imageFile: imageFile,
        maxWidth: maxWith,
        maxHeight: maxHeight,
      );
      final int width = ImageUtils.getWidth(resizedImageFile);
      final int height = ImageUtils.getHeight(resizedImageFile);

      expect(width <= maxWith, true);
      expect(height <= maxHeight, true);
    },
  );

I get the following error:

FileSystemException: Cannot open file, path = 'applicationSupportPath/resizedImage.png' (OS Error: No such file or directory, errno = 2)

How can I mock path provider so that I can actually write to the path?


text:
Q: NSAttributedString background color is not solid when other attributes are applied I want to make several changes to UILabel text style by using NSAttributedString:

*

*Part of the string must have a solid backgroundColor;

*Some parts of the string must have a different font;

*Some parts of the string must have a different foregroundColor;

But when i made these changes, i ran into the problem that backgroundColor has some spacing (vertical lines in the image) between (i think) other attributes (font/foregroundColor).

(See the full size image)
How can i fixed that?
Swift Playground code:
import PlaygroundSupport
import UIKit

let label = UILabel()
label.backgroundColor = .black
let text = "Hello + World!"
let nsText = NSString(string: text)

let attributedString = NSMutableAttributedString(string: text)

attributedString.addAttribute(.backgroundColor, value: UIColor.systemCyan, range: nsText.range(of: "Hello + Wo"))

attributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 100.0), range: nsText.range(of: "Hello"))

attributedString.addAttribute(.foregroundColor, value: UIColor.systemPurple, range: nsText.range(of: " + "))
attributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 80.0), range: nsText.range(of: " + "))

attributedString.addAttribute(.foregroundColor, value: UIColor.white, range: nsText.range(of: "World!"))
attributedString.addAttribute(.font, value: UIFont.systemFont(ofSize: 44.0), range: nsText.range(of: "World!"))

label.attributedText = attributedString
label.sizeToFit()

PlaygroundPage.current.liveView = label

A: There is an attribute called expansion that adjusts the font's expansion factor using a float value. The problem only occurs where two ranges with different font sizes meet, and this is a graphical rendering issue that cannot be overridden. But if you explicitly zero out the expansion factor, or even apply a small negative value, the gaps will not be noticeable.
attributedString.addAttribute(.expansion, value: NSNumber(value: 0), range: nsText.range(of: "Hello + World!"))

https://developer.apple.com/documentation/foundation/nsattributedstring/key/1524652-expansion?language=objc__5


text:
Q: Error on big numbers agregattion Using Apache Spark 2.0.2 I have a table stored as parquet which contains about 23 millions rows and about 300 columns. I have a column called total_price stored as double, if I execute:
select sum(total_price) from my_table;

+-----------------+
|   total_price   |
+-----------------+
|   9.3923769592E8|
+-----------------+

So this number 9.3923769592E8 is wrong.
but if I execute:
select year, sum(total_price) from my_table;

+-------+------------------------+
|   year|             total_price|
+-------+------------------------+
|   2017|  44510982.10004025     |
|   2016| 293320440.63992333     |
|   2015| 311512575.890131       |
|   2014| 289885757.2799143      |
|   2013|      5192.319          |
|   2012|      2747.7000000000007|
+-------+------------------------+

My assumption is that on the first query the double data type has an overflow or something like it.

*

*Why I'm getting the result with so many decimals after the dot if they are stored as #.##?

*How can I fix the error of the first query?

A: The value you get looks just fine - 9.3923769592E8 is roughly ~939,237,695 and more or less what you expect based on the numbers aggregated by year.
Regarding the values you get you have to remember that only some numbers are representable using floating point arithmetics and commonly used types, like Scala Double or Float, are not suitable for use cases where exact values are necessary (accounting for example). For application like this you should use DecimalType.
I would also recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic and Is floating point math broken?


text:
Q: Is it possible that the Execute SQL Statement simultaneously works with SQL Statement and with Variables Is it possible to design the Execute SQL Task such that when it reads from SQL's database ,  task A executed and when it reads from variables , task B executed? It means that the Execute SQL Task simultaneously works with SQL Statement and with Variables .

A: So you want the SqlStatementSource property of an Execute SQL task to be set at runtime depending on whether you retrieve a value from a SQL database. If no value is retrieved, you want it set to a pre-existing variable's value.

*

*Create an Execute SQL task to retrieve your SQL Database value
and assign it to variable DatabaseSQL. I'm assuming your query will return NULL if no value is found.

*Assign your default value to variable DefaultSQL.

*In your Execute SQL task, create an Expression for the
SqlStatementSource property and set the expression to
REPLACENULL(@User::DatabaseSQL, @User::DefaultSQL)


text:
Q: Highlight and autocomplete code inside custom tags as PHP I have php file. And I have php code inside custom tags:
[[MYKEYWORD
    $x  = 1;
    $y = 2;
    $z = $x + $y;
    echo $z;
]]

or
[[
    $x  = 1; $y = 2; $z = $x + $y;
    echo $z;
]]

For the moment PhpStorm defines it as plain text, but I need PhpStorm to highlight and autocomplete code inside these tags as php code.
How do I do that?


text:
Q: Deploying application in Jboss AS 7.1 with JDK 7 getting Error as "MSC00001: Failed to start service jboss.web.deployment.default-host./" 08:49:26,415 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-4) MSC00001: Failed to start service jboss.web.deployment.default-host./: org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./: Failed to start service
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1767) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
Caused by: java.lang.IllegalArgumentException: Child container with name  already exists
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:804)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:792)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:356)
    at org.jboss.as.web.deployment.WebContextInjector.inject(WebContextInjector.java:62)
    at org.jboss.as.web.deployment.WebContextInjector.inject(WebContextInjector.java:38)
    at org.jboss.msc.inject.CastingInjector.inject(CastingInjector.java:55) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl.doInject(ServiceControllerImpl.java:1549) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl.access$1900(ServiceControllerImpl.java:49) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.performInjections(ServiceControllerImpl.java:1780) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1741) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
    ... 3 more

08:49:26,631 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "SampleApp.war" was rolled back with failure message {"JBAS014671: Failed services" => {"jboss.web.deployment.default-host./" => "org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./: Failed to start service"}}
08:49:26,706 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015877: Stopped deployment SampleApp.war in 75ms
08:49:26,707 INFO  [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report
JBAS014777:   Services which failed to start:      service jboss.web.deployment.default-host./: org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./: Failed to start service

08:49:26,709 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.web.deployment.default-host./" => "org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./: Failed to start service"}}}}

A: The issue was resolved. Thanks Aaron and James.  Added in jboss-web.xml file
/ which resolved the issue.


text:
Q: autocomplete dropdown test with ruby (watir) i'm trying to create watir test that fills inn a textfield by writing feks
"lon" and waiting till the dropdown is triggered and then clicking on the first element in the list.
Writing "lon" should trigger many options like "London, England, Storbritannia", London, Kentucky, USA and etc.
Is it somehow possible to this with watir??
thnx in advance.
This is what my code looks like until now,
it odes not work though and i'm wondering where i have missed something.
def test_scriptflight_autocomplete
    @site.navigate_to(:travel, :flight)
     from_field = @site.ie.text_field(:id, "locOriginName")
    to_field   = @site.ie.text_field(:id, 'locDestinationName')
    from_field.set('oslo')
# need to fire a key press event after setting the text since the js is handling
# trigger the autocomplete (requires a 'keydown')
from_field.fire_event('onkeydown')

# wait until the autocomplete gets populated with the AJAX call
@site.ie.wait_until{@site.ie.div(:id, 'onlinesearch').lis.length > 0}
puts @site.ie.div(:id, 'locOriginName ').lis.length
puts @site.ie.div(:id, 'locOriginName').li(:index, 5).text

# find the li you want to select in the autocomplete list and click it
@site.ie.div(:id, 'from-field').li(:text, 'Oslo, Oslo, Norge').click

end

A: Me and a colleague(Magnar) at work found this blog that helped us to find the answer i was looking for.
http://blog.saush.com/2008/05/using-rspec-and-watir-for-functional-testing-in-web-applications/
class Watir::IE
    def fire_keydown_on(element_id, key)
        ie.Document.parentWindow.execScript("key = document.createEventObject(); key.keyCode = #{key}")
        ie.Document.parentWindow.execScript("document.getElementById('#{element_id}').fireEvent('onkeydown', key)")
    end
end

From the Blog:
We just added a new method 'fire_keydown_on' for the IE class, which takes in the element id, and the key. This method calls Javascript to create an event object (this only works in IE, by the way) and sets the key code to be '13′, which is the carriage-return key (the enter key). The it calls Javascript to get the HTML element (using the element id) and fire the 'onkeydown' event on it, while passing on the event object it just created.


text:
Q: Loading XAML at runtime? First some background: I'm working on an application and I'm trying to follow MVVM conventions writing it. One thing I'd like to do is to be able to give the application different "skins" to my application. The same application, but show one "skin" for one client and a different "skin" for another.
And so my questions are:
1. Is it possible to load a xaml file at run time and "assign" it to my app?
2. Can the xaml file be an external file residing in a different folder?
3. Can the application switch to another xaml file easily, or only at startup time?
So where should I start looking at for information on this? Which WPF methods, if they exist, handle this functionality?
Thanks!
Edit: the type of "skinning" I'm wanting to do is more than just changing the look of my controls. The idea is having a completely different UI. Different buttons, different layouts. Kinda like how one version of the app would be fully featured for experts and another version would be simplified for beginners.

A: I made simple markup extension, which loads xaml:
public class DynamicXamlLoader : MarkupExtension
{
    public DynamicXamlLoader() { }

    public DynamicXamlLoader(string xamlFileName)
    {
        XamlFileName = xamlFileName;
    }

    public string XamlFileName { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var provideValue = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
        if (provideValue == null || provideValue.TargetObject == null) return null;

        // get target
        var targetObject = provideValue.TargetObject as UIElement;
        if (targetObject == null) return null;

        // get xaml file
        var xamlFile = new DirectoryInfo(Directory.GetCurrentDirectory())
            .GetFiles(XamlFileName ?? GenerateXamlName(targetObject), SearchOption.AllDirectories)
            .FirstOrDefault();

        if (xamlFile == null) return null;

        // load xaml
        using (var reader = new StreamReader(xamlFile.FullName))
            return XamlReader.Load(reader.BaseStream) as UIElement;
    }

    private static string GenerateXamlName(UIElement targetObject)
    {
        return string.Concat(targetObject.GetType().Name, ".xaml");
    }
}

Usage:
This find and load MyFirstView.xaml file
<ContentControl Content="{wpf:DynamicXamlLoader XamlFileName=MyFirstView.xaml}" />

And this fill whole UserControl (find and load MySecondView.xaml file)
<UserControl x:Class="MySecondView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Content="{wpf:DynamicXamlLoader}" />

A: You can load any XAML that you want using XamlReader.Load.
If you style all your controls in your application and define those styles in your applications resource dictionary you can load new styles defined in XAML somewhere else using XamlReader.Load and replace parts of your resource dictionary with the loaded XAML.  Your controls will change appearance accordingly.

A: I have done loading XAML at runtime, here is a short example
Grid grd = new Grid();
var grdEncoding = new ASCIIEncoding();
var grdBytes = grdEncoding.GetBytes(myXAML);
grd = (Grid)XamlReader.Load(new MemoryStream(grdBytes));
Grid.SetColumn(grd, 0);
Grid.SetRow(grd, 0);
parentGrid.Children.Add(grd);

private String myXAML = @" <Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Margin='30 10 30 65' VerticalAlignment='Bottom'>" +
                    "<Label Content='Date: 1-Feb-2013' FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Left'/>" +
                    "<Label Content='4'  FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Center'/>" +
                    "<Label Content='Hello World'  FontFamily='Arial' FontSize='12' Foreground='#666666' HorizontalAlignment='Right'/>" +
                "</Grid>";

A: As Jakob Christensen noted, you can load any XAML you want using XamlReader.Load. This doesn't apply only for styles, but UIElements as well. You just load the XAML like:
UIElement rootElement;
FileStream s = new FileStream(fileName, FileMode.Open);
rootElement = (UIElement)XamlReader.Load(s);
s.Close();

Then you can set it as the contents of the suitable element, e.g. for
<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Foo Bar">
    <Grid x:Name="layoutGrid">
        <!-- any static elements you might have -->
    </Grid>
</Window>

you could add the rootElement in the grid with:
layoutGrid.Children.Add(rootElement);
layoutGrid.SetColumn(rootElement, COLUMN);
layoutGrid.SetRow(rootElement, ROW);

You'll naturally also have to connect any events for elements inside the rootElement manually in the code-behind. As an example, assuming your rootElement contains a Canvas with a bunch of Paths, you can assign the Paths' MouseLeftButtonDown event like this:
Canvas canvas = (Canvas)LogicalTreeHelper.FindLogicalNode(rootElement, "canvas1");
foreach (UIElement ui in LogicalTreeHelper.GetChildren(canvas)) {
    System.Windows.Shapes.Path path = ui as System.Windows.Shapes.Path;
    if (path != null) {
        path.MouseLeftButtonDown += this.LeftButtonDown;
    }
}

I've not tried switching XAML files on the fly, so I cannot say if that'll really work or not.

A: I think this is fairly simple with the XamlReader, give this a shot, didn't try it myself, but I think it should work.
https://learn.microsoft.com/en-us/archive/blogs/ashish/dynamically-loading-xaml

A: As it's already mentioned in other answers, you can use XamlReader.Load.
If you are looking for a more straightforward example, here is an example showing how easily you can create a control from a string variable containing the XAML:
public T LoadXaml<T>(string xaml)
{
    using (var stringReader = new System.IO.StringReader(xaml))
    using (var xmlReader = System.Xml.XmlReader.Create(stringReader))
        return (T)System.Windows.Markup.XamlReader.Load(xmlReader);
}

And as the usage:
var xaml = "<TextBox xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation\'>" +
            "Lorm ipsum dolor sit amet." +
            "</TextBox>";
var textBox = LoadXaml<System.Windows.Controls.TextBox>(xaml);


text:
Q: cURL command with parameters returned by python -c "python code here" command I have this command
curl http://localhost:6800/schedule.json | python -c "import json; print (' '.join(['-d '+key+'='+word for key,word in json.load(open('cron_parameters_testing.json')).items() ] ))"

actually the python command reads parameters from JSON file like this
{
'project' : 'default'
}
and returns the output as -d project=default
I have separately tested python -c "import json; print (' '.join(['-d '+key+'='+word for key,word in json.load(open('cron_parameters_testing.json')).items() ] )) command it works perfectly but it does work with the cURL
my final command that I want to run is
curl http://localhost:6800/schedule.json -d project=default
of course I want -d project=default to be generated from command I mentioned

A: | is a pipe, in your case it sends standard output from curl to become the standard input to python. This seems unrelated to your task. Try:
curl http://localhost:6800/schedule.json `python -c "import json; print (' '.join(['-d '+key+'='+word for key,word in json.load(open('cron_parameters_testing.json')).items() ] ))"`

The backticks (`...`) evaluate the command inside and get substituted with the output of the command. Alternatively you can use $(...), especially if you need to nest commands like this.


text:
Q: Segregate elements of a string output My C# output is in the form:
Epoch Timestamp1,Cost1,Epoch Timestamp2,Cost2,Epoch Timestamp3,Cost3.

(Costn is the cost for Epoch TImestampn.)
I want to get the cost for each timestamp, in the below manner:
timestamp cost
timestamp cost
..
..
..

I am implementing this in C# in Visual Studio 2017.
How can I implement this? Any ideas please?
Thank you.

A: Just use Split and a for loop, add pepper and salt to taste
var input = "Epoch Timestamp1,Cost1,Epoch Timestamp2,Cost2,Epoch Timestamp3,Cost3.";

var split = input.Split(',');
var results = new List<string>();

for (int i = 0; i < split.Length; i+=2)
   results.Add(split[i] + " " + split[i + 1]);

foreach (var item in results)
   Console.WriteLine(item);

See it in action here


text:
Q: why pop over display all time in angular? I make a pop over using directive .But my popover display all time when i generate row dynamically .I need to show popover or tool only on  icon click ?
Now it is display without click and also display oll rows .i want to display only that row which is clicked?
Here is plunker
http://plnkr.co/edit/OYiawflIBnpJ1PKx02LG?p=preview
app.directive('popUpCheck', function() {
  return {
    restrict: 'A',
    templateUrl: 'pop.html',
    link: function (scope, el, attrs) {
            scope.label = attrs.popoverLabel;
            $(el).popover({
                trigger: 'click',
                html: true,
                placement: 'right'
            });
        }
  }
});

Here is my html

        {{guitar.color}}

        {{guitar.value}}

A: From the console your first problem is that there is no jquery and bootstrap-ui doesn't use jquery. So calling $(el).popover is never going to work.
I'd recommend looking at the docs for bootstrap-ui popover here http://angular-ui.github.io/bootstrap/#/popover. If you need the custom wrapper then there should be docs somewhere on the site for using it from javascript.


text:
Q: How to override newAccount function Of EMailNotification Model in magento2 I want to apply a condition for new customer registration email based on user type, for that I applied some condition In new account function and its working fine in my core model but how can I Override that function in my custom module?
here is my code:
etc/frontend/di.xml:
 <preference for="Magento\Customer\Model\EmailNotification" type="Namespace\Mymodule\Model\EmailNotification" />

EmailNotification.php :
public function newAccount(
    CustomerInterface $customer,
    $type = self::NEW_ACCOUNT_EMAIL_REGISTERED,
    $backUrl = '',
    $storeId = 0,
    $sendemailStoreId = null
    ) {
        $types = self::TEMPLATE_TYPES;

        if (!isset($types[$type])) {
            throw new LocalizedException(
            __('The transactional account email type is incorrect. Verify and try again.')
            );
        }

        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer, $sendemailStoreId);
        }

        $store = $this->storeManager->getStore($customer->getStoreId());

        $customerEmailData = $this->getFullCustomerObject($customer);

      //add my custom condition here:
        $userType = $customer->getCustomAttribute('user_type')->getValue();
        if($userType == 2){
            $this->sendEmailTemplate(
            $customer,
            $types[$type],
            self::XML_PATH_REGISTER_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'back_url' => $backUrl, 'store' => $store],
            $storeId
            );
        }

    }

A: Check below code
create di.xml file in custom module

File:-Vendor/Module/etc/frontend/di.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <preference for="Magento\Customer\Model\EmailNotification" type="Vendor\Module\Model\EmailNotification"/>

</config>

Then create the EmailNotification.php file in the module.

File:-Vendor/Module/Model/EmailNotification.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Customer\Helper\View as CustomerViewHelper;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Customer\Model\EmailNotificationInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Framework\Exception\LocalizedException;
/**
 * Customer email notification
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class EmailNotification implements EmailNotificationInterface
{
    /**#@+
     * Configuration paths for email templates and identities
     */
    const XML_PATH_FORGOT_EMAIL_IDENTITY = 'customer/password/forgot_email_identity';

    const XML_PATH_RESET_PASSWORD_TEMPLATE = 'customer/password/reset_password_template';

    const XML_PATH_CHANGE_EMAIL_TEMPLATE = 'customer/account_information/change_email_template';

    const XML_PATH_CHANGE_EMAIL_AND_PASSWORD_TEMPLATE =
        'customer/account_information/change_email_and_password_template';

    const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'customer/password/forgot_email_template';

    const XML_PATH_REMIND_EMAIL_TEMPLATE = 'customer/password/remind_email_template';

    const XML_PATH_REGISTER_EMAIL_IDENTITY = 'customer/create_account/email_identity';

    const XML_PATH_REGISTER_EMAIL_TEMPLATE = 'customer/create_account/email_template';

    const XML_PATH_REGISTER_NO_PASSWORD_EMAIL_TEMPLATE = 'customer/create_account/email_no_password_template';

    const XML_PATH_CONFIRM_EMAIL_TEMPLATE = 'customer/create_account/email_confirmation_template';

    const XML_PATH_CONFIRMED_EMAIL_TEMPLATE = 'customer/create_account/email_confirmed_template';

    /**
     * self::NEW_ACCOUNT_EMAIL_REGISTERED               welcome email, when confirmation is disabled
     *                                                  and password is set
     * self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD   welcome email, when confirmation is disabled
     *                                                  and password is not set
     * self::NEW_ACCOUNT_EMAIL_CONFIRMED                welcome email, when confirmation is enabled
     *                                                  and password is set
     * self::NEW_ACCOUNT_EMAIL_CONFIRMATION             email with confirmation link
     */
    const TEMPLATE_TYPES = [
        self::NEW_ACCOUNT_EMAIL_REGISTERED => self::XML_PATH_REGISTER_EMAIL_TEMPLATE,
        self::NEW_ACCOUNT_EMAIL_REGISTERED_NO_PASSWORD => self::XML_PATH_REGISTER_NO_PASSWORD_EMAIL_TEMPLATE,
        self::NEW_ACCOUNT_EMAIL_CONFIRMED => self::XML_PATH_CONFIRMED_EMAIL_TEMPLATE,
        self::NEW_ACCOUNT_EMAIL_CONFIRMATION => self::XML_PATH_CONFIRM_EMAIL_TEMPLATE,
    ];

    /**#@-*/

    /**#@-*/
    private $customerRegistry;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var TransportBuilder
     */
    private $transportBuilder;

    /**
     * @var CustomerViewHelper
     */
    protected $customerViewHelper;

    /**
     * @var DataObjectProcessor
     */
    protected $dataProcessor;

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var SenderResolverInterface
     */
    private $senderResolver;

    /**
     * @param CustomerRegistry $customerRegistry
     * @param StoreManagerInterface $storeManager
     * @param TransportBuilder $transportBuilder
     * @param CustomerViewHelper $customerViewHelper
     * @param DataObjectProcessor $dataProcessor
     * @param ScopeConfigInterface $scopeConfig
     * @param SenderResolverInterface|null $senderResolver
     */
    public function __construct(
        CustomerRegistry $customerRegistry,
        StoreManagerInterface $storeManager,
        TransportBuilder $transportBuilder,
        CustomerViewHelper $customerViewHelper,
        DataObjectProcessor $dataProcessor,
        ScopeConfigInterface $scopeConfig,
        SenderResolverInterface $senderResolver = null
    ) {
        $this->customerRegistry = $customerRegistry;
        $this->storeManager = $storeManager;
        $this->transportBuilder = $transportBuilder;
        $this->customerViewHelper = $customerViewHelper;
        $this->dataProcessor = $dataProcessor;
        $this->scopeConfig = $scopeConfig;
        $this->senderResolver = $senderResolver ?: ObjectManager::getInstance()->get(SenderResolverInterface::class);
    }

    /**
     * Send notification to customer when email or/and password changed
     *
     * @param CustomerInterface $savedCustomer
     * @param string $origCustomerEmail
     * @param bool $isPasswordChanged
     * @return void
     */
    public function credentialsChanged(
        CustomerInterface $savedCustomer,
        $origCustomerEmail,
        $isPasswordChanged = false
    ) {
        if ($origCustomerEmail != $savedCustomer->getEmail()) {
            if ($isPasswordChanged) {
                $this->emailAndPasswordChanged($savedCustomer, $origCustomerEmail);
                $this->emailAndPasswordChanged($savedCustomer, $savedCustomer->getEmail());
                return;
            }

            $this->emailChanged($savedCustomer, $origCustomerEmail);
            $this->emailChanged($savedCustomer, $savedCustomer->getEmail());
            return;
        }

        if ($isPasswordChanged) {
            $this->passwordReset($savedCustomer);
        }
    }

    /**
     * Send email to customer when his email and password is changed
     *
     * @param CustomerInterface $customer
     * @param string $email
     * @return void
     */
    private function emailAndPasswordChanged(CustomerInterface $customer, $email)
    {
        $storeId = $customer->getStoreId();
        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer);
        }

        $customerEmailData = $this->getFullCustomerObject($customer);

        $this->sendEmailTemplate(
            $customer,
            self::XML_PATH_CHANGE_EMAIL_AND_PASSWORD_TEMPLATE,
            self::XML_PATH_FORGOT_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
            $storeId,
            $email
        );
    }

    /**
     * Send email to customer when his email is changed
     *
     * @param CustomerInterface $customer
     * @param string $email
     * @return void
     */
    private function emailChanged(CustomerInterface $customer, $email)
    {
        $storeId = $customer->getStoreId();
        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer);
        }

        $customerEmailData = $this->getFullCustomerObject($customer);

        $this->sendEmailTemplate(
            $customer,
            self::XML_PATH_CHANGE_EMAIL_TEMPLATE,
            self::XML_PATH_FORGOT_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
            $storeId,
            $email
        );
    }

    /**
     * Send email to customer when his password is reset
     *
     * @param CustomerInterface $customer
     * @return void
     */
    private function passwordReset(CustomerInterface $customer)
    {
        $storeId = $customer->getStoreId();
        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer);
        }

        $customerEmailData = $this->getFullCustomerObject($customer);

        $this->sendEmailTemplate(
            $customer,
            self::XML_PATH_RESET_PASSWORD_TEMPLATE,
            self::XML_PATH_FORGOT_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
            $storeId
        );
    }

    /**
     * Send corresponding email template
     *
     * @param CustomerInterface $customer
     * @param string $template configuration path of email template
     * @param string $sender configuration path of email identity
     * @param array $templateParams
     * @param int|null $storeId
     * @param string $email
     * @return void
     * @throws \Magento\Framework\Exception\MailException
     */
    private function sendEmailTemplate(
        $customer,
        $template,
        $sender,
        $templateParams = [],
        $storeId = null,
        $email = null
    ) {
        $templateId = $this->scopeConfig->getValue($template, 'store', $storeId);
        if ($email === null) {
            $email = $customer->getEmail();
        }

        /** @var array $from */
        $from = $this->senderResolver->resolve(
            $this->scopeConfig->getValue($sender, 'store', $storeId),
            $storeId
        );

        $transport = $this->transportBuilder->setTemplateIdentifier($templateId)
            ->setTemplateOptions(['area' => 'frontend', 'store' => $storeId])
            ->setTemplateVars($templateParams)
            ->setFrom($from)
            ->addTo($email, $this->customerViewHelper->getCustomerName($customer))
            ->getTransport();

        $transport->sendMessage();
    }

    /**
     * Create an object with data merged from Customer and CustomerSecure
     *
     * @param CustomerInterface $customer
     * @return \Magento\Customer\Model\Data\CustomerSecure
     */
    private function getFullCustomerObject($customer)
    {
        // No need to flatten the custom attributes or nested objects since the only usage is for email templates and
        // object passed for events
        $mergedCustomerData = $this->customerRegistry->retrieveSecureData($customer->getId());
        $customerData = $this->dataProcessor
            ->buildOutputDataArray($customer, \Magento\Customer\Api\Data\CustomerInterface::class);
        $mergedCustomerData->addData($customerData);
        $mergedCustomerData->setData('name', $this->customerViewHelper->getCustomerName($customer));
        return $mergedCustomerData;
    }

    /**
     * Get either first store ID from a set website or the provided as default
     *
     * @param CustomerInterface $customer
     * @param int|string|null $defaultStoreId
     * @return int
     */
    private function getWebsiteStoreId($customer, $defaultStoreId = null)
    {
        if ($customer->getWebsiteId() != 0 && empty($defaultStoreId)) {
            $storeIds = $this->storeManager->getWebsite($customer->getWebsiteId())->getStoreIds();
            $defaultStoreId = reset($storeIds);
        }
        return $defaultStoreId;
    }

    /**
     * Send email with new customer password
     *
     * @param CustomerInterface $customer
     * @return void
     */
    public function passwordReminder(CustomerInterface $customer)
    {
        $storeId = $customer->getStoreId();
        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer);
        }

        $customerEmailData = $this->getFullCustomerObject($customer);

        $this->sendEmailTemplate(
            $customer,
            self::XML_PATH_REMIND_EMAIL_TEMPLATE,
            self::XML_PATH_FORGOT_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
            $storeId
        );
    }

    /**
     * Send email with reset password confirmation link
     *
     * @param CustomerInterface $customer
     * @return void
     */
    public function passwordResetConfirmation(CustomerInterface $customer)
    {
        $storeId = $this->storeManager->getStore()->getId();
        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer);
        }

        $customerEmailData = $this->getFullCustomerObject($customer);

        $this->sendEmailTemplate(
            $customer,
            self::XML_PATH_FORGOT_EMAIL_TEMPLATE,
            self::XML_PATH_FORGOT_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'store' => $this->storeManager->getStore($storeId)],
            $storeId
        );
    }

    /**
     * Send email with new account related information
     *
     * @param CustomerInterface $customer
     * @param string $type
     * @param string $backUrl
     * @param string $storeId
     * @param string $sendemailStoreId
     * @return void
     * @throws LocalizedException
     */
    public function newAccount(
        CustomerInterface $customer,
        $type = self::NEW_ACCOUNT_EMAIL_REGISTERED,
        $backUrl = '',
        $storeId = 0,
        $sendemailStoreId = null
    ) {
        $types = self::TEMPLATE_TYPES;

        if (!isset($types[$type])) {
            throw new LocalizedException(
                __('The transactional account email type is incorrect. Verify and try again.')
            );
        }

        if (!$storeId) {
            $storeId = $this->getWebsiteStoreId($customer, $sendemailStoreId);
        }

        $store = $this->storeManager->getStore($customer->getStoreId());

        $customerEmailData = $this->getFullCustomerObject($customer);

        $this->sendEmailTemplate(
            $customer,
            $types[$type],
            self::XML_PATH_REGISTER_EMAIL_IDENTITY,
            ['customer' => $customerEmailData, 'back_url' => $backUrl, 'store' => $store],
            $storeId
        );
    }
}

Then check to hit below command for check email notification file is properly override or not

php bin/magento setup:di:compile

Finally applied some condition In new account function and check
I hope this will help you.


text:
Q: flexbox min-width failing in IE and Edge I have some table that set width for  elements so some columns will have at least some percent of a width of the container.
I want to use flexbox to center this table and set the minimum-width for it.
The goal is to have centered table with some minimum width for which some columns will have the same width (same ratio).
If some cells have longer texts then I don't care if ratio will broke (width of this column will be bigger then other). I just care that it has nice and same width of columns  for common case (small amount of text data in cells)
I was able to came up with solution that works on Firefox and Chrome (link).
But for Edge and IE11 the table stretch as if it was not in flex container (try to comment display: flex; on Firefox or Chrome and the result is stretched table like on Edge.
Also it looks that sometime setting columns work (link2). But I don't see the pattern of when it break in Edge/IE11.
Here is more production example that I want to achieve (works in Chrome/Firefox, stretch in Edge/IE11): "production" table example.
Any ideas how to achieve what I want on Edge/IE11? (I put in bold what I want to achieve).
It would be good if I could keep using flexbox container (it might require more changes in my codebase) but I think I will be fine with deleting style=width:p% from <col> if that's necessary.

A: The min-width rule is apparently being ignored in Edge / IE11.
There's an equivalent command that seems to work.
Instead of:
.inner {
    min-width: 800px
}

Use:
.inner {
    flex-basis: 800px; /* 1 */
    flex-shrink: 0;    /* 2 */
}

revised codepen

notes:

*

*flex-basis is a substitute for width, in this case (see: flex-basis vs width)

*flex-shrink: 0 ensures flex-basis / width cannot decrease below 800px (hence, both rules together emulate min-width)


text:
Q: Tarea en segundo plano con discord.py envio de mensajes automaticamente Como hacer que cuando alguien se conecta mi bot mande un mensaje a general, no un mensaje de bienvenida si no unos mensajes que estan en dos lista y que siempre los envia aleatoria mente, por el mometo tengo esto de codigo.
@tasks.loop(3)
async def halago_o_insulto(ctx):
    si = True
    dom_2 = random.choice(lista and lista_2)
    await ctx.send(dom_2)

Siempre que alguien se conecte que envie un mensaje.


text:
Q: Python get start and end date of the week How to get the start date and end date of a week, and also if the following dates below comes under a particular range of start and end dates of the week how to show only those weeks start and end date.I am using python 2.4
2011-03-07  0:27:41
2011-03-06  0:13:41
2011-03-05  0:17:40
2011-03-04  0:55:40
2011-05-16  0:55:40
2011-07-16  0:55:40

A: from datetime import datetime
from time import strptime

Now
datetime(*strptime('2011-03-08  0:27:41', '%Y-%m-%d  %H:%M:%S')[0:6]).weekday()

returns the day of the week for the first date "as an integer, where Monday is 0 and Sunday is 6", so selecting those dates for which weekday() in [0, 6] will give you the start and end dates of weeks (or use 4 instead of 6 for work weeks).

A: From python2.5 onwards datetime module has datetime.strptime(date_string, format) which you can pass the date_string and format to get a datetime object for doing comparisions. In python2.4, you could use the time module's support of strptime. From the documentation, you should be able to find the week part of your question.


text:
Q: how to add pinch zoom functionality in flutter qr code scanner? I am developing qr code scanner app using qr_code_scanner flutter package.I am unable to add the pinch zoom functionality on that. Is there anyway to add this functionality or other qr code scanner package which supports pinch zoom function? Please help me on this.

A: InteractiveViewer can help you to implement pinch, zoom.
Check this out:
https://api.flutter.dev/flutter/widgets/InteractiveViewer-class.html
If you need double tap to zoom, wrap InteractiveViewer with GestureDetector and implement onDoubleTap
onDoubleTapDown: _handleDoubleTapDown,
              onDoubleTap: () {
                kLogger.i('--> on double tap');
                _handleDoubleTap();
              },
_____

void _handleDoubleTapDown(TapDownDetails details) {
    _doubleTapDetails = details;
}

void _handleDoubleTap() {
    if (_transformationController.value != Matrix4.identity()) {
    _transformationController.value = Matrix4.identity();
} else {
      final position = _doubleTapDetails.localPosition;
      // For a 3x zoom
      _transformationController.value = Matrix4.identity()
        ..translate(-position.dx * 2, -position.dy * 2)
        ..scale(3.0);
      // Fox a 2x zoom
      // ..translate(-position.dx, -position.dy)
      // ..scale(2.0);
    }
}


text:
Q: Must the endomorphism ring of a finitely generated module be Noetherian? Let $A$ be a ring (not necessarily commutative). If it helps, one can assume that $A$ is right hereditary (i.e. every submodule of a projective right $A$-module is projective). Let $M$ be a finitely generated module and $B=\text{End}(M)$. Is it true that $B$ is Noetherian?
I think this is true for commutative $A$. Then $B$ would be a Noetherian $A$-module, and since any ideal in $B$ could be considered an $A$-module, the fact that $B$ is a Noetherian $A$-module would imply that $B$ is a Noetherian $B$-module. That is, a Noetherian ring.
But is this true in the non-commutative case?


text:
Q: CalDAV client for iClouds: MKCALEDAR requests stopped working and fail with 412 Precondition Failed I developed a client for iCloud calendar service that uses CalDAV protocol. I use caldav4j library for Java, however the problem I encountered is language/library independent.
Several days ago creating of new calendars in my client stopped working. Now, I get 412 Precondition Failed status code while sending MKCALENDAR requests to iCloud. Other operations, like getting list of calendar resources, getting events, creating and updating events work the same as before.
I tried also to CURL it and to use Postman to send similar requests and results are always the same - 412 Precondition Failed.
Example request send by my client to create new calendar looks like this:
MKCALENDAR /xxxxxxxxxx/calendars/2321321CH34CHU35Y4UI5YVU31TIBCYTUIYBUI3
HTTP/1.1
Host: caldav.icloud.com
Content-Type: text/xml
Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==
cache-control: no-cache
<?xml version="1.0" encoding="UTF-8"?>
<C:mkcalendar xmlns:C="urn:ietf:params:xml:ns:caldav">
<D:set xmlns:D="DAV:">
    <D:prop>
        <D:displayname>new calendar</D:displayname>
        <C:calendar-description xml:lang="en">my description</C:calendar-description>
    </D:prop>
</D:set>
</C:mkcalendar>

Parts with xxxxx contains my proper principal id and authorization token.
Does anybody know if Apple has changed there something recently? I'm sure I didn't changed anything in my code and requests like the one in example above worked successfully a few days ago.


text:
Q: When binding a ListView using an ItemsSource, what is the correct way to indicate to the ListView that one or more items are already selected? I have a WPF form which includes a ListView and the following bindings:
    <ListView ItemsSource="{Binding SelectableItems}" SelectionMode="Extended">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="IsSelected" Value="{Binding IsSelected}" />
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Data From" DisplayMemberBinding="{Binding Started}" Width="150" />
                <GridViewColumn Header="Data To" DisplayMemberBinding="{Binding Finished}" Width="150" />
            </GridView>
        </ListView.View>
    </ListView>

The ViewModel's SelectableItems property returns an ObservableCollection of SelectableObject items where the SelectableObject inherits from ListViewItem.
The challenge we are having is as follows. When the view is initialized, one or more items in the SelectableItems collection may have their IsSelected property set to true. When the view is shown, visually each item appears to be in the correct selection state. Unfortunately, it appears that the "current selection" information is not being fully communicated to the ListView itself. The expected operation upon performing a simple single click on a non-selected item is that any currently selected items are deselected and the single clicked item then becomes the only item with IsSelected set to true. This does not appear to be happening. Instead the newly clicked item is added to the set of previously clicked items... but only the first time. All subsequent single click operations operate as expected.
Is there something else that needs to be done during initialization to correctly initialize the ListView's expectations concerning the currently selected items?

A: Basically, the ListView uses the SelectedItems property to keep track of the extended selection. When your collection is bound to the control, it has no way of knowing / updating the SelectedItems collection, and therefore doesn't know that there are objects selected. Unfortunately, the SelectedItems property is not bindable.
I have in the past created Attached Properties to 'wrap' the SelectedItems collection with a bindable property, but it is cumbersome, and I am fairly sure that my implementation might cause leaks.
Alternatively, you can use some minor code-behind / attached property to set the SelectedItems property when the ItemsSource changes:
Edit: Changed to Attached Property
public class Bindable
{
    public static readonly DependencyProperty InitializeSelectedItemsProperty = DependencyProperty.RegisterAttached(
                                                            "InitializeSelectedItems", typeof(bool), typeof(Bindable), new PropertyMetadata(default(bool), InitializeSelectedItemsChanged));

    private static void InitializeSelectedItemsChanged(DependencyObject depObject, DependencyPropertyChangedEventArgs args)
    {
        var listView = depObject as ListBox;

        if (listView != null && (bool)args.NewValue)
        {
            TypeDescriptor.GetProperties(listView)["ItemsSource"]
                    .AddValueChanged(listView, new EventHandler(ListViewItemsSourceChanged));
        }
    }

    private static void ListViewItemsSourceChanged(object sender, EventArgs eventArgs)
    {
        var listView = sender as ListBox;

        listView.SelectedItems.Clear();

        foreach (var item in listView.ItemsSource.OfType<ISelectable>().Where(i => i.IsSelected))
        {
            listView.SelectedItems.Add(item);
        }
    }
}

<ListView ItemsSource="{Binding SelectableItems}" Bindable.InitializeSelectedItems="True" SelectionMode="Extended" ...>

A: A solution will be to store the selected items in a list, or better in a dictionnary, if your listview is a list of items which could be identified as a pair of Key/Value.
Then when your list is updated by the binding, you should iterate through your dictionary and test if a couple key/value exist in the listview you then if true set is property to Selected.
It's a way.


text:
Q: How to use HiddenFor with an expression of object I have an extension that creates a component, in this component I'am adding a HiddenFor.
This is the code:
class Test<TModel>
{

     protected HtmlHelper<TModel> HtmlHelper { get; set; }

     public void MyFunction<TColumnModel>(Expression<Func<TModel, object>> expVal, string name, params Expression<Func<TColumnModel, object>>[] columns)
     {

          // Make some stuff with columns

          var hidden = this.HtmlHelper.HiddenFor(expVal);

     }

}

The problem is:
When I execute the code above, it returns the following error:

Templates can be used only with field access, property access,
  single-dimension array index, or single-parameter custom indexer
  expressions.

Ok, this error ocurrs because I am trying to create a HiddenFor using an expression of object, if I make a cast, it will probably resolve, but, how to make a cast of an expression without compile it? I don't want to compile the expression to get the value every time.
Another solution, could be instead of use an expression of TModel and object, use an expression of two generic types, like that:
MyFunction<TColumnModel, TValue>(Expression<Func<TModel, TValue>> expVal

But, when I call this method I don't know the type of TValue, it would not be a problem, but as I have to inform the TColumModel I will have to inform the TValue too.
So, there are two questions:
Is there a way to create a HiddenFor of an expression of object?
I can call a method with two generic types, passing just one?
Thanks


text:
Q: how to create savedInstanceState for dynamically selected image in Android? I create a android application.Select image from gallery using a button and retrieve in the ImageView. The image fetching is successful.
Now I want to saved the state of the selected Image.I try to fix.It makes crash application.When I change the Horizontal orientation the app is crashed.Please help me to solve the issue.
My Code :
public class MainActivity extends ActionBarActivity {

ImageView imgBackground;
Button loadImgBtn;

String imgDecodableString;
Drawable drawable;

private static int RESULT_LOAD_IMG = 1;
private static final String IMAGE_DATA = "image_resource";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    loadImgBtn = (Button)findViewById(R.id.btnSelectImage);
    imgBackground = (ImageView)findViewById(R.id.myImg);

    loadImgBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /* Create intent to open Image Application like Gallery */
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            /* start the Intent */
            startActivityForResult(galleryIntent,RESULT_LOAD_IMG);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
            /* Get the Image from Data */
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            /* Get the Cursor */
            Cursor cursor = getContentResolver().query(selectedImage,filePathColumn,null,null,null);

            /* Move the first row */
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

            /* Rendering the Image */
            drawable =  new BitmapDrawable(imgDecodableString);
            imgBackground.setBackgroundDrawable(drawable);
        }
    } catch (Exception e) {
        message(getBaseContext()," Error : " + e.getMessage(),Toast.LENGTH_SHORT);
    }
}

public void message(Context ctx,String msg,int duration) {
    Toast.makeText(ctx,msg,duration).show();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
     super.onSaveInstanceState(outState);
     outState.putParcelable(IMAGE_DATA, (android.os.Parcelable) drawable);
}

@Override
protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    drawable = (Drawable) savedInstanceState.getParcelable(IMAGE_DATA);
}
}

A: I have not tested this, so I don't know if it is working. Hope it is.
But you should be aware of this

...it might not be possible for you to completely restore your
  activity state with the Bundle that the system saves for you with the
  onSaveInstanceState() callback—it is not designed to carry large
  objects (such as bitmaps) and the data within it must be serialized
  then deserialized, which can consume a lot of memory and make the
  configuration change slow. In such a situation, you can alleviate the
  burden of reinitializing your activity by retaining a stateful Object
  when your activity is restarted due to a configuration change.

public class MainActivity extends ActionBarActivity {

        ImageView imgBackground;
        Button loadImgBtn;

        String imgDecodableString;
        BitmapDrawable drawable;

        private static int RESULT_LOAD_IMG = 1;
        private static final String IMAGE_DATA = "image_resource";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            loadImgBtn = (Button)findViewById(R.id.btnSelectImage);
            imgBackground = (ImageView)findViewById(R.id.myImg);

            loadImgBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
            /* Create intent to open Image Application like Gallery */
                    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            /* start the Intent */
                    startActivityForResult(galleryIntent,RESULT_LOAD_IMG);
                }
            });

            if(savedInstanceState != null) {
                Bitmap tmp = savedInstanceState.getParcelable(IMAGE_DATA);
                if(tmp != null) {
                    drawable = new BitmapDrawable(getResources(), tmp);
                    imgBackground.setImageDrawable(drawable);
                }
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            try {
                if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
            /* Get the Image from Data */
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };

            /* Get the Cursor */
                    Cursor cursor = getContentResolver().query(selectedImage,filePathColumn,null,null,null);

            /* Move the first row */
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imgDecodableString = cursor.getString(columnIndex);
                    cursor.close();

            /* Rendering the Image */
                    drawable =  new BitmapDrawable(imgDecodableString);
                    imgBackground.setBackgroundDrawable(drawable);
                }
            } catch (Exception e) {
                message(getBaseContext()," Error : " + e.getMessage(), Toast.LENGTH_SHORT);
            }
        }

        public void message(Context ctx,String msg,int duration) {
            Toast.makeText(ctx,msg,duration).show();
        }

        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            if(drawable != null && drawable.getBitmap() != null) {
                outState.putParcelable(IMAGE_DATA, drawable.getBitmap());
            }
        }

        @Override
        protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
            super.onRestoreInstanceState(savedInstanceState);
        }
    }

}

A: Be careful in using Instance State with Bitmaps. As Bojan quoted you should not use the Bundle managed via 'onSaveInstanceState' for images.
This is the updated quote:

it might not be possible for you to completely restore your activity state with the Bundle that the system saves for you with the onSaveInstanceState() callback—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow. In such a situation, you can alleviate the burden of reinitializing your activity by retaining a Fragment when your activity is restarted due to a configuration change. This fragment can contain references to stateful objects that you want to retain.

from the official documentation
You can find the code I implemented following this hint looking at my answer at this other question


text:
Q: Query one document or another depending on specific field Imagine a SolR-index with documents similar to this
[
{
    ProductId: 123,
    Contract: abc
},
{
    ProductId: 123,
    Contract: def
},
{
    ProductId: 123
},
{
    ProductId: 567
},
{
    ProductId: 567,
    Contract: bar
}
]

*

*There is always a document with a specific ProductId and without a Contract

*Additionally there may be 0 to n documents with Contract
I need a query, where I can use a Contract and that should return me all ProductIds either the one with the given Contract, if exists, or the single document without a Contract at all.
For example I will make a query with Contract: def (somehow) and it should give me this
[
{
    ProductId: 123,
    Contract: def
},
{
    ProductId: 567
}
]

*

*The document with Contract:abc is not part of the result

*The document with ProductId:123 but without Contract is not part of the result

*The document ProductId:567 is part of the result, because there is no document with this ProductId and ContractId: def
In other words what I need is something like

*

*Give me one documents per ProductId and with Contract:X XOR -Contract*, but not both.

A: Step 1 Write your query so that records without Contracts as well as all with matching contracts are returned, but the ones with the appropriate contract have the highest score. This gets around the problem that you will sometimes want items in your results that don't match the contract value: q=Contract:"def" OR (*:* -Contract:[* TO *]). The (*:* -Contract:[* TO *]) matches that all records without contracts, and the Contract:"def" matches records with the correct contract. The records matching Contract:"def" should naturally have a higher score than those with no contract, but if there's any trouble or you just want to be sure, you can add a boost to that clause, Contract:"def"^2.
Step 2 Add Result Grouping to the query, configured so that you are requesting only the highest scoring record for any given ProductId:
q=Contract:"def" OR (*:* -Contract:[* TO *])&group=true&group.field=ProductId

This requires that the ProductId field be configured in your schema.xml as multiValued="false", as multiValued fields cannot be used as groups. I'm also assuming that you are using the Standard Query Parser, either set as a default in your solrconfig.xml or by adding the argument defType=lucene when you make the query.
The results should look something like this:
'grouped'=>{
'ProductId'=>{
  'matches'=>5,
  'groups'=>[{
      'groupValue'=>123,
      'doclist'=>{'numFound'=>3,'start'=>0,'docs'=>[
          {
            'ProductId'=>123,
            'Contract'=>'def'}]
      }},
    {
      'groupValue'=>567,
      'doclist'=>{'numFound'=>2,'start'=>0,'docs'=>[
          {
            'ProductId'=>567}]
      }}]}}}

Note that neither the matches nor the numFound values in the result set will tell you how many groups have been returned, but the argument rows=XX can be used to define the maximum number of desired groups (in this case ProductIds).


text:
Q: Button Onclick does not work inside form Good Day
I am using an ASP.NET webform where I have wrapped the following button inside the form tags:
<form runat="server">

  <button class="btn btn-primary" onclick="window.location='http://google.co.za';">Login</button>

</form>

ISSUE: The problem is that when clicking on the button, it just directs to the current page...does not redirect. However, when I remove the form tags, the button works. If I leave the form tags and I use an anchor tag to relocate, it works as well...It is just the button that is giving me issues.
Why is that?
I am using Twitter bootstrap as well(extra info..)
Thank you

A: Add type="button" attribute to your button tag. Without it button works as submit.


text:
Q: How can I order entries in my OrderedDict where values are duplicated? I have a bunch of code that is out of scope of this question. The code scrapes data and gives me the following dictionary:

{'Male Open 60 Mins': {'Kavin Jones': {'total_points': 47,
'plate_number': '35'}, 'Alan Smith': {'total_points': 42,
'plate_number': '23'}, 'Dominique Smith': {'total_points': 35,
'plate_number': '20'}, 'James Smith': {'total_points': 32,
'plate_number': '15'}, 'Hans Smith': {'total_points': 35,
'plate_number': '99'}, 'Cameron Smith': {'total_points': 33,
'plate_number': '21'}, 'Michael Smith': {'total_points': 23,
'plate_number': '148'}, 'Chris Smith': {'total_points': 32,
'plate_number': '18'}, 'Jackson Smith': {'total_points': 14,
'plate_number': '17'}, 'Grant Smith': {'total_points': 12,
'plate_number': '48'}, 'David Smith': {'total_points': 11,
'plate_number': '3'}, 'Andrew Smith': {'total_points': 23,
'plate_number': '32'}, 'Duncan Smith': {'total_points': 22,
'plate_number': '33'}, 'Brian Smith': {'total_points': 18,
'plate_number': '36'}, 'Manning Jones': {'total_points': 10,
'plate_number': '14'}, 'Matthew Smith': {'total_points': 15,
'plate_number': '27'}, 'Clifford Smith': {'total_points': 6,
'plate_number': '28'}, "Che'quan Smith": {'total_points': 4,
'plate_number': '34'}, 'Philip Smith': {'total_points': 9,
'plate_number': '43'}, 'Christopher Jones': {'total_points': 4,
'plate_number': '13'}, 'Wendell Smith': {'total_points': 5,
'plate_number': '2'}, 'Maceo Smith': {'total_points': 2,
'plate_number': '8'}, 'Craig Smith': {'total_points': 2,
'plate_number': '11'}, 'Dennis Smith': {'total_points': 2,
'plate_number': '10'}, 'Edwin Smith': {'total_points': 2,
'plate_number': '88'}, 'Dirk Smith': {'total_points': 2,
'plate_number': '142'}, 'Mark Smith': {'total_points': 12,
'plate_number': '46'}, 'Jay Smith': {'total_points': 2,
'plate_number': '25'}, 'Blake Smith': {'total_points': 2,
'plate_number': '178'}, 'Stephen Smith': {'total_points': 1,
'plate_number': '31'}, 'Justin Smith': {'total_points': 2,
'plate_number': '12'}, 'Peter Smith': {'total_points': 2,
'plate_number': '26'}, 'Jenai Smith': {'total_points': 1,
'plate_number': '29'}, 'Christopher Smith': {'total_points': 2,
'plate_number': '44'}, 'Nathan j. Smith': {'total_points': 2,
'plate_number': '39'}, 'Deryck Smith': {'total_points': 1,
'plate_number': '24'}, 'Conor Smith': {'total_points': 25,
'plate_number': '40'}, 'Moses Smith': {'total_points': 7,
'plate_number': '16'}, 'Howard Smith': {'total_points': 5,
'plate_number': '41'}, 'Chad Smith': {'total_points': 1,
'plate_number': '38'}}, 'Female Open 60 Mins': {'Jennifer Smith':
{'total_points': 67, 'plate_number': '42'}, 'Ashley Smith':
{'total_points': 40, 'plate_number': '6'}, 'Caitlin Smith':
{'total_points': 25, 'plate_number': '5'}}}

I then run the following code to order each racer within each race by total_points:
from collections import OrderedDict
from operator import getitem

for key in overall_standings.keys():
    current_reorder = OrderedDict(sorted(overall_standings[key].items(), key = lambda x: getitem(x[1], 'total_points'), reverse=True))
    overall_standings[key] = current_reorder

    for item, racer_info in overall_standings.items():
        print("\n********" + item + "********")
        for name, data in racer_info.items():
            print(name)
            print(data['total_points'])
            print(data['plate_number'])

If I print out the ordered dictionary now, it looks like this:

{'Male Open 60 Mins': OrderedDict([('Kavin Jones', {'total_points': 47, 'plate_number': '35'}), ('Alan Smith', {'total_points': 42, 'plate_number': '23'}), ('Dominique Smith', {'total_points': 35, 'plate_number': '20'}), ('Hans Smith', {'total_points': 35, 'plate_number': '99'}), ('Cameron Smith', {'total_points': 33, 'plate_number': '21'}), ('James Smith', {'total_points': 32, 'plate_number': '15'}), ('Chris Smith', {'total_points': 32, 'plate_number': '18'}), ('Conor Smith', {'total_points': 25, 'plate_number': '40'}), ('Michael Smith', {'total_points': 23, 'plate_number': '148'}), ('Andrew Smith', {'total_points': 23, 'plate_number': '32'}), ('Duncan Smith', {'total_points': 22, 'plate_number': '33'}), ('Brian Smith', {'total_points': 18, 'plate_number': '36'}), ('Matthew Smith', {'total_points': 15, 'plate_number': '27'}), ('Jackson Smith', {'total_points': 14, 'plate_number': '17'}), ('Grant Smith', {'total_points': 12, 'plate_number': '48'}), ('Mark Smith', {'total_points': 12, 'plate_number': '46'}), ('David Smith', {'total_points': 11, 'plate_number': '3'}), ('Manning Jones', {'total_points': 10, 'plate_number': '14'}), ('Philip Smith', {'total_points': 9, 'plate_number': '43'}), ('Moses Smith', {'total_points': 7, 'plate_number': '16'}), ('Clifford Smith', {'total_points': 6, 'plate_number': '28'}), ('Wendell Smith', {'total_points': 5, 'plate_number': '2'}), ('Howard Smith', {'total_points': 5, 'plate_number': '41'}), ("Che'quan Smith", {'total_points': 4, 'plate_number': '34'}), ('Christopher Jones', {'total_points': 4, 'plate_number': '13'}), ('Maceo Smith', {'total_points': 2, 'plate_number': '8'}), ('Craig Smith', {'total_points': 2, 'plate_number': '11'}), ('Dennis Smith', {'total_points': 2, 'plate_number': '10'}), ('Edwin Smith', {'total_points': 2, 'plate_number': '88'}), ('Dirk Smith', {'total_points': 2, 'plate_number': '142'}), ('Jay Smith', {'total_points': 2, 'plate_number': '25'}), ('Blake Smith', {'total_points': 2, 'plate_number': '178'}), ('Justin Smith', {'total_points': 2, 'plate_number': '12'}), ('Peter Smith', {'total_points': 2, 'plate_number': '26'}), ('Christopher Smith', {'total_points': 2, 'plate_number': '44'}), ('Nathan j. Smith', {'total_points': 2, 'plate_number': '39'}), ('Stephen Smith', {'total_points': 1, 'plate_number': '31'}), ('Jenai Smith', {'total_points': 1, 'plate_number': '29'}), ('Deryck Smith', {'total_points': 1, 'plate_number': '24'}), ('Chad Smith', {'total_points': 1, 'plate_number': '38'})]), 'Female Open 60 Mins': OrderedDict([('Jennifer Smith', {'total_points': 67, 'plate_number': '42'}), ('Ashley Smith', {'total_points': 40, 'plate_number': '6'}), ('Caitlin Smith', {'total_points': 25, 'plate_number': '5'}}}

I'm not sure how OrderedDict or sorted sorts the racers where they have the same number of points. You'll see that there are a bunch of racers where the total_points are 2 and 1.
What I'm looking to do, is to add to the dictionary a key for each racer where it averages their race positions. Take Chad Smith for instance. Let's say that he came 10th, 11th, 10th, and 9th. I want to add a key where his race position average is 10. This is easy to do.
How do I take the OrderedDict now and say, for every duplicate in total_points, I want to now sort by race position average? Would this code come during my primary OrderedDict and sorted code or would it come after?

A: I learned that built into sorted is a tuple value where you can sort by a secondary field if there is a tie in your first field.
I added the following lines to my code to allow for the list addition. If this racer is new, we create a var with the empty list.
if racer not in overall_standings[race_name]:
    overall_standings[race_name][racer] = {}
    if "average_position" not in overall_standings[race_name][racer]:
        overall_standings[race_name][racer]["average_position"] = []
    overall_standings[race_name][racer]["average_position"].append(position)
else:
    overall_standings[race_name][racer]["average_position"].append(position)

Could you do this cleaner? Sure. But this works. Code clean-up comes later.
This would give me a dictionary that looks like:

{'Male Open 60 Mins': {'Kavin Smith': {'average_position': [1, 2],
'total_points': 47, 'plate_number': '35'}, 'Alan Potts':
{'average_position': [2, 3], 'total_points': 42, 'plate_number': '23'}}}

I then averaged out the list:
for item, racer_info in overall_standings.items():
for name, data in racer_info.items():
    data["average_position"] = sum(data["average_position"])/len(data["average_position"])

Finally I do the following from the code in my original question:
for key in overall_standings.keys():
    current_reorder = OrderedDict(sorted(overall_standings[key].items(), key = lambda x: (getitem(x[1], 'total_points'), -getitem(x[1], 'average_position')), reverse=True))
    overall_standings[key] = current_reorder

I do -getitem(x[1] with a minus because you can only set the reverse= switch once and while I want the total_points to  order from biggest to smallest, I want the average_position to order from smallest to biggest (because if you and another racer both have 20 points, coming 1st beats coming 2nd overall).
Now I just access the data.
for item, racer_info in overall_standings.items():
    print("\n------------" + item + "------------")
    for name, data in racer_info.items():
        print(name)
        print("Total Points: " + str(data['total_points']))
        print("Plate Number: " + str(data['plate_number']))
        print("Average Position: " + str(data['average_position']))
        print("-----------------------")


text:
Q: What is afterburn command for in Freelancer? I see in the command controlling the ship with Tab key saying to Afterburn.
I don't know what that is.

A: Check that your ship has a thruster installed; it's in the 4th page of equipment, with your shield. If you have one, you can hold Tab to zoom at 200 MPS for a little while (still slower than cruise mode's 300 MPS though). The thruster has limited charge represented by the number to the left of your health and shield bars, but it recharges pretty fast.


text:
Q: "arrive" Vs. "reach" what are the differences if any? In the past I've been told that there is a difference between the usage of these two verbs: "arrive" and "reach", But I've never understood it. Today Iv'e checked it in the Cambridge dictionary and I found that they are considering synonyms:

Reach: to arrive at a place, especially after spending a long time or a lot of effort travelling.
Arrive: to reach a place, especially at the end of a journey.

But By googling I've reached / arrived this site, which the writer there write the following things:

REACH and ARRIVE are very similar, they imply you made it to the final
  destination. I reached my goal, I arrived home.
REACH implies you were farther away and you finally reached the destination. Often it is used in a context where there were
  difficulties in the way. But not necessarily. It implies the goal is
  achieved, you reached your destination. e.g. "Despite the storm on the sea we reached the shore safe and sound."
ARRIVE means you got there. It is used also in a context of
  transportation, like planes, buses, trains. e.g. I arrived at 10 / The
  bus is scheduled to arrive at 10.

Now, my question is if based on that they are synonyms, can I use them interchangeably or they are not synonyms and I have to use each one of them in a certain context. Very often I find myself thinking about If I should use "arrive" or "reach". So far, I have no really clear information about it.

A: These are mostly synonymous, at least when talking about the end of some journey.

My GPS is telling me, "You have reached your destination."
My GPS is telling me, "You have arrived at your destination."

Metaphorically, while "arrive" is often just a description of events, "reach" can imply some sort of effort or unusual extension (related to its other definitions) so it can sound slightly more dramatic.

After a journey of many days, they finally reached the castle.

This is subtle, though.  If you really want to imply effort there are more dramatic verbs.

Parched and weary after crossing the desert, they stumbled into the oasis.

A: Arrive and reach are synonyms. However, arrive takes the preposition at, while reach doesn't.


text:
Q: How do I filter a list by type in Google Earth Engine? I have a function that outputs a list of an image and a feature collection. I'd like to use a filter to separate them. ee.filter.hasType() looks like what I want, but I can't figure out how to implement it. More broadly, lots of the filters have this (leftField, rightValue, rightField, leftValue) argument structure that I find confusing.
For example, to filter the image I tried this:
myFunctionOutput.filter(ee.Filter.hasType({leftField: "type", rightValue: ee.Image()}))
But this isn't right. What's the proper way to filter a list by type?

A: That filter argument structure is optimized for the most common use case of filtering a piece of metadata by a constant, in a collection.  E.g.:
ee.Filter.lt({leftField: "CLOUD_COVER", rightValue: 10}))

which is the same as:
ee.Filter.lt("CLOUD_COVER", 10)

Sometimes, however, you want to compare a property vs another property, so you have to specify "this is a property name, not a string literal to compare against:
ee.Filter.lt({leftField: "CLOUD_COVER", rightField: "cloud_threshold"}),

and occasionally, there's a need to have the left value be a literal (e.g.: geometry filtering).
As is (vaguely) implied by the docs for ee.List.filter, there's currently no way to filter on type for Images or Features in a list:

To filter list items that aren't images or features, test a property
named 'item', e.g.: ee.Filter.gt('item', 3)

When examining a List element that is an Image or a Feature, any property name you specify in the filter will be taken to be a property inside the list element.  So to make things work by specifically examining type, you'd need to map over the elements in the list setting a type on each one, then filter for that type:
var images = ee.List([ee.Image(1), ee.Feature(null, {})])
    .map(function(item) { return ee.Feature(item).set('type', ee.Algorithms.ObjectType(item)) })
    .filter(ee.Filter.eq('type', 'Image'))

It's safe (in this limited case) to cast the Images to Feature to get at the set() function.  It shouldn't mess anything up.
But a better solution is to just filter for an image-only property (e.g.: system:bands) being non-null to get at the images, and use ee.Filter.notNull(...).not() to get at the features.
ee.List([ee.Image(1), ee.Feature(null, {})])
    .filter(ee.Filter.notNull(['system:bands']))


text:
Q: Why doesn't pandas update a variable's dtype when populating a dataframe? I noticed a difference between two pandas version, and was wondering why that was the case / if it was an expected behaviour:
import pandas as pd
df = pd.DataFrame(columns = ("Name", "Age"))
df.loc[1] = "Jane", 5
df.loc[2] = "Riley", 24
df.dtypes

In my test:

*

*with Python 3.5 and Pandas 0.18.1, populating the dataframe does update the "object" dtype of the Age variable to "float64"

*with Python 3.7 and Pandas 0.23.4, populating the dataframe does not update the "object" dtype of the Age variable

Why is that? I couldn't find an explanation in the documentation.
Edit: I just noticed df.infer_objects().dtypes, which might be particularly relevant... Did the automatic "inference" get ditched along the way?


text:
Q: Como puedo sacar todas las combinaciones de un rango? Ejemplo las combinaciones de 123 serian:
123, 132, 213, 231, 312, 321.
Necesito ayuda
def generar():
    def unico(x,L):
        esUnico=True
        for i in range(len(L)):
            if x==L[i]:
                esUnico=False
                break
        return esUnico
    L=[]
    j=0

    while j<6:
        x=random.randint(1,36)
        if unico(x,L):
            L.append(x)
            j+=1
    numero["text"]= L
print(L)

El problema es que solo me genera una sola combinacion

A: Es mejor no reinventar la rueda cuando la biblioteca estándar python ya te da las herramientas para lograr lo que quieres.
En la biblioteca itertools tienes la función permutations(). El único problema es que hay que pasarle un iterable (en tu caso las cifras del número), en vez de un número, pero es muy sencillo obtenerlo, basta aplicarle str() pues una cadena es un iterable para python.
La función te devuelve otro iterable, y cuando iteras por él, en cada iteración te devuelve una tupla con una permutación diferente. Basta juntar la tupla en una cadena usando "".join().
Si además usas una comprensión de listas para hacer la iteración, puedes lograr lo que buscas con una línea de código:
[ "".join(x) for x in permutations(str(numero))]

Demo:
from itertools import permutations

n = 123
print([ "".join(x) for x in permutations(str(n))])

Resultado:
['123', '132', '213', '231', '312', '321']