text:
Q: Raspberry Pi as a gateway between BLE beacon and IBM Watson I'm trying to use a Raspberry Pi 3 as a gateway to send data from a BLE beacon to IBM Watson platform. I can view the data from the beacon in the Raspberry Pi console but I don't understand how can I send the data to Watson.
I've tried using Node-RED and the Generic-BLE node but it seems this node only works with dongles and i'm using the embedded Bluetooth of the RaspberryPi to read the data from the BLE beacon.
Has anyone tried to do this and was successful?

A: There should be absolutely no difference between a USB BLE dongle and the built in BLE on a RPi3.
You will have to either run Node-RED as root or use the following command to allow NodeJS to access the BLE adapter.
sudo setcap cap_net_raw+eip $(eval readlink -f `which node`)

A: You might want to try node-red-contrib-bleacon instead of Generic-BLE, as Generic-BLE is designed for connectable GATT Bluetooth LE modules.  BLE Beacons are typically transmit only devices that often don't have public interfaces to connect over GATT.


text:
Q: KMeans in Python centroids not in correct position, how do I "unscale" them? I have a small script to run in a jupyter notebook. The Kmeans seems to be working correctly, but my centroids are scaled down. How do I get them to display correctly on my plot? My x and y range from 0 to about 500 on each side.
from pandas import DataFrame
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
import pandas as pd

plt.figure(figsize=(8, 6))
df = pd.read_csv("sales-by-week-4.csv")
df2 = DataFrame(df,columns=["Average Sale Price", "Average Weekly"])
plt.figure(figsize=(8, 6))
kmeans = KMeans(n_clusters=5).fit(scale(df2))
centroids = kmeans.cluster_centers_
print(centroids)

plt.scatter(df2["Average Weekly"], df2["Average Sale Price"], c= kmeans.labels_.astype(float), s=50, alpha=0.5)
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=50)

Here's my centroid print.
[[ 2.65044538 -0.37653707]
 [-0.64002758 -0.25885017]
 [-0.39559393  5.26965425]
 [ 0.91316601 -0.29410492]
 [-0.5276885   0.8949181 ]]

A: You fitted KMeans on your scaled dataframe. Try to fit on df2 only

redpajama_set_name: RedPajamaStackExchange


text:
Q: php line in a css, but the css comes from php I had the issue, that I want to add a get_template_directory_uri() in a css line. This Css line is located in a boxes.php file.
$box_first = 'linear-gradient(rgba(0, 175, 227, .8), rgba(0, 175, 227, .8)),
url("/wp/wp-content/themes/my_theme/inc/img/boxes/box2.png") center;';

I also tried already to make a variable and put the variable in
$tpl_dir = echo get_template_directory_uri() .
'/inc/img/boxes/box2.png';

$box_first = 'linear-gradient(rgba(0, 175, 227, .8), rgba(0, 175, 227, .8)),
url("$tpl_dir") center;';

, without any success..
Do you have any conclusions for me?
Many thanks and stay healthy, Dennis

A: Am not quite sure I got your idea. Anyway, I will point out some problems here.
If you want to assign the value returned by the function, you don't have to echo it. So that echo can be removed like this:
$tpl_dir = get_template_directory_uri() .
'/inc/img/boxes/box2.png';

Here, the value returned by the function (ie, the url) is appended with the path to the image.
And the second problem here is, when you want to use the value from a variable, inside a string that has single quotes for enclosing the string, try to do concatenation.
Eg:
$box_first = 'linear-gradient(rgba(0, 175, 227, .8), rgba(0, 175, 227, .8)),
url("' . $tpl_dir . '") center;';

Or else, it should be enclosed in double quotes. Then only the variable inside would be parsed.
Eg:
$box_first = "linear-gradient(rgba(0, 175, 227, .8), rgba(0, 175, 227, .8)),
url(\"$tpl_dir\") center;";

Or,
$box_first = "linear-gradient(rgba(0, 175, 227, .8), rgba(0, 175, 227, .8)),
url('$tpl_dir') center;";

Also, if you are going to follow this instead of concatenation, I would suggest enclosing the variable name in curly braces.
Eg:
$box_first = "linear-gradient(rgba(0, 175, 227, .8), rgba(0, 175, 227, .8)),
    url(\"{$tpl_dir}\") center;";

Now you can use the $box_first  variable to style the element. Eg:
<div class="abc_something" style="<?php echo $box_first ; ?>">blah blah blah


text:
Q: How can I have a SQL Max on a LEFT JOIN? How can i find the MAX value of tenant_id on a LEFT JOIN of the given stall_id?
$sql = "SELECT * FROM stall s
        LEFT JOIN tenant t
        ON t.stall_id = s.stall_id
        LEFT JOIN rent r
        ON r.tenant_id = t.tenant_id AND r.rent_status = 1
        WHERE s.stall_id = 1";

A: Do you want like this one:-
    SELECT * FROM stall s
    LEFT JOIN tenant t
    ON t.stall_id = s.stall_id
    LEFT JOIN rent r
    ON r.tenant_id = t.tenant_id AND r.rent_status = 1
    WHERE s.stall_id = 1 ORDER BY r.tenant_id desc LIMIT 1

A: I don't think you need to use MAX() in this case, as the rent_status field looks to be a boolean (1 or 0). That means that a simple INNER JOIN would do the trick.
SELECT * FROM `stall` AS s
INNER JOIN rent AS r ON r.stall_id = s.id AND r.rent_status = 1
WHERE s.stall_id = 1


text:
Q: What are alternative terms/words for "cognitive dissonance?" I grasp the meaning completely, I'm just looking for alternatives ways to express it.

A: Consider the following possibilities. (Not all of them express exactly the concept you are after, but all of them incorporate aspects of it):

*

*Self-contradictory attitudes

*Rationalization / rationalizing behaviour

*Behavioural inconsistency

*Self-justification

*Polite fiction

*Self-deception

*Victim blaming

*Confirmation bias

*Prejudice

*Excuse-making

*Living a lie

*Being closeted (e.g. as a homosexual, follower of a different faith (or none), member of a different ethnicity)

*Denial behaviours, e.g. denial of responsibility, self-denial

*Plausible deniability

*Projection

A: More colloquially, someone might say: "I can't get my head around it"

A: I think you could use the term ambivalence or its adjective form ambivalent.
Ambivalence is defined as:

Simultaneous and contradictory attitudes or feelings (as attraction and repulsion) toward an object, person, or action

And that is pretty much the same definition as cognitive dissonance.

Psychological conflict resulting from incongruous beliefs and attitudes held simultaneously

In fact, there are a number of online articles — such as this one entitled "Thinking and Caring About Cognitive Inconsistency: When and for Whom Does Attitudinal Ambivalence Feel Uncomfortable" — that use the word ambivalence when describing cognitive dissonance.

A: The term Dunning-Kruger effect is well known enough to have meaning amongst generally educated people.
From Wikipedia:

The Dunning–Kruger effect is a cognitive bias which can manifest in
  one of two ways:

*

*Unskilled individuals suffer from illusory superiority, mistakenly rating their ability much higher than is accurate. This bias is
  attributed to a metacognitive inability of the unskilled to recognize
  their ineptitude.

*Those persons to whom a skill or set of skills come easily may find themselves with weak self-confidence, as they may falsely assume that
  others have an equivalent understanding.

Eg.

She was suffering from Dunning-Kruger effect, her cookies were not the morsels of heaven she believed they were, they were palatable, at best.


text:
Q: How do I compute uncertainties in the positions transformed using Helmert transformation? I am familiar with Python, MATLAB and Mathematica. My data is given by Cartesian coordinates (positions in X,Y,Z (meters), standard deviations XX, YY, ZZ (meters) and a correlation matrix (XY, YZ, ZX).
For the Helmert transformation I will probably use Geodetic toolbox in MATLAB.


text:
Q: Linker errors for namespace being included multiple times I'm trying to fix an "explicit specialization in non-namespace scope" error using the method described in this post. So I managed to move the templated functions into a separate namespace, and I'm calling these functions from my class (see the code below).
The code now compiles, however I'm getting linker errors " already defined in main.obj" for all the functions in the namespace. I thought that adding #ifndef STYLE_H at the top would prevent the namespace from being included multiple times or am I missing something? How can I fix this error?
Below is my code (simplified):
#ifndef STYLE_H
#define STYLE_H

namespace hanzi {

namespace styleUtil {

    template <class T>
    T get(const QString& name, T defaultValue = T(), const Style* style = NULL, const Style* baseStyle = NULL) {
        // ...
    }

    template <>
    QColor get<QColor>(const QString& name, QColor defaultValue, const Style* style, const Style* baseStyle) {
        // ...
    }

    template <>
    ImagingEffect get<ImagingEffect>(const QString& name, ImagingEffect defaultValue, const Style* style, const Style* baseStyle) {
        // ...
    }

}

class Style : public QObject {

    Q_OBJECT

public:

    explicit Style(const QString& filePath);

    template <class T>
    T get(const QString& name, T defaultValue = T()) const {
        return styleUtil::get<T>(name, defaultValue, this, baseStyle_);
    };

};

}

#endif // STYLE_H

A: Regarding the original error,

I'm trying to fix an "explicit specialization in non-namespace scope" error

What that error means is that you cannot define member function template specializations inside a class definition. I.e. the following would be illegal:
struct Bar
{
    template <typename T> void boo() { }
    // template <> void boo<char>() { boo<int>(); }  // Error! Cannot specialize here
};

However, this is solved by simply placing the specialisation outside the class definition:
template <> void Bar::boo<char>() { boo<int>(); }  // Good.

(The latter position of the specialization is "at namespace scope", for example at global scope, which is what the error message wanted to tell you to do.)

A: A full specialization of a function template is no longer a template: it is a function.
As such, when you define it in a header, you need to add the keyword inline.
inline changes the behavior of C++'s "One Definition Rule" (ODR). Essentially, with inline the function must be defined in every translation unit where it's used, and those definitions must be effectively equal. Both accomplished by placing the definition in a header file.
inline also serves as a hint about optimization, but that second meaning is not guaranteed.
Also note, so this answer does not mislead you, there is no such thing as a partial specialization of a function template.


text:
Q: Administrator user receive Access Denied and Need Permission I want to move a file that is named resmon.exe from C:\Windows\System32 to D:\. While I logged with an Administrator user, but I can't move it and I receive something like Access-Denied!
As you see below I am Administrator :

This is output when I try to copy and paste normally :
When I right click and select paste :

When I click on Continue :

And this is output of Command-line windows, when I want to move the file via commands:
Note: I run CMD as Administrator

Q1: Why I receive Access-Denied?
Q2: How can I move the file?
Q3 : What is TrustedInstaller in third image? AND how I can have its permission?
Appreciate you time and consideration :)

A: *

*You receive access denied because TrustedInstaller is the owner of the file and this is a protected operating system file.

*The steps needed involve taking ownership of the file, as detailed in this question: how do i get administrative permission from trusted installer to delete a file in windows media player?

Before taking ownership I would suggest you to create a new restore point so that the system may be reverted back in case of any loss of data or irregular behavior.

*

*Locate the file or folder on which you want to take ownership in windows explorer

*Right click on file or folder and select "Properties" from Context Menu

*Click on Security tab

*Click on "Advance"

*Now click on Owner tab in Advance Security Settings for User windows

*Click on Edit Button and select user from given Change Owner to list if user or group is not in given list then, click on other users or groups. Enter name of user/group and click ok.

*Now select User/group and click apply and ok. (Check "Replace owner on sub containers and objects" if you have files and folder within selected folder)

*Click ok when Windows Security Prompt is displayed

*Now Owner name must have changed.

*Now click Ok to exist from Properties windows

*TrustedInstaller is a special service that handles windows updates and owns many system files. [Reference]What is TrustedInstaller service ?


text:
Q: Embed Complete GitHub Repository in a Web Page I have created a repository on Github. This repository contains a complete project with the folder structure and files. If I have to embed this code on my website, I can do that by creating Gists and adding them to my web page.
The problem is that I have a big project and adding snippets as Gists is not an easy task; also, it will not be user friendly either, as the visitors won't get the idea of the complete project.
So, I just want to embed the whole repository on my web page in such a way that the visitor can browse the code. Do you have any idea about that? Any API, Plug In, code sample etc.

A: A JQuery plugin was recently created that adds this functionality.  Take a look a repo.js.


text:
Q: Apache 2.4 + PHP 7.2 prefork mpm + file uploads lead to partial upload errors after 20 seconds I've been noticing an issue with a web application we have where our application's code that handles file uploads would intermittently encounter file upload error 3. I wasn't sure how our users were triggering this error but I do know that the ones who did would be uploading files through an unstable or slow internet connection (mobile hotspots, public wifi, etc). So I tested this by using Chrome Dev Tools' throttling feature (fast 3g) and uploading a 10mb file that would take somewhere around a minute or more to complete. We use the Dropzonejs library to handle uploads by the way with no chunking whatsoever. After exactly 22 - 23 seconds, the connection always seems to get aborted but Apache still proceeds to handle the incomplete request body it receives and passes it to PHP, leading to a partial upload error.
I can't seem to figure out what is causing this to happen. PHP config has max_execution_time and max_input_time set to 0 and -1 respectively. Post and upload max sizes are set relatively high and well, the file upload size doesn't even seem to matter. As long as the upload request takes longer than 22 - 23 seconds, the problem occurs. I tried disabling mod_reqtimeout and it didn't make a difference. Other things I've tried are tinkering with the apache Timeout value and disabling keepalive and it still gives me issues a little after 20 seconds always (that time comes from the browser's network tab).
I don't see anything in apache's error logs and the access logs make these requests appear legit, since apache still continues to handle the incomplete request like normal.
I initially thought it might be dropzonejs killing the ajax request connection but I have also tested the same code on my local dev environment which uses laradock (software versions will be slightly different. Still both apache 2.4 and php 7.2) and I cannot replicate the issue, so it couldn't be a client-side problem.

A: We had the same issue and solved thanks to this question.
However there is no need to entirely disable the module.
The problem is caused by this bug in Apache 2.4.39:
https://bz.apache.org/bugzilla/show_bug.cgi?id=63325
As suggested in the bug report you can explicitly set the default in Apache config file.

A: Looks like it was mod_reqtimeout stopping my post requests. I think my apache changes just weren't propagating fully when I initially tried disabling it (I'm guessing due to a mix of me using a graceful restart and having keepalive enabled).


text:
Q: Is space of Dirac measures Banach? Is the space of all Dirac measures on a set $\Omega$ Banach? With the total variation norm. I don't know what convergence means in this norm.. I mean how do I even think about it.

A: The space $V$ spanned by the Dirac measures on $\Omega$ is Banach $\Leftrightarrow$ $\Omega$ is finite.
$\textit{Proof:}$
($\Leftarrow$)
If $|\Omega|=n$, then $V\simeq \mathbb{R}^n$ as a linear space. Every finite dimensional normed space is Banach.
($\Rightarrow$)
Let $x_n\in\Omega$ be a countable sequence of distinct points. Then
$$\mu_n=\sum_{k=0}^n 2^{-k}\delta_{x_k}$$
is a Cauchy sequence in $V$ since
$$\| \mu_n-\mu_m\| = \left\|\sum_{k=m+1}^n 2^{-k}\delta_{x_k} \right\|\leq \sum_{k=m+1}^n 2^{-k} \|\delta_{x_k} \| =\sum_{k=m+1}^n 2^{-k}$$
which can be made arbitrarily small if one choose $n$ and $m$ sufficiently large. The limiting measure however is not in $V$, thus $V$ is not Banach.


text:
Q: API to install driver from driverstore Is there any APIs available to install the driver for my device say for example (PNPC031)  from the driverstore or from the inf folder?

A: Triggering plug-and-play detection for devices should install the driver for your device from the inf directory/driver store - if it finds a matching driver.
Check out the CM_Reenumerate_DevNode_Ex API:
http://msdn.microsoft.com/en-us/library/windows/hardware/ff539766(v=vs.85).aspx
If you know the path of your INF file you can install it with the Setup API:
http://msdn.microsoft.com/en-us/library/aa377398(v=vs.85).aspx

A: I dont know, if this it exactly you want, but for install driver from inf file may use ADVAPACK.DLL API.


text:
Q: How to run Netbeans makefile on terminal I am trying to run the netbeans makefile via my terminal of one of my C++ project
While executing
   Make

, I receive the following errors:
...
/bin/sh: 1: -o: not found
make[1]: *** [nbproject/qt-Debug.mk] Error 127
...

What should I do? Thanks in advance. Please note that I can easily build the program via Netbeans.
EDIT : I use ubuntu 13.04, netbeans 7.3, linux terminal.

A: I simply use:
make

or
make CONF=Release

in the project root (where the Makefile is located), and it works. I have a simple C++ project without anything extra.


text:
Q: Is there a way to see a Stack Exchange site's oldest users? In the 'Users' section of each Stack Exchange site, there is a 'New User' section that shows the newest members of the site. But, is there any good way to see the oldest members of each site?
I have found that when I type, for example, user:1 into the main search tab on this site, that it pulls up a post by Jeff Atwood, which means that he was the 1st user on this site (right?). But after user:4 (the four users that show up using the search tab are all moderators that work on the SO team), the method doesn't work anymore.

A: This query will grab the 100 oldest users on a site ordered by their id
SELECT TOP 100
id as [User Link]
From Users
where id != -1
ORDER BY id`

Link to query
or by their creation date
SELECT TOP 100
id as [User Link]
From Users
where id != -1
ORDER BY creationdate

Link to query
You can use the site switcher below the Run Query button to switch to the desired site,


text:
Q: Oracle OSB Business Service with OWSM Policy I am creating a Business Service in OSB and I want to select Policies -> OWSM Policies option. However on the screen to this service the option is greyed out. I can still select WLS9 Policies From WSDL or From Pre-defined Policy or WS-Policy Resource.
So I need to find out why OWSM is disabled.
Documentation suggests that this is because WSM Policy manager is not installed but I believe this is not the cause because:

*

*In Enterprise Manager I see a metadata repository named msd-owsm

*If I go to http://soabpm-vm.site:7001/wsm-pm/ and validate I see Policy Manager Status: Operational
I am using the 11.1.1.7 virtual box image (obtained from http://www.oracle.com/technetwork/middleware/soasuite/learnmore/vmsoa-172279.html) and I am running the Admin server only.
Can anyone suggest other places I can look.
Thanks
Robert

A: After logging into the WLS Admin Console select Deployments in the Domain Structure box on the left. (dev_soasuite --> Deployments)
Look for owsmInitializer
If you don't see it then you will need to install the OWSM EAR file.
To do this, click Install while still on the Deployments page and provide the path to the EAR file.
The general path is /"Middleware Home"/"OSB Home"/lib/common. For the Oracle Pre-installed VM the path should be /oracle/fmwhome/Oracle_OSB1/lib/common.
Click Next and choose the owsmInitializer.ear file. Continue till it is installed successfully.
Once installed go back to the Deployments page and ensure that owsmInitializer is deployed and active.
Restart the server and you should be able to select OWSM policies within OSB.


text:
Q: Getting multiple inputs from one line from a file in c++ Basically, I'm attempting to get three things from one line of code, read from a .txt file.  This will be repeated, but for now I only need to know how to get one line.  The line I'm reading looks like this:
Biology                 $11 12

So I want to get a string, and two ints, and completely ignore the $ (note, I cannot change the .txt file, so i have to leave the $ in)
So if I have
string subject;
int biologyscores[25];

The code I have is :
int biologyscores[25]; //array to store the integer values
std::string subject;   //string to store the subject the scores are for
std::ifstream infile("myScores.txt"); //declare infile to read from "myScores.txt"

infile >> subject >> biologyscores[0] >> biologyscores [1];  //read into string and int array

So the string will be used to check which subject these scores are for, and the scores themselves will be stored in an array biologyscores, indexed next to each other.
The problem is after this code executes, subject = "Biology" which is desired, but biologyscores at index 0 and 1 both seem to have junk numbers, not what I want to read into them.

A: You can use a dummy character variable which will "pick up" $ character:
char dummy_char;
infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1];  //read into string and int array

A: You can use seekg and tellg
    std::fstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
int temp;
infile >> subject;   //read into string
temp=infile.tellg(); //to get the position of $
infile.seekg(temp+1);// to move one step forward
infile>> biologyscores[0] >> biologyscores [1];//now you can read the int values


text:
Q: ghc fails to find a library that I built and installed with cabal new-install --lib I am building a Haskell library with Cabal that I would like to install to use in some other projects. I am using Windows PowerShell and new style Cabal commands. I have ghc 8.10.1 and Cabal 3.2.0.0 and used Chocolatey to install them. cabal new-install --lib builds and installs the library just fine and without warnings. From --verbose output I noticed that Cabal mentions folder C:\Users\Liisi\AppData\Roaming\cabal\store\ghc-8.10.1\package.db and it does contain my package.
However, when I try to compile a test project that consists of a single Haskell file that uses this library, ghc can't find the library. (The test project is not itself a Cabal project since I intend to use the library for tiny, mostly single-file projects.)
ghc Test.hs and ghc --make Test.hs both fail to find the library. ghc-pkg list does not list the name of my library. In another question (which was probably the wrong question to ask) I got the suggestion to try ghc -package-env=C:\Users\Liisi\.ghc\x86_64-mingw32-8.10.1\environments\default --make and this one does work - however, it would defeat the main purpose of making the library a Cabal project (convenience and usability).
I've also had an opportunity to test my package on OSX and everything worked as expected. So it's probably a Windows-specific issue.


text:
Q: How to set tag of select in proper way to have the size of "5" As you see in the snippet below , there are many options .
When I click the select tagment , a long list will appear before it become the size of 5 . You can try it . I don't want the wrong effect of it .
I tried mousedown event to prevent it  but failed . How to controll it ?

$("#select").click(function(event){
   event.preventDefault();
   event.stopPropagation();
   if ( !$(this).hasClass("size") ) {
    $(this).attr("size","5");
    $(this).addClass("size");
   } else {
    $(this).attr("size","1");
    $(this).removeClass("size");
   }
  });

   <select name="test" id="select">
    asdfasdf
    <option value="">option1</option>
    <option value="">option2</option>
    <option value="">option3</option>
    <option value="">option4</option>
    <option value="">option5</option>
    <option value="">option6</option>
    <option value="">option7</option>
    <option value="">option8</option>
    <option value="">option9</option>
    <option value="">option8</option>
    <option value="">option7</option>
    <option value="">option6</option>
    <option value="">option5</option>
    <option value="">option4</option>
    <option value="">option3</option>
    <option value="">option2</option>
    <option value="">option1</option>
    <option value="">option2</option>
    <option value="">option3</option>
    <option value="">option4</option>
    <option value="">option5</option>
    <option value="">option6</option>
    <option value="">option7</option>
    <option value="">option8</option>
    <option value="">option9</option>
    <option value="">option0</option>
    <option value="">option9</option>
    <option value="">option8</option>
    <option value="">option7</option>
    <option value="">option6</option>
   </select>

It can't become the size of one when blur.

A: try this
 $("#select").one("click",function(){
   if (!$("#select").hasClass("size")) {
     $("#select").attr("size", "5");
     $("#select").addClass("size");
   } else {
     $("#select").attr("size", "1");
     $("#select").removeClass("size");
   }
});

A: Saw this on another post the other day it had a good link to a working fiddle using jquery.
<select name="select1" onmousedown="if(this.options.length>8){this.size=2;}" onchange='this.size=0;' onblur="this.size=0;">

http://jsfiddle.net/aTzc2/
You can just set the this.size= to whatever you want.

<select name="select1" onmousedown="if(this.options.length>5){this.size=5;}" onchange='this.size=0;' onblur="this.size=5;">
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5</option>
    <option value="6">option 6</option>
    <option value="7">option 7</option>
    <option value="8">option 8</option>
    <option value="9">option 9</option>
    <option value="10">option 10</option>
    <option value="11">option 11</option>
        <option value="12">option 12</option>
    </select>

css:
#myselect-container {
    position:relative;
    height:9px;
    width:100px;
    /*for contain our absoulte select tag */
}
#myselect-container select {
   position:absolute;
   /*for put our list on other tag */

}

A:

$(function(){
   $("#test").click(function(event){
    event.preventDefault();
    event.stopPropagation();
    $(this).focus();
    if ( $("option").length > 5 ) {
     //选项超过五个
     if ( !$(this).hasClass("size") ) {
      //未打开状态时 展开下拉列表
      $(this).attr("size","5").addClass("size");
     } else {
      //已打开状态时 收回下拉列表
      $(this).attr("size","1").removeClass("size").blur();
     }
    } else {
     //选项不超过五个
     if ( !$(this).hasClass("size") ) {
      //未打开状态时 展开下拉列表
      $(this).attr("size" , $("option").length).addClass("size");
     } else {
      //已打开状态时 收回下拉列表
      $(this).attr("size","1").removeClass("size").blur();
     }
    }
   }).mousedown(function(event){
    event.preventDefault();
   }).blur(function(){
    $(this).attr("size","1").removeClass("size");
   }).change(function(){
    //blur之后才会触发change
    console.log($("option:selected").html());
   });
   $("option").click(function(event){
    event.preventDefault();
    console.log($(this).index());
    $("option").eq($(this).index()).prop("selected","selected");
   });

  });
#test{
  font-size: 30px;
  position: fixed;
  left: 200px;
 }

 <select name="test" id="test" >
  asdfasdf
  <option value=""></option>
  <option value="">asdfasfd2</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
  <option value="">asdfasfd3</option>
  <option value="">asdfasfd4</option>
 </select>


text:
Q: SQL Creating New Table that is based of a column in an already created table Here is an example of what I need, different values:
I already have table 1 created in the database.
Table 1: Person
Columns: PK->ID, Name, Favorite Color, Favorite Sport, etc..
This table is already in database and filled with values.
Now I want to create a second table, Table 2 which has a primary key of Favorite Sport column from my Table 1 and just one more column for the description.
Ex:
Table 2: Sports
Columns: Pk->Favorite Sport, description
I want to make sure I am just creating this table correctly, so I don't mess anything up. Would this be the correct syntax to use? (I will fill up the data separately after table is created.)
CREATE TABLE Sports (
Favorite_Sport Varcher(25),
Description Varcher(100),
PRIMARY KEY(Favorite_Sport),
Foreign KEY(Favorite_Sport) REFERENCES Person;
)
Thanks!

A: There are probably several ways to do this, but I think I'd go with
CREATE TABLE Sports
  (SPORT        Varchar2(25)
     CONSTRAINT PK_SPORTS
       PRIMARY KEY
       USING INDEX,
   Description  Varchar2(100));

(I changed the name of the primary key column on the SPORTS table to SPORT).
You really don't want nor can you have SPORTS.SPORT reference PERSON.FAVORITE_SPORT, as FAVORITE_SPORT is not a primary or unique key on PERSON. Instead, you want the foreign key relationship to go the other way around, with PERSON.FAVORITE_SPORT referencing SPORTS.SPORT:
ALTER TABLE PERSON
  ADD CONSTRAINT PERSON_FK1
    FOREIGN KEY (FAVORITE_SPORT) REFERENCES SPORTS(SPORT);

SQLFiddle here
Best of luck.


text:
Q: BigQuery Export schema - how to export complete event column from firebase I already link the firebase to bigquery, and everyday a new table gets created with the date stamp. The columns within the export can be found in the following link: https://support.google.com/firebase/answer/7029846?hl=en
BUT, there is not firebase analytics data(such as add_porduct_like, add_product_to_cart, and so on) being export. how can I export complete data into BigQuery.

A: Firebase Analytics data is already exported in those daily tables formed each day in Big Query.
What is required over here is to run queries in order to extract the relevant data.
Take a look at this doc for sample queries when Firebase Data is exported to Big Query.
In short, you need to make use of the schema and based on the Field Name, you can query the data obtained in Big Query by Firebase.

A: When you submit an event with parameters to Firebase Analytics, it is stored as an array in the column event_dim.params.
To get data from database, you will need to use this query (I'm using standard SQL):
SELECT
  event_dim.name AS event_name,
  event_dim.params AS event_params

FROM
  `project.your_app.app_events_20171109`,
  UNNEST(event_dim) as event_dim

If you want to get specific parameter, you'll also have to unnest another field:
SELECT
  event_dim.name AS event_name,
  event_dim.params AS event_params

FROM
  `project.your_app.app_events_20171109`,
  UNNEST(event_dim) as event_dim,
  UNNEST(event_dim.params) as params

WHERE params.key LIKE "add_product_to_cart"

You can read more about how Firebase Analytics stores data and how to use UNNEST function here: https://firebase.googleblog.com/2017/03/bigquery-tip-unnest-function.html


text:
Q: How can I do handwriting recognition each time a user has finished tracing a stroke? Basing myself on the code given by MSDN for Handwriting Recognition in windows 10 apps, I tried to have it recognize the handwriting automatically after the user has finished tracing an ink stroke rather than when clicking a button.
I have been able to do something similar in a Windows 8.1 metro app by calling my handwriting recognition method when the PointerReleased event was triggered in my canvas. It worked great and I tried to emulate the same behavior in UWP.
The PointerReleased event was not firing in the UWP app so I used the InkCanvas.InkPresenter.StrokeInput.StrokeEnded event instead to call this method :
async void RecognizeAsync(InkStrokeInput input, PointerEventArgs e)
{
    IReadOnlyList<InkStroke> currentStrokes =myInkCanvas.InkPresenter.StrokeContainer.GetStrokes();
    if (currentStrokes.Count > 0)
    {
        var recognitionResults = await inkRecognizerContainer.RecognizeAsync(myInkCanvas.InkPresenter.StrokeContainer, InkRecognitionTarget.All);

        if (recognitionResults.Count > 0)
        {
            // Display recognition result
            string str = "Recognition result:";
            foreach (var r in recognitionResults)
            {
                str += " " + r.GetTextCandidates()[0];
            }
            Status.Text=str;
        }
        else
        {
            Status.Text = "No text recognized.";
        }
    }
    else
    {
        Status.Text="Must first write something.";
    }
}

It's close to what I want to achieve, except the last stroke is not taken into account.
I guess that when the StrokeEnded event is triggered, the InkStroke has not yet been "processed" and thus it is not included in currentStrokes.
I tried to circumvent this problem by adding the Strokes corresponding to the InkStrokeInput of the event to the StrokeContainer I use as a parameter for the recognition :
InkStrokeContainer totalStrokes=new InkStrokeContainer();
if (currentStrokes.Count > 0) {
    totalStrokes= myInkCanvas.InkPresenter.StrokeContainer;
}
totalStrokes.AddStrokes(input.InkPresenter.StrokeContainer.GetStrokes());

var recognitionResults = await inkRecognizerContainer.RecognizeAsync(totalStrokes, InkRecognitionTarget.All);

But input.InkPresenter.StrokeContainer.GetStrokes() returns an empty List.
Is there a way for me to access the current Stroke when the event is triggered ? Or is there another event I could use to call the handwriting recognition after the stroke has been "processed" ?
Or another way to automatically recognize the handwriting for all the current InkStrokes alltogether ?

A: I have found a way to achieve the result I was expecting by calling my RecognizedAsync method when the InkCanvas.InkPresenter.StrokesCollected event is triggered.
From the MSDN documentation :

InkPresenter.StrokesCollected event
Occurs when one or more ink strokes are processed ("wet" to "dry") by the >application thread.
By default, an ink stroke is processed on a low-latency background thread and >rendered wet as it is drawn. When the stroke is completed (pen or finger >lifted, or mouse button released), the stroke is processed on the UI thread >and rendered dry to the InkCanvas layer (above the application content).


text:
Q: Universal mapping property and field extensions The following is a portion of notes for an introduction to Galois theory (I am not in the course):
There are possible details missing but I can't find a similar discussion using the universal property.

Let $f(x) \in k[x]$ be irreducible and for $\beta$ a root of $f(x)=0$ in a field extension $K$ of $k$, there is a $k$-algebra map $k(\alpha) \to K$ such that $\phi(\alpha)=\beta$. To prove this note that by the universal property of $k[x]$, there is a unique $k$-algebra homomorphism $k[x] \to \overline{k}$ sending $x$ to $\beta$. The kernel is the ideal generated by the minimal polynomial of $\beta$ which is $f(x)$, and thus this map factors through $k[x]/ f$ which is isomorphic to $k(\alpha)$

Question 1: Is $\alpha \in K$ (or $\alpha \in \overline{k}$, not entirely clear) also a root of $f(x)=0$? From my understanding, it is only true that $k(\alpha) \cong k[x]/f$ if $f(\alpha)=0$.
Question 2: Assuming $\alpha$ is a root. Using the idea of "factors trough" there exists $\psi: k[x]/f \to \overline{k}$ such that $\psi(\overline{x})=\beta$, where $\overline{x}$ represent the image of $x$ in the projection $k[x] \to k[x] / f$. I want to identify $\overline{x}$ with $\alpha$ through the isomorphism to get $\psi(\alpha)=\beta$. However, this is a bit hand wavy and we still only have that $\psi(\beta) \in \overline{k}$, and we want $\beta \in K$.
Anyway, I apologize for this question being a bit confusing and would appreciate any attempt at an explanation.

A: For the first question, yes, $\alpha$ ought to be a root. (It is  not necessarily in $K$.)
For the second question, in the same way as for $\beta$, you have an isomorphism $k[x]/f \to k[\alpha] = k(\alpha)$ sending $x$ to  $\alpha$; the inverse of that isomorphism does what you need.
It is not quite clear to me what you mean with:

and we still only have that $\psi(\beta) \in \overline{k}$, and we want $\beta \in K$.

First, I think you mean $\psi(\alpha)= \beta$. And, $\beta$ was assumed to be in $K$. I see that you are likely worried that the map goes to $\overline{k}$ and not $K$. But the image is just $k[\beta]$ which is in $K$. (It is not quite clear to me why $\overline{k}$ is brought up at that point at all.)


text:
Q: The 4 outputs of a linear model in R In R, after creating a linear model using the function model <- lm() and plotting it using plot(model), you will get back 4 graphs each displaying your model differently. Can anyone explain what these graphs mean?

A: plot.lm can produce 6 different diagnostic plots, controlled by the which parameter. These are:

*

*a plot of residuals against fitted values

*a Normal Q-Q plot

*a Scale-Location plot of sqrt(| residuals |) against fitted values

*a plot of Cook's distances versus row labels

*a plot of residuals against leverages

*a plot of Cook's distances against leverage/(1-leverage)

By default it will produce numbers 1, 2, 3 and 5, pausing between plots in interactive mode.
You can see them all in one go if you set up the graphics device for multiple plots, eg:
mdl <- lm(hp~disp,mtcars)
par(mfrow=c(3,2))
plot(mdl,which=1:6)

Interpretation of these plots is a question for Cross Validated, though ?plot.lm gives some basic information.


text:
Q: Can't to input file at aside bootstrap I try to create input file at aside bootstrap, but when i click the button for attach the file, pop-up browse file not working. do you know what the problem?

  File Upload

          Change
          Select file
          <input type="file" />

        Remove

A: Where you close aside tag? Close it and try again.

A: <!DOCTYPE html>

<title>Page Title</title>

  File Upload

          Change
          Select file
          <input type="file" />

        Remove

working fine with same code just added  as said in previous answer.
https://jsfiddle.net/14Lfb7kh/


text:
Q: Verb tenses when asking a question How can I establish time period when trying to ask someone about a question that was asked some time ago?

I asked you a question in my last email, but I wasn't sure (this is happening now) if it went through.

My asking took place sometime in the past, but my being not sure happened a little after my asking. So would it be more correct to say "I had asked you a question"? Just how much information is allowed to be assumed that they are happening around the same time?

I asked you a question, but you must have forgotten, since you still haven't gotten back to me.

Is it okay to use present perfect instead of simple past? I want to assume that my asking a question and her forgetting it happened around the same time, but it seems more natural to use present perfect here. Am I mistaken?
EDIT: I have additional questions:
I know this is kind of too late, but when I say "I asked you a question in my last email, but I wasn't sure (this is happening now) if you received it," don't I have to say "had received" in order to be correct? I think (write email -> try to send it -> be unsure if you received it) works here as well, but why do I have to use past perfect here?

A: There's nothing wrong with mixing verb tenses in a single sentence if that correctly conveys the time relationships. I think what you want to say in this case is something like:

I sent you an email in which I asked you a question, but I am not sure if you received it.

The sending of the email was in the past, so it is properly past tense. The unsureness is in the present, so "am not sure", present tense.
When you need the past perfect is when both events are in the past, but you want to make clear that one preceded the other.

I had sent you an email in which I asked you a question, but I was not sure if you had received it. But today I see your reply.

Now the "not sureness" is in the past, but "had sent" tells the reader that the sending came before the not sureness. Seeing the reply is in the present.

A: English has nice, implied time flow. It happens merely by logical sequence. Keep it simple and clear. Be direct.  Although this does not answer your specific concern about verb tense, it does address the underlying time problem of the communication itself. Here's some alternatives where the tense problems vanish:

I sent you an email with a question, but I am uncertain if you received
  it.

If you want to emphasize the time frames, then just do so explicitly:

I sent you an email yesterday morning, but as of noon today I'm unsure if you received it.

A: The guiding principle should be don't use Past Perfect unless you really have to.
The uncertainty occurred after the asking - chronologically, and in the narrative sequence of OP's text. That's what normally happens when you report a series of events...

I did this. Then I did that.

It's grammatically possible, but completely pointless in most contexts, to express that as...

I had done this. Then I did that.

In OP's second example, it's pretty much impossible to avoid Present Perfect with the word must. You could get away with ...but it must be [that] you forgot..., but it's a bit "starchy". Present Perfect is perfectly natural here.
Consider, for example,...

1: You didn't answer the doorbell when I rang, so you must have gone to work early.
   2: You didn't answer the doorbell when I rang, so you must have been in the shower.

Clearly in #1, the action in the present perfect clause (you going to work) happened before the simple past (I rang). But in #2, you being in the shower happened at the same time as I rang. That's not a problem in English; if the chronological relationship between actions is obvious from context, it doesn't always have to be made explicit by the verb forms.


text:
Q: TypeError: 'list' object cannot be interpreted as an integer The playSound function is taking a list of integers, and is going to play a sound for every different number. So if one of the numbers in the list is 1, 1 has a designated sound that it will play.
def userNum(iterations):
  myList = []
  for i in range(iterations):
    a = int(input("Enter a number for sound: "))
    myList.append(a)
    return myList
  print(myList)

def playSound(myList):
  for i in range(myList):
    if i == 1:
      winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

I am getting this error:
TypeError: 'list' object cannot be interpreted as an integer

I have tried a few ways to convert the list to integers. I am not too sure what I need to change. I am sure that there is a more efficient way of doing this. Any help would be very greatly appreciated.

A: range is expecting an integer argument, from which it will build a range of integers:
>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Moreover, giving it a list will raise a TypeError because range will not know how to handle it:
>>> range([1, 2, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object cannot be interpreted as an integer
>>>

If you want to access the items in myList, loop over the list directly:
for i in myList:
    ...

Demo:
>>> myList = [1, 2, 3]
>>> for i in myList:
...     print(i)
...
1
2
3
>>>

A: remove the range.
for i in myList

range takes in an integer. you want for each element in the list.

A: Error messages usually mean precisely what they say.  So they must be read very carefully.  When you do that, you'll see that this one is not actually complaining, as you seem to have assumed, about what sort of object your list contains, but rather about what sort of object it is.  It's not saying it wants your list to contain integers (plural)—instead, it seems to want your list to be an integer (singular) rather than a list of anything. And since you can't  convert a list into a single integer (at least, not in a way that is meaningful in this context) you shouldn't be trying.
So the question is:  why does the interpreter seem to want to interpret your list as an integer?  The answer is that you are passing your list as the input argument to range, which expects an integer.  Don't do that.  Say for i in myList instead.

A: You should do this instead:
for i in myList:
    # etc.

That is, remove the range() part. The range() function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.

A: since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.
use this
for i in range(len(myList)):
with this, we get the singular integer value which can be used easily

A: For me i was getting this error because i needed to put the arrays in paratheses. The error is a bit tricky in this case...
ie. concatenate((a, b)) is right
not concatenate(a, b)
hope that helps.

A: In playSound(), instead of
for i in range(myList):

try
for i in myList:

This will iterate over the contents of myList, which I believe is what you want. range(myList) doesn't make any sense.

A: def userNum(iterations):
    myList = []
    for i in range(iterations):
        a = int(input("Enter a number for sound: "))
        myList.append(a)
    print(myList) # print before return
    return myList # return outside of loop

def playSound(myList):
    for i in range(len(myList)): # range takes int not list
        if i == 1:
            winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

A: The error is from this:
def playSound(myList):
  for i in range(myList): # <= myList is a list, not an integer

You cannot pass a list to range which expects an integer. Most likely, you meant to do:
 def playSound(myList):
  for list_item in myList:

OR
 def playSound(myList):
  for i in range(len(myList)):

OR
 def playSound(myList):
  for i, list_item in enumerate(myList):

A: n=input().split()
ar=[]
for i in n:
    if i not in ar:
        ar.append(i)
print(*ar)

We usually pass string as a integer... for that we have to type "n"

A: when we facing like this error:

TypeError: st object cannot be interpreted as an st

it usually because we use X instead len(X) in for loops

#error
for i in range(df.index):
    pass

#currect
for i in range( len(df.index) ):
    pass

A: list cannot be interpreted as an integer when using range
for i in range(list): -> will not work
for i in list: -> will work


text:
Q: Need Get-ADUser to ehco out for user input I am trying to get Powerhsell to echo out for user input and query AD,  but am getting stuck right off the bat. When I run the code it simply returns no results with the variable. Also would like to be able to trim down the return to only a few Properties. If multiple users have similar names I will need to create a loop or something to work through the multiple accounts just have not got there yet. The goal of this is to be able to quickly view the necessary information about users on a help desk and eventually be able use it to do simple password resets and moving of objects. Very new at this and am very thankful for any advice or help. This site always dose me well. Thanks in advance.
$Firstname = Read-Host 'What is the users FirstName?'

$Lastname = Read-Host 'What is the users Lastname?'

Get-ADUser -Filter {(Name -Like "$Firstname*") -And (Surname -Like "$Lastname*")} -Properties LastLogondate LockedOut EmployeeID

A: This is a known issue with the -Filter parameter on AD cmdlets. You can use a variable by itself, but not inside of a string inside the filter.
So you can do this instead:
$Firstname = Read-Host 'What is the users FirstName?'
$Firstname = "$Firstname*"

$Lastname = Read-Host 'What is the users Lastname?'
$Lastname = "$Lastname*"

Get-ADUser -Filter {(Name -Like $Firstname) -And (Surname -Like $Lastname)} -Properties LastLogondate LockedOut EmployeeID

A: The argument to the Properties parameter is an array of strings, you need to separate those by comma:
Get-ADUser -Filter {(Name -like "$Firstname*") -and (Surname -like "$Lastname*")} -Properties LastLogondate,LockedOut,EmployeeID


text:
Q: How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winform in c#? How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winforms in c#?
I have been working on a Winforms Application and is using drag and drop functionality. I have the drag and drop functionality working, but need to make it more intuitive and user friendly.
Part of this will involve actually showing the item being dragged, preferably semi-transparent when dragging and also considered with the mouse down location at the item. What is the easiest way to do this?
The items I am dragging are custom user control(s) with text, pictures, data auto-created and in flow layout panel,but I am not even sure where to look for how to do this.
I added my code worked here :
A)   In the main form :
public main_form()
    {
        InitializeComponent();
        flowLayoutPanel1.AllowDrop = true;
        flowLayoutPanel1.DragDrop += new DragEventHandler(this.flowLayoutPanel1_DragDrop);
        flowLayoutPanel1.DragEnter += new DragEventHandler(this.flowLayoutPanel1_DragEnter);
        foreach (uploaded_items c in flowLayoutPanel1.Controls)
            c.MouseDown += new MouseEventHandler(c_MouseDown);
    }

    private void c_MouseDown(object sender, MouseEventArgs e)
    {
        uploaded_items data=new uploaded_items();
        foreach (uploaded_items c in flowLayoutPanel1.Controls)
        {
              if (c._isDragging == true) data = c;
        }
        Bitmap bmp = new Bitmap(data.Size.Width, data.Size.Height);
        data.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size));
        bmp.MakeTransparent(Color.White);
        Cursor cur = new Cursor(bmp.GetHicon());
        Cursor.Current = cur;
    }

    private void flowLayoutPanel1_DragEnter(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

    private void flowLayoutPanel1_DragDrop(object sender, DragEventArgs e)
    {
        uploaded_items data = (uploaded_items)e.Data.GetData(typeof(uploaded_items));
        FlowLayoutPanel _destination = (FlowLayoutPanel)sender;
        Point p = _destination.PointToClient(new Point(e.X, e.Y));
        var item = _destination.GetChildAtPoint(p);
        int index = _destination.Controls.GetChildIndex(item, false);
        _destination.Controls.SetChildIndex(data, index);
        _destination.Invalidate();

    }

B) In the user control :
public partial class uploaded_items : UserControl
{
    public uploaded_items()
    {
        InitializeComponent();
        AllowDrag = true;
    }

    public bool AllowDrag { get; set; }
    public bool _isDragging = false;
    private int _DDradius = 4;  //the min distance the mouse req to dragged so that drag action would be taken
    private int _mX = 0;        //positon on mouse down
    private int _mY = 0;

    protected override void OnGotFocus(EventArgs e)
    {
        this.BackColor = Color.SandyBrown;
        base.OnGotFocus(e);
    }

    protected override void OnLostFocus(EventArgs e)
    {
        this.BackColor = Color.Transparent;
        base.OnLostFocus(e);
    }

    protected override void OnClick(EventArgs e)
    {
        this.Focus();
        base.OnClick(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        this.Focus();
        base.OnMouseDown(e);
        _mX = e.X;
        _mY = e.Y;
        this._isDragging = false;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (!_isDragging)
        {
            // This is a check to see if the mouse is moving while pressed.
            // Without this, the DragDrop is fired directly when the control is clicked, now I have to drag a few pixels first.
            if (e.Button == MouseButtons.Left && _DDradius > 0 && this.AllowDrag)
            {
                int dist_x_dragged = e.X - _mX ;
                int dist_y_dragged = e.Y - _mY ;
                if (((dist_x_dragged ^ 2) + (dist_y_dragged ^ 2)) > _DDradius)
                {
                    DoDragDrop(this, DragDropEffects.All);
                    _isDragging = true;
                    return;
                }
            }
            base.OnMouseMove(e);
        }
    }

    protected override void OnMouseUp (MouseEventArgs e)
    {
        _isDragging = false;
        base.OnMouseUp(e);
    }

    #region Properties
    private string _title;
    private string _msg;
    private Image _icon;
    [Category("Custom Props")]
    public string title
    {
        get { return _title; }
        set { _title = value; lbl_title.Text = value; }
    }
    [Category("Custom Props")]
    public string msg
    {
        get { return _msg; }
        set { _msg = value; lbl_msg.Text = value; }
    }
    [Category("Custom Props")]
    public Image icon
    {
        get { return _icon; }
        set { _icon = value; pictureBox1.Image = value; }
    }
    #endregion
}

The primary drag and drop function is ok,
but I found I could not show the control / picture of the control dragging in this scheme:

*

*Limited area covered:
the bmp only appears when it's mouse down and dragged "carefully" on the user control, and it's only limited on the user control but not the text/ picture on the user control or the flow layout panel

*When I try to drag, the bmp disappeared

*the bmp is centered at mouse instantaneous location, but I wish it situated at the location at which the mouse initially down on the user control


text:
Q: The annotation for provider function of dagger module class I am developing an Android project with Kotlin and Dagger 2. I have a NetworkModule in which I define some provider functions.
@Module
object NetworkModule {
   @Provides
   @JvmStatic  // Here uses @JvmStatic
   internal fun provideSomething(): Something {
      ...
   }
}

I see some people use kotlin @JvmStatic and some use dagger's @Reusable to annotate the provider function:
@Module
object NetworkModule {
   @Provides
   @Reusable  // Here uses @Reusable
   internal fun provideSomething(): Something {
      ...
   }
}

And..some people use both:
@Module
object NetworkModule {
   @Provides
   @JvmStatic // Here use both @JvmStatic
   @Reusable  // and uses @Reusable
   internal fun provideSomething(): Something {
      ...
   }
}

I get confused. My two questions are:

*

*What is the motivation to annotate either @JvmStatic and/or @Reusable ? What's the reason behind or what is the benefit doing so?

*Which one is better to use @JvmStatic or @Reusable ? Or either one is fine? Or should I use both, if so what is the reason to use both then?

A: If you declare your module as a Kotlin object, @JvmStatic was required. That limitation was removed with dagger 2.25 You can also check this issue for more info.
If you use Dagger 2.25 or newer there is no reason to use @JvmStatic anymore.
From the @Reusable docs:

A scope that indicates that the object returned by a binding may be (but might not be) reused.
{@code @Reusable} is useful when you want to limit the number of provisions of a type, but there is no specific lifetime over which there must be only one instance.

If you inject the same thing in multiple places, and having the same instance is not a problem, this can help not to create a new object for each usage.
@JvmStatic and @Reusable are not related to each other, depending on your need you can use one, the other or both of them.


text:
Q: 2 QMainWindow glued - Size of Layout I have a main window that I center this way in main.cpp :
int main(int argc, char *argv[])
{
     QApplication app(argc, argv);
     QMainWindow *qmain = new QMainWindow;
     Ui_MainWindow ui;
     ui.setupUi(qmain);
     QRect r = qmain->geometry();
     r.moveCenter(QApplication::desktop()->availableGeometry().center());
     qmain->setGeometry(r);
     qmain->show();
     return app.exec();
}

In this "qmain" main window, I can create another QMainWindow and I try to make stick (or glue I don't know how to say) the two windows. Actually, I would like the right-top corner of the first one to be located at the left-top of the second one. For this, I use the following Ui_MainWindow's member function :
void Ui_MainWindow::generate_IC()
{
qmenu = new QMainWindow;
DiskMenu = new Ui_DiskGalMenu;
DiskMenu->setupUi(qmenu);
setInitialDiskMenuPosition(qmenu, this);
qmenu->show();
}

and the setInitialDiskMenuPosition :
void Ui_MainWindow::setInitialDiskMenuPosition(QMainWindow *MainWindow, Ui_MainWindow *parent)
{
        QSize size = parent->widget->size();
        QDesktopWidget* desktop = QApplication::desktop();
        int width = desktop->width();
        int height = desktop->height();
        int mw = size.width();
        int mh = size.height();
        int right = (width/2) + (mw/2);
        int top = (height/2) - (mh/2);
       MainWindow->move(right, top);
}

But the problem is that I don't get exactly what I want since the centralwidget size "parent-> widget->size()" only returns the size of the widget and not the whole "qmain" parent window. So I have a light shift because the borders of the "qmain" window are not taken in account like it is shown below :

If I could have access to the size of the whole parent window...
If anyone could help me

A: According to documentation you need to use parent->widget->frameGeometry().size() instead of parent->widget->size()


text:
Q: Infinitely Many Zeros I recently came across the following argument regarding the uniqueness of the zeros of a complex polynomial.
Please note that the proof that a complex polynomial of degree $m$ has $m$ zeros has been established at this point. The following is also not the complete proof of the uniqueness of the roots. I just want to focus on a particular passage from the proof that I need help clarifying.
Consider the following equation of two factorizations of the same complex polynomial of degree $m$, where $z, \lambda_i, \tau_i\in\mathbb{C}$, for $i=1\dots m$:
$$\left(z - \lambda_1\right)\left(z - \lambda_2\right)\dots\left(z - \lambda_m\right)
=
\left(z - \tau_1\right)\left(z - \tau_2\right)\dots\left(z - \tau_m\right)$$
Therefore, all $\lambda_i$ and $\tau_i$ are the zeros of the polynomial. Moreover, substituting $z=\lambda_i$, the resulting equation implies that $\lambda_i = \tau_j$ for some $j \in \left\{1\dots m\right\}$. To make it simple, let's relabel $\tau_j$ so that $\lambda_i = \tau_i$.
Now, consider $i = 1$. Dividing both sides by $z - \lambda_1$, we get
$$\left(z - \lambda_2\right)\dots\left(z - \lambda_m\right)
=
\left(z - \tau_2\right)\dots\left(z - \tau_m\right)$$
for all $z\in\mathbb{C}$ except possibly $z = \lambda_1$.
So far, with the exception of the word "possibly", it has been straight-forward and obvious to me. However, what comes next in the argument puzzles me:
"Actually, the equation above [after dividing by $z - \lambda_1$] holds for all $z\in\mathbb{C}$ because, otherwise, by subtracting the right side from the left side, we would get a non-zero polynomial that has infinitely many zeros."
That passage is a part of the proof of theorem 4.14 in "Linear Algebra Done Right", third edition (S. Axler).
Why would the alternative case imply a non-zero polynomial with infinitely many roots? Could someone please kindly show me?
Thank you.

A: If $f(z)=g(z)$ for every $z$ with the possible exception of $\lambda_1$ then $f(z)-g (z)=0$ whenever $z \in \mathbb C \setminus \{\lambda_1\}$. The set  $\mathbb C \setminus \{\lambda_1\}$ is an infinite set so $f(z)-g(z)=0$ has infinitely many solutions. This cannot happen if $f$ and $g$ are polynomials.


text:
Q: Unity Gradle Build failed (Failed to apply plugin [id 'com.android.application'] --> Your project path contains non-ASCII characters) I can´t build my App for Android, Im always getting the following Error Code as you can see in the picture
I already tried fixing it by putting "android.overridePathCheck=true" in to the gradle.properties as it says in the Error Code. But that didn´t worked for me.
This is my build.gradle file where the Error occurs on line 24.


text:
Q: PHP Redirect if on mobile device | Facebook tab page Looking for some help here:
we have a Facebook tab page, which does not work on mobile devices, so want a PHP redirect code that will redirect to a mobile version away form Facebook.
We added website URL to "Mobile web" on Facebook but can not get that to work, so would like a PHP code just to dump in.
Thank you.

A: You need to direct users to a Canvas App Page, which will automatically redirect mobile users to your mobile site url. You can then use javascript to redirect desktop users to your Page Tab.
Detailed instructions here: https://stackoverflow.com/a/15860533/121285


text:
Q: Is there a trick to invert a $3\times 3$ matrix? Consider any matrix which is $3\times3$ or bigger, but always square.
Is there a trick to invert quickly a matrix of this type without computing all the minors?
Thanks in advance.

A: Yes, there is: Gauß reduction, downwards, then upwards, on your matrix. Simultaneously, perform the same row operations on the unit matrix. The transformed unit matrix is the inverse.

A: Here is a method based on the Cayley-Hamilton theorem and Bocher's formula. Write the characteristic polynomial of an $n \times n$ matrix $A$ as $$\det(\lambda I-A)=\lambda^n+\beta_1\lambda^{n-1}+...+\beta_n.$$ The Cayley-Hamilton theorem says that$$A^n+\beta_1A^{n-1}+...+\beta_nI=0,\text {so} $$ $$A(A^{n-1}+\beta_1A^{n-2}+...+\beta_{n-1}I)=-\beta_nI$$ Thus, if $\beta_n=0$, the inverse does not exist; otherwise, the inverse is given by $$A^{-1}=\frac {-1}{\beta_n}(A^{n-1}+\beta_1A^{n-2}+...+\beta_{n-1}I)$$ To calculate the $\beta_{\nu}$ efficiently, use Bocher's formula $$\beta_1=-\mu_1,\text {    } \beta_{\nu}=\frac{-1}{\nu}(\beta_{\nu -1}\mu_1+...+\beta_1\mu_{\nu -1}+\mu_{\nu})$$ where $\mu_i=tr(A^i)$ The most effective way to use this formula is to evaluate the matrix polynomial by "synthetic division," so for $n=3$ we have $$A^{-1}=\frac {-1}{\beta_3}(A(A+\beta_1I)+\beta_2I)$$ Note that we do not have to store the powers of $A$. All we have to do is evaluate successive powers of $A$ and use them to calculate the traces and $\beta_i$as we go along. This method works over any field of characteristic 0 or of characteristic greater than $n.$ It also works over any commutative ring with identity in which all the elements 2,3, ... ,$n$ are invertible.

A: It is often much more work to invert the matrix and use the inverse than to just go ahead and solve the linear system of equations of interest in the first place. Sure, matrix inverses are of huge theoretical importance, but you know the saying: "In theory, theory and practice are the same; in practice, they are very different".


text:
Q: Singleton Windows Phone Native App How can I make sure there is only 1 running instance of my C# native app (RT) running on the device at anyone time?
If this was a desktop app there would be many ways to do this.
I have Googled but cannot find anything.  It could just be I am not putting the right search parameters in though!
Thanks

A: There can only ever be one instance of your app running at any time anyway.


text:
Q: Making a 2x image for retina display If I have an image that at normal resolution (72dpi) is 50x50, and I need to make a 2x resolution image for retina display, do I make it...

*

*50x50 at 144 dpi?

*100x100 at 144 dpi?

*100x100 at 72 dpi?

I need to appear the same size.  In other words, it can't look twice as large on a retina screen. (I'm new to this.)

A: There's no such thing as "dpi" in UIImage display. Just make the 2x version 100x100, twice the point count as the 1x version.


text:
Q: $P$ is a $p$-Sylow subgroup of $G$ and $H$ is a subgroup of $G$. Show that $P\cap H$ is contained in a $p$-Sylow subgroup of $H$
Let $G$ a group, let $H$ a subgroup of $G$ and let $P\in\operatorname{Syl}_p(G)$. Show that $P\cap H$ is a subset of some $U\in\operatorname{Syl}_p(H)$.

I know that \begin{align} |G| &=p^a\cdot nk,\\ |H| &=p^b\cdot n, \\ |P| &=p^a\end{align} for $b\leq a, (p,n),(p,k)=1$. The trivial case is $a=b$, but i don't know how to handle the case $b<a$.

A: Here is a little hint:
what's the order of the elements of $P \cap H $ ?
Then use Sylow's theorem to deduce that this is contain in a P-sylow of H.

A: Being the intersection of two subgroups, $P \cap H$ is a subgroup. Moreover, it is contained in $P$, so it has order $p^k$ for some $k$.
Let $Q$ be a maximal $p$-subgroup of $H$ that contains $P \cap H$. It has to exist since you can take $Q_0 = P \cap H$, and then search for a bigger $Q_1$. If you can't find it, then $Q=Q_0$. Otherwise, take $Q_1$ and search for a bigger $Q_2$, and so on. This process has to terminate, since $H$ is finite.
The key is that now, from Sylow's theorems, we know that every maximal $p$-subgroup of $H$ is a Sylow $p$-subgroup of $H$. So take $U=Q$ and you are done.


text:
Q: How to implement justify()-method in Java I am trying to make my own justify()-method that takes a string and an integer as input, and fils in spacing so that the string has the same length as the given integer. I have followed the answers to this question to do it.
I want my code to work somethinglike this:
Input = "hi hi hi" 20
Output = hi       hi       hi

My code looks like this:
//Add spaces to string until it is of desired length
static String justify(StringBuilder text, int width) {

    String[] inputLS = text.toString().split(" ");                //Split string into list of words

    //Sum the length of the words
    int sumOfWordLengths = 0;
    for (String word : inputLS){ sumOfWordLengths += word.length(); }

    int padding = width-sumOfWordLengths;                         //How much spacing we need
    String lastWord = inputLS[inputLS.length - 1];                //Last word in list of strings

    //Remove the last word
    ArrayList<String> withoutLast = new ArrayList<>
                                (Arrays.asList(inputLS).subList(0, inputLS.length - 1));

    StringBuilder result = new StringBuilder();                   //Initialize StringBuilder

    //Iterate over strings and add spacing (we do not add spacing to the last word)
    while (padding > 0){
        for(String word : withoutLast){
            result.append(word).append(" ");
            padding--;
        }
    }
    result.append(lastWord);                                      //Add the last word again
    return result.toString();
}

public static void main(String[] args) {
        // IO
        Scanner scanner = new Scanner(System.in);                       //Initialize scanner
        System.out.println("Please enter a string and an integer: ");   //Ask for input from user

        String line = scanner.nextLine();          //Get input-string from user
        String[] strings = line.split(" ");        //Split string at " " into list of strings
        String text = strings[0];                  //Get first element from list as string
        int width = Integer.parseInt(strings[1]);  //Get second element from list as an int

        // Create a string with three times the input text with spaces between
        StringBuilder forJustify = new StringBuilder();
        for(int i=0; i<3; i++){ forJustify.append(text).append(" "); }

        // Make sure the length of the string is less than the given int
        if (text == null || text.length() > width) {
            System.out.println(text);
            throw new IllegalArgumentException("Whoops! Invalid input. Try again.");
        }

        System.out.println("Gave this as input:\t" + forJustify);
        System.out.println("Justify:\t\t\t" + justify(forJustify, width));
    }

Which gives me this output:
Please enter a string and an integer:
hi 20
Gave this as input: hi hi hi
Justify:            hi hi hi hi hi hi hi hi hi hi hi hi hi hi hi

But I want this output:
Please enter a string and an integer:
hi 20
Gave this as input: hi hi hi
Justify:            hi       hi       hi

I know that there's something wring with the while-loop, but I don't understand how to fix it. All help is appreciated!

A: This solution is super simple using printf()
String test = "hi hi hi";
String[] tokens = test.split(" ");
int spacing = 20;
for (String token : tokens) {
    System.out.printf("%" + spacing + "s", token);
}
System.out.println();

The output (right-justified):
                  hi                  hi                  hi

For left-justify solution, just add - after the percent sign
for (String token : tokens) {
    System.out.printf("%-" + spacing + "s", token);
}
System.out.println();

outputs:
hi                  hi                  hi

UPDATE: Extracting justification as a function:
public static void justify(int spacing, boolean leftJustified, String...words) {
    for (String word : words) {
        System.out.printf("%" + (leftJustified ? "-" : "") + spacing + "s", word);
    }
    System.out.println();
}

To use,
public static void main(String[] args) {
    String test = "hi hi hi";
    String[] tokens = test.split(" ");
    int spacing = 20;

    justify(spacing, false, tokens); // right-justified
    justify(spacing, true, tokens); // left-justified
}

A: I came up with this solution after using the answer above:
static String justify(StringBuilder text, int width) {

        //Turn StringBuilder into an arraylist of strings
        String[] words = text.toString().split(" ");
        List<String> arraylist = Arrays.asList(words);

        //Find the length of the words and length of the padding needed
        int lengthOfWords = 3 * arraylist.get(0).length();
        int pad = width - lengthOfWords;

        //Add padding by using format on each word separately and then combine the strings and add last word
        String result;
        if (pad % 2 == 0){
            String temp1 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            String temp2 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            result = temp1 + temp2 + words[0];
        } else {
            pad--;
            String temp1 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            String temp2 = String.format("%" + (-(pad / 2) - 2) + "s", words[0]);
            result = temp1 + temp2 + words[0];

            //Turn string into arraylist
            ArrayList<Character> cs = new ArrayList<>();
            for (char c : result.toCharArray()){ cs.add(c); }

            //Add last whitespace between first and second word
            int index = nextSpaceIndex(cs);
            cs.add(index, ' ');

            //Turn arraylist back to string
            StringBuilder str = new StringBuilder();
            for (Character c : cs) { str.append(c); }
            result = str.toString();
        }
        return result;
    }

Which gives me this output:
Please enter a string and an integer:
hi 20
Justified:      |hi       hi       hi|


text:
Q: bash script array to memoize fibonacci sequence Unable to save Fibonacci values to an associative array for momoization. This script takes a Fibonacci index as an argument and returns the associated value sequence value. On each script execution a new sequence is generated from 1 to the argument value. Memoization should decrease the overall runtime.
fab.sh
if [ -f log.txt ]; then
  rm log.txt
fi

# initialize SAVED array
SAVED=()

# populate saved with $1 of 0's
for i in $(eval echo {0..$(($1-1))}); do
  SAVED[i]=0
done

fib () {
  local currentIndex=$1

  if [ "$currentIndex" -eq 0 ]
  then
    echo 0
  elif [ "$currentIndex" -eq 1 ] ; then
    echo 1
  elif [[ ${SAVED[$currentIndex]} -ne 0 ]]; then
    echo 'MEMOIZED' >> log.txt
    echo ${SAVED[$currentIndex]}
  else
    SAVED[$currentIndex]=$((`fib $[$currentIndex - 1]`+`fib $[$currentIndex - 2]`))
    echo ${SAVED[@]} >> log.txt
    echo ${SAVED[$currentIndex]}
  fi
}

if [[ $1 -eq 0 ]]
then
  echo "Sequence limit must be at least 1"
elif [[ $1 -gt 0 ]]
then
  fib $(($1 - 1))
fi

if fab.sh is ran using $ source fab.sh 5:
$ 3

It is printing the correct value but memoization is not functioning.
The log.txt file out is:
0 0 1 0 0
0 0 0 2 0
0 0 1 0 0
0 0 0 0 3

It seems like the 'SAVED' array is being reset or the assigned values aren't persisting. Since the SAVED array is a global variable I would think this would work. It could have something to do with how bash handles recursive functions.
Any insights would be greatly appreciated.

A: Instead of
SAVED[$currentIndex]=$((`fib $[$currentIndex - 1]`+`fib $[$currentIndex - 2]`))

you probably wanted to write
SAVED[currentIndex]=$((`fib $((currentIndex - 1))` + `fib $((currentIndex - 2))`))

However, that wouldn't solve the actual problem. As we can see from your log, the memoization array has at all times at most one entry. How is it possible that the last entry is filled, but the entries which are needed to compute that last entry are 0? The answer is »subshells«!
When you call your function using a subshell $(fib ...), the changes that function makes on variables are only inside the subshell.
To work around the problem, you have to either use a file for memoization or find a way to call your function without a subshell.
Here is how I would have written that scrip, if I were forced to use your current approach. Please note that there are better ways to compute the fibonacci numbers and better languages to program these computations in.
#! /bin/bash
memo=(0 1)
fib() {
        >&2 printf %s "fib($1) memo=(${memo[*]}) => "
        local n="$1"
        if [ "${memo[n]+x}" ]; then
                >&2 echo lookup
                return
        fi
        >&2 echo compute
        fib "$((n-1))"
        fib "$((n-2))"
        ((memo[n]=memo[n-1]+memo[n-2]))
}
fib "$1"
echo "${memo[$1]}"

Lines starting with >&2 are only there to print debug information; you can delete them. To suppress debug output, run the script as script.sh 12 2> /dev/null.
Improvements:

*

*To work around the subshell problem, don't echo the function result and store it using var=$(fib ...), but remain silent and directly store the result in a designated global variable. Here we don't need a new variable because we already have the memoization array. We first call fib x to make sure that array entry x is there, then we access that entry with memo[x].

*Instead of printing to a log, print debug information to stderr using >&2 echo.

*By storing fib(0)=0 in the memoization array, we don't have to use an index offset.

*Embed the trivial cases 0 and 1 directly into the memoization array.

*Don't initialize the array with 0.
${memo[n]}+x expands to x if and only if fib(n) is already memoized.


text:
Q: Scheme String Help I am trying to write a function that evaluates to the number of distinct characters in the input string str. So for example (distinct-char "eeeiicczz") would return 4. I need some help with my code. This is what I have.
(define string-contains
  (lambda (str char)
    (if (equal? str "")
        #f
        (if (char=? (string-ref str 0) char)
            #t
            (if (not (char=? (string-ref str 0) char))
                (string-contains (substring str 1 (string-length str)) char))))))

(define unique-chars
  (lambda (str)
    (cond
      ((equal? str "") "")
      ((equal? (string-length str) 1) (string-ref str 0))
      (else
      (if (equal? (string-contains (substring str 1 (string-length str)) (string-ref str 0)) #t)
          (unique-chars (substring str 1 (string-length str)))
          (string-append (substring str 0 1) (substring str 1 (string-length str))))))))

(define distinct-char
  (lambda (str)
    (string-length (unique-chars str))))

I am limited to using these Built in functions:
(if x y z), (cond ...),
(read)
(string-length x)
(string-ref str x)
(substring x y)
(string-append x y)
(equal? x y), (char=?)
(remainder x y), (quotient x y)
(max ...), (min ...)
(+ x y), (- x y), (* x y), (/ x y)
(> x y), (< x y), (<= x y), (>= x y)
(and x y), (or x y), (not x y)

A: Since it's possible to convert a string to a list, it would be much easier to do that and use the built in list functions. (Note: the following code is in Racket. Since it's pretty much Scheme, I'm assuming these functions exist. If they don't check your docs for something similar)
(define (distinct-char str)
  (length (remove-duplicates (string->list str))))

Here is a template you can fill in. Replace the comments with what you think should happen in each situation. Good luck!
(define (empty-string? str)
  ( #| What property does an empty string have? Add a simple boolean expression here. |# )

 (define (char-exists? str char)
  (cond
    [(empty-string? str) ( #| If the string is empty, does the character exist? |# )]
    [else ( #| Check the first character in the string. If it is what we're looking for
               we're done! If it's not call this function on the rest of the string. |# )]))

(define (unique-chars str)
  (cond
    [(empty-string? str) ( #| What should you return if the string is empty? |# )]
    [(equal? (string-length str) 1) ( #| What should you return if the string is one character long? |# )]
    [else ( #| If the character at the beginning of the string exists in the rest of the string, ignore it
               and preform recursion on the rest of the string. If it doesn't, append the character to
               the result of this function on the rest of the string. |# )]))

(define (distinct-char str)
  (string-length (unique-chars str)))

A: One of the reasons you learn stuff in scheme is it trains you to build up useful building blocks yourself, and then hook those building blocks together.
In this case, the general approach I would recommend is to write a function:
(string-contains str ch)

That returns #t or #f depending on whether or not str contains the character ch, and then use that to define a function:
(unique-chars str)

that returns a string of the unique characters in str (you scan str, building up your answer, and at every spot see if the next character is already in the answer string you're building, and if not, add it to your answer string).
Then, the function you wanted is just
(string-length (unique-chars str))

A: You can keep and pass along a list of every distinct character that you've come across before.  That way, every time you check a new character, you look it up in your list to see if you've already seen it before.  If it's not in your list, then it's a new character and you can add it to your list.
Homework question, so I'm not writing code in the answer.


text:
Q: jquery accordion multi form in one page and when one form do not submit the other form remain lock I need to make some changes to this page: http://sirpaff.selgis.com/v1.1/CrearNuevaFichaFamiliar.php
As you can see there has a jQuery script,  this http://jqueryui.com/accordion/
I need that when a user is inserting data into the form "Datos Generales y del Jefe(a) de Familia"
the other Section of Accordion remain locked until the user completes the entire("Datos Generales y del Jefe(a) de Familia") form and give him to "Guardar"(submit).
Then, when save the information, is open the following next Section of Accordion "Carácteristica de la Vivienda"
Again similarly When fill the "Carácteristica de la Vivienda" section and click to the "Guardar" the following next section "Integrantes de la Familia" will be open.

A: There are two parts to this.
Firstly you need to handle form submission yourself : http://geekswithblogs.net/renso/archive/2009/09/09/intercept-a-form-submit-with-jquery-and-prevent-or-allow.aspx This prevents the page from reloading. You will need to send the data to the server yourself using an ajax call: http://api.jquery.com/jQuery.ajax/
Secondly you want to disable accordion sections by intercepting beforeActivate:
$( "#accordion" ).accordion({
        beforeActivate: function( event, ui ) {
                          if ( ui.newHeader.text() === "Don'tActivateMe" ){
                                 event.preventDefault();
                           }
                        }
 });


text:
Q: Joining strings at compile time I want to join file names and image formats at compile time.
The following example doesn't work, because string[] can't be evaluated at compile I suppose...
immutable imageFormats = ["bmp", "jpg", "gif", "png"];

template fileNamesWithImageFormat(string[] fileNames)
{
    string[] fileNamesWithImageFormat() {
        string[] ret;
        ret.length = imageFormats.length * fileNames.length;

        for (int j = 0; j < fileNames.length) {
            for (int i = 0; i < imageFormats.length; ++i) {
                ret[j * fileNames.length + i] = fileNames[j] ~ "." ~ imageFormats[i];
            }
        }

        return ret;
    }
}

It fails with the error message:
Error: arithmetic/string type expected for value-parameter, not string[]

I need this to be finally fed into import(). How can the error be resolved?

A: You are over-complicating this a bit.
CTFE (Compile-Time Function Execution) should suit here. You can just write usual  function that processes string[] input and use it in compile-time expressions. There are some limitations, but your code is pretty CTFE-ready, so there is no need for templates.
You have also minor error in your indexes. Corrected version that works at compile-time:
import std.algorithm, std.array, std.range;
import std.stdio;

string[] modify(string[] names)
{
    if (!__ctfe)
        assert(false);

    immutable string[] imageFormats = ["bmp", "jpg", "gif", "png"];

    string[] ret;
    ret.length = imageFormats.length * names.length;

    for (int j = 0; j < names.length; ++j) {
        for (int i = 0; i < imageFormats.length; ++i) {
            ret[j * imageFormats.length + i] = names[j] ~ "." ~ imageFormats[i];
        }
    }

    return ret;
}

enum string[] input = ["one", "two"];

pragma(msg, modify(input));

void main() {}

Or check it out on DPaste: http://dpaste.1azy.net/7b42daf6
If something is unclear in provided code or you insist on using other approach - please leave a comment here. D has plenty of different tools for compile-time tasks.

A: Upon further searching, it turned up http://forum.dlang.org/post/jezkyrguyoshofciuxjq@forum.dlang.org.
This is a bug as of DMD 2.061, a workaround is to declare fileNames as alias.


text:
Q: Angular 4 integration with Struts 2 I am new to Angular 4. Is it possible to integrate Angular 4 with Struts and Hibernate ?
If yes, then where to keep web.xml, JSP files, Hibernate etc. Where to keep struts jar?
Any example code or documentation link will be of great help.

A: Angular2/4 app you develop in the separate project or module, probably even using separate IDE. The backend might use any technology that has a web API endpoints.
If the backend is Struts then endpoints should be mapped via the action mapper.
Also Struts doesn't work with Hibernate without integration, you should integrate Struts with Hibernate, or Spring with Hibernate and then integrate Struts with Spring.


text:
Q: Plotting dataframe in r I have the following dataframe (1:10):
   Date Avg.Join.Delay Min.Join.Dely Max.Join.Dely    ACCOUNT STB_TYPE  MARKET
1  6/5/2015      199.20000            51           396 2063207586  IPH8010 Seattle
2  6/5/2015       77.68750            50           145 2063207586  IPW8000 Seattle
3  6/5/2015       80.00000            78            81 2063221752  IPW8000 Seattle
4  6/5/2015       72.25000            52            81 2063231994  IPW8000 Seattle

What I am trying to do is to plot a graph of the Average delay with regard to its Min and Max. I want to see the correlation of these three attributes in a visual way but I can't figure out a way doing so. Below is a reproducible example:
df <- data.frame(Date= c('6/5', '6/6', '6/7'),
                  Avg = c(600, 500, 400),
                  Min = c(25, 85, 40),
                  Max = c(65, 28, 39),
                  Account = c(504,316,920),
                  Type = c('x','y','z'),
                  Market = c('a','b','c'))

A: This seems a good use of geom_pointrange(), but it will make no sense for your example, because your Avg is higher than your Max, and on 6/7 your Min is higher than your Max.
library(ggplot2)
ggplot(df, aes(x=Date, y=Avg)) +
  geom_pointrange(aes(ymin=Min, ymax=Max))


text:
Q: How to execute an SAP transaction code either using Python or Java? We would like to execute transaction code SM04 so that we get users' details.
We want to connect to the underlying API. Could you tell me the Python packages or Java jars?

A: Question clarified. Here you go:

*

*Install SAP Java Connector: http://help.sap.com/saphelp_nwpi711/helpdata/en/48/7080a5872c1b5ae10000000a42189c/content.htm

*Write code to execute function module TH_USER_LIST


text:
Q: ORA-64219: invalid LOB locator encountered We migrated from oracle c12 to c19. And now we have simple test case that fails:
//arrange
string data = new string('x', 5000);
var connection = tm.GetConnection();

var createTableCmd = connection.CreateCommand(false);
createTableCmd.Text = "CREATE TABLE xx_temp (id NUMBER, text_long NCLOB, text_short NVARCHAR2(2000))";
createTableCmd.ExecuteNonQuery();

//act
var insertCmd = connection.CreateCommand(false);
insertCmd.Text = "INSERT INTO XX_TEMP (text_long) VALUES (@p1)";
var param = new OracleParameter("@p1", OracleDbType.NClob, data.Length, System.Data.ParameterDirection.Input);
param.Value = data;
insertCmd.Parameters.Add(param);
var insertResult = insertCmd.ExecuteNonQuery();

The last line fails with the error: ORA-64219: invalid LOB locator encountered
We're using Devart.Data.Oracle component. And I have no idea what is wrong.
What is interesting is that when I'm trying to connect to DB from powershell using Oracle.ManagedDataAccess.dll, I have no problems using similar code.

A: Please upgrade to dotConnect for Oracle v9.11.980. The following code works with v9.11.980 and Oracle 19c:
//arrange
string data = new string('x', 5000);
var connection = new OracleConnection();
connection.ConnectionString = @"User Id=****;Password=****;Server=YOUR_HOST/YOUR_SID;Direct=true;";
connection.Open();

var createTableCmd = connection.CreateCommand();
//createTableCmd.CommandText = "DROP TABLE xx_temp";
//createTableCmd.ExecuteNonQuery();
createTableCmd.CommandText = "CREATE TABLE xx_temp (id NUMBER, text_long NCLOB, text_short NVARCHAR2(2000))";
createTableCmd.ExecuteNonQuery();

//act
var insertCmd = connection.CreateCommand();
insertCmd.CommandText = "INSERT INTO XX_TEMP (text_long) VALUES (:p1)";
var param = new OracleParameter("p1", OracleDbType.NClob, data.Length, System.Data.ParameterDirection.Input);
param.Value = data;
insertCmd.Parameters.Add(param);
var insertResult = insertCmd.ExecuteNonQuery();


text:
Q: Getting info for a specific Date and Subtracting two Dates So this is really more like two questions combined because it's for the same table I'm trying to gather all this info from
ANSWERED BY TMNT IN COMMENTS For question one: I'm trying to collect some info based on MAX Date. The table contains various SiteID entries with various dates with various amounts of info I want retrieve.  However, I just want to capture just the MOST recent date date for each site and all it's corresponding info.
When writing this below query I get all the right SiteIDs
Select
sn.siteID,
MAX(sn.CreationDate)
From SiteNotifications sn
Group By sn.SiteID
Order By sn.SiteID

However, as soon as I start writing in the other info I need it's start showing me dates from previous notifications rather than the MAX date.
Select
sn.siteID,
MAX(sn.CreationDate),
sn.NotificationMessage,
sn.CreatedByUserID
From SiteNotifications sn
Group By sn.SiteID, sn.NotificationMessage, sn.CreatedByUserID
Order By sn.SiteID

I'm pretty sure this has to do with the fact that since there are different users, different notification messages, etc. they'll show up because they're "unique" rows.  But now that MAX isn't working I'm totally not sure how to proceed.
ANSWERED BY LANGE IN COMMENTS - Second Question: I'm trying to subtract two DateTime times to display the amount of days between them.
I write this
Select
DateAdd(d,-mino,maxo)
FROM
(Select
sn.SiteID,
MAX(sn.CreationDate) Maxo,
MIN(sn.CreationDate) Mino
From SiteNotifications sn
Group By sn.SiteID)a

And it gets me an error message that reads
Operand data type datetime is invalid for minus operator.
I tried converting the dates by using CAST and CONVERT but keeps giving me the same problem.  :(

A: For the First question since you need the max date by site Id irrespective of the other fields  you can change your query to.
Select
 sn.siteID,
 MaxCreationDate.Maxo,
 sn.NotificationMessage,
 sn.CreatedByUserID
From SiteNotifications sn
INNER JOIN (SELECT SiteId, MAX(CreationDate)Maxo FROM SiteNotifications GROUP BY SiteId      )MaxCreationDate
 ON MaxCreationDate.SiteID = sn.SiteID AND sn.CreationDate = Maxo
 Group By sn.SiteID, sn.NotificationMessage, sn.CreatedByUserID, MaxCreationDate.Maxo
 Order By sn.SiteID

OR use the row_number and partition concept.
 WITH CTE AS (
  Select
  siteID,
  CreationDate
  NotificationMessage,
  CreatedByUserID,
  Row_Number()OVER(Partition by siteID ORDER by CreationDate desc)RN
  From SiteNotifications)
 SELECT * FROM CTE
 WHERE RN =1


text:
Q: Select a hyperlink in one column based on "X" in adjacent column So I'm fairly new to VBA, and I have been struggling with trying to get my macro to work.
Essentially what I'm trying to do is have a program read down a column, and for every "X" located in that column, the corresponding hyperlink in the adjacent column will be selected.
Sub Select_Hyperlinks()

Dim rng As Range, cell As Range, sel As Range
Dim sht As Worksheet

For x = 1 To 6
    Set sht = Sheets("Generator")
    Set sel = cell.Offset(-1, 0)

    Set rng = Intersect(sht.Range("D4:D9"), sht.UsedRange)
    For Each cell In rng.Cells
        If (cell.Value) <> "X" _
        Then
            If sel Is Nothing Then
            Set sel = cell.Offset(-1, 0)
            sel.Select
        End If
        Next cell
    End If
    Next x

End Sub

I also tried a simpler idea using the Find and FindNext functions and for each X, I tried to get it to select and activate the cell in the adjacent column, but also with no luck. It seems I always get snagged up on the .Offset function.
EDIT:
Here's what I've managed to come up with, after some further research. I've adapted this from a macro designed to delete all empty rows.
Sub AutoOpen()

Dim xlastcell As Integer
Dim xcell As Integer
xcell = 1

Range("C200").End(xlUp).Select
xlastcell = ActiveCell.Cells   'This used to say ActiveCell.Row but I want a single cell'

Do Until xcell = xlastcell

    If Cells(xcell, 1).Value = "X" Then
    Cells(x, 1).Select
    ActiveCell.Offset(0, -1).Select   'I'm also unable to get this function to work'
    Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True

    xcell = xcell - 1
    xlastcell = xlastcell - 1

    End If

xcell = xcell + 1

Loop

End Sub

A: Are you saying that if there is an X in the one column, you want to open the hyperlink?
EDIT:
Use this and change things to match your variables.
Sub asdhkl()
Dim c As Hyperlink
Dim i As Range
For Each i In Sheets(1).Range("b1:b3")
    If i = "x" Then
        Set c = i.Offset(0, -1).Hyperlinks(1)
        c.Follow
    End If
Next i
End Sub


text:
Q: Dynamically add or remove text fields and insert into a single row I want to Add or Remove input fields and insert data into a single row in a table and my problem is after generating input fields I can't insert every fields data into a single row
My data is inserted in a separated row.
Please watch my code. Especially php code ( Line no 10 in name.php )
Please Click here and watch my html codes
Please Click here and watch my php codes

A: Try this code:
this code replace in name.php file.
<?php
 extract($_POST);
 $name=implode(",",$_POST['name'])
 $connect = mysqli_connect("localhost", "root", "", "test");

 $sql = "INSERT INTO tbl_name(name) VALUES('".$name."')";

 mysqli_query($connect, $sql);

 ?>


text:
Q: RxJava - add headers in a sorted list of emitted items Let's say I have a list of items and emit it:
Observable<Item> items = Observable.fromIterable(list);

Now I want to have a second observable that inserts headers. If a header must be inserted or not can be decided by comparing two consecutive items. Any ideas how to do that?
Logic is like following:

*

*compare two consecutive items

*if they need different headers, add a new header item between them

*if not, just emit the items

I need something similar to scan but the operator must emit the input items + an optional header item...

A: You can buffer with a sliding window and do a flatMap over the overlapping windows to insert headers/separators between items:
Observable.just(1, 3, 4, 5, 7, 8, 10, 12, 14)
.buffer(2, 1)
.flatMapIterable(v -> {
    if (v.size() <= 1) {
        return v;
    }
    if (v.get(1) - v.get(0) > 1) {
        return Arrays.asList(v.get(0), 1000);
    }
    return Collections.singletonList(v.get(0));
})
.subscribe(System.out::println);


text:
Q: How to list all classes implementing a specific interface in Android? In Java (NetBeans), I realized it with...
ClassPathLoader pathLoader = new ClassPathLoader(".");
try {
//get Classes
Hashtable ht = pathLoader.getClasses();
Set s = ht.keySet();
Iterator iter = s.iterator();
String fullName = null;
    while(iter.hasNext()) {
        try {
        fullName = (String) iter.next();
        //create class
        Class cls = Class.forName(fullName);
        //get interface from the class
        Class[] interfaces = cls.getInterfaces();
        for(int i = 0; i < interfaces.length; i++) {
        if(interfaces[i].getName().equals("IMyObserver.IFeature")) {

        //Field field = cls.getDeclaredField("LOCATION");
        //String location = (String)field.get(null);
        Constructor cons2 = cls.getDeclaredConstructor(List.class);

        Object oo = cons2.newInstance(qList);

        System.out.println(fullName);
        }
    }

This works very well, but in Android it does not work. I think the problem is at the ClassPath. Does anyone have an idea?