text:
Q: How do i add pdf text annotation review status using itextsharp I am working using itextsharp in c# .net. I have multiple text annotation and multiple reply to that annotation, everything working fine but when i try to add review status (Eg: Accepted,Rejected,None etc..) to the annotation. It is not showing in pdf.
I had export the data file from pdf and checked. Annotation's review status is coming in data file. If i changed the status flag of annotation review status  /F 28/ to /F 30/ in data file,review status showing correctly in pdf.
How do i set status flag of annotation as /F 30/. I tried all annotation flag in itextsharp /F 30/ not coming.
Annotation tag in exported pdf data file
2 0 obj /Contents(brit mkt level 1 no 5)/F 28/M(D:20160928170753+05'30') NM(1888890568)/Page 0/Rect[231.0 605.0 249.0 625.0]/Subtype/Text/T(BM/01 Britania marketing | Marketing)

Annotation status review tag in exported pd data file
7 0 obj /Contents(None by Britania commercial)/F 28/IRT(1888890568)/M(D:20161006111625+05'30')/NM(63aafcf6-742e-4ffb-9465-2dba3c731bf2)/Page 0/Popup 8 0 R/Rect[231.0 605.0 249.0 625.0]/State(None)/StateModel(Review)/Subtype/Text/T(Britania commercial) endobj

8 0 obj /F 28/Open false/Page 0/Parent 7 0 R/Rect[2160.0 505.0 2340.0 625.0]/Subtype/Popup/Type/Annot endobj

C# code used is given below.
 var reader = new iTextSharp.text.pdf.PdfReader(originalReader);
             var fout = new MemoryStream();
            if (cmnts.ContainsKey("reviseStatus"))
                {
                    switch (Convert.ToInt16(cmnts["reviseStatus"]))
                    {
                        case 0:
                            reviseStatus = "None";
                            break;
                        case 1:
                            reviseStatus = "Accepted";
                            break;
                        case 2:
                            reviseStatus = "Cancelled";
                            break;
                        case 3:
                            reviseStatus = "Completed";
                            break;
                        case 4:
                            reviseStatus = "Rejected";
                            break;
                        default:
                            reviseStatus = "None";
                            break;
                    }
                    revisedOn = cmnts.ContainsKey("revisedOn") ? cmnts["revisedOn"].ToString() : "";
                    revisedBy = cmnts.ContainsKey("revisedBy") ? cmnts["revisedBy"].ToString() : "";
                }

                if (noteArray.Count == 1)
                {
                    var fstTemp = new MemoryStream();
                    var stamper = new PdfStamper(reader, fstTemp);
                    if (!string.IsNullOrEmpty(reviseStatus))
                    {
                        var writer = stamper.Writer;
                        var page = reader.GetPageN(pageNo);
                        var annots = page.GetAsArray(PdfName.ANNOTS);
                        var count = annots.Size;
                        var notes = (Dictionary<string, object>) noteArray[0];
                        for (var l = 0; l < count; l++)
                        {
                            var sticky = annots.GetAsDict(l);
                            var cmntid = sticky.Get(PdfName.NM);
                            if ((cmntid !=null?cmntid.ToString() : "") == notes["commentId"].ToString())
                            {
                                var stickyRect = sticky.GetAsArray(PdfName.RECT);
                                var stickyRectangle =
                                  new iTextSharp.text.Rectangle(
                                      stickyRect.GetAsNumber(0).FloatValue,
                                      stickyRect.GetAsNumber(1).FloatValue,
                                      stickyRect.GetAsNumber(2).FloatValue,
                                      stickyRect.GetAsNumber(3).FloatValue);
                                var replySticky = PdfAnnotation.CreateText(writer,
                                    stickyRectangle,
                                    revisedBy, reviseStatus + " by " + revisedBy, true, null);
                                replySticky.Put(PdfName.IRT, annots.GetAsIndirectObject(l));
                                replySticky.Put(PdfName.M,new PdfDate(convertTimestamp(Double.Parse(revisedOn))));
                                replySticky.Put(PdfName.STATE, new PdfString(reviseStatus));
                                 var n = sticky.GetAsNumber(PdfName.F);
                                replySticky.Put(PdfName.F, new PdfNumber(n.IntValue |PdfAnnotation.FLAGS_HIDDEN)); //PdfAnnotation.FLAGS_HIDDEN
                                replySticky.Put(PdfName.OPEN,PdfBoolean.PDFFALSE);
                                replySticky.Put(new PdfName("StateModel"), new PdfString("Review"));
                                var canvas = stamper.GetOverContent(pageNo);
                                canvas.AddAnnotation(replySticky,true);
                            }
                        }
                    }
                    fout = fstTemp;
                    stamper.Close();
                    reader = new iTextSharp.text.pdf.PdfReader((byte[]) fout.ToArray());
                }

Does anyone know how to do it?
Thanks in advance
SHIJIL


text:
Q: How to get the number of pages/posts from a Wordpress RSS feed with a Java servlet I am coding a servlet, where I want to read in Wordpress feed. How do i get number of posts/pages from the wordpress feed? Is there any URL parameter?
And assuming that each page has fixed # of posts (6 in my case)

A: Wordpress feeds use RSS, so you need to use a Java RSS library.
Question (and answer) here: java library for reading RSS and ATOM feeds
Answer, quoted:

Have you had a look into the following list? http://java-source.net/open-source/rss-rdf-tools
Even though it has been mentioned several times, I would suggest using Rome as well.

Update: Wordpress also has an XmlRpc API, so you can use that to query posts.  The closest to I can see to getting the number of posts/pages is to use wp.getPageList which returns an array of all posts with minimal data.
As part of the XmlRpc API support, Wordpress implements several standards including the Blogger API, for which there is a decent tutorial.  Again, no specific 'getPostCount()' function.
public static void printAllPosts(
    GoogleService myService, String blogId)
    throws ServiceException, IOException {
  // Request the feed
  URL feedUrl = new URL("http://www.blogger.com/feeds/" + blogID + "/posts/default");
  Feed resultFeed = myService.getFeed(feedUrl, Feed.class);

  // Print the results
  System.out.println(resultFeed.getTitle().getPlainText());
  for (int i = 0; i < resultFeed.getEntries().size(); i++) {
    Entry entry = resultFeed.getEntries().get(i);
    System.out.println("\t" + entry.getTitle().getPlainText());
  }
  System.out.println();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to order child records when referenced from a parent object in PeeWee ORM How do I specify an order for the records returned via a foreign key in Peewee?
I have the following (simplified) model;
class Order(peewee.Model):
    order_no = peewee.CharField()

class OrderLine(peewee.Model):
    order_item = peewee.CharField()
    quantity = peewee.IntegerField()
    price = peewee.DecimalField()

    order = peewee.ForeignKeyField(Order)

When I fetch an order using my_order = Order.get(1234) I would like to then iterate through the order lines in a specific order, sometimes in order_item order, sometimes in quantity order. Is there a way to do this? At the moment they seem to come back in order_item.id order from the database.

A: The back-ref of the foreign-key (Order.orderline_set) is just a wrapper around a select query, so you can order it how you wish:
for item in order.orderline_set.order_by(OrderLine.quantity):
    ...


text:
Q: Cannot import telethon Had telethon working with my code.
For some reason, my code did not work anymore after some time, so tried to upgrade telethon library. Now, even not able to import telethon.
Followed installation instructions here: https://telethon.readthedocs.io/en/latest/basic/installation.html
# pip3 show telethon

Name: Telethon
Version: 1.8.0
Summary: Full-featured Telegram client library for Python 3
Home-page: https://github.com/LonamiWebs/Telethon
Author: Lonami Exo
Author-email: totufals@hotmail.com
License: MIT
Location: /home/XXX/.local/lib/python3.5/site-packages
Requires: pyaes, rsa
Required-by:

After this, trying to do basic import of telethon library fails.
Running python 3.5.2
# python3 -c "import telethon;"

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/xxx/.local/lib/python3.5/site-packages/telethon/__init__.py", line 1, in <module>
    from .client.telegramclient import TelegramClient
  File "/home/xxx/.local/lib/python3.5/site-packages/telethon/client/__init__.py", line 13, in <module>
    from .users import UserMethods  # Required for everything
  File "/home/xxx/.local/lib/python3.5/site-packages/telethon/client/users.py", line 7, in <module>
    from .. import errors, utils, hints
  File "/home/xxx/.local/lib/python3.5/site-packages/telethon/hints.py", line 56, in <module>
    typing.BinaryIO
  File "/usr/lib/python3.5/typing.py", line 552, in __getitem__
    dict(self.__dict__), parameters, _root=True)
  File "/usr/lib/python3.5/typing.py", line 512, in __new__
    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
  File "/usr/lib/python3.5/typing.py", line 512, in <genexpr>
    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
  File "/usr/lib/python3.5/typing.py", line 1077, in __subclasscheck__
    if super().__subclasscheck__(cls):
  File "/usr/lib/python3.5/abc.py", line 225, in __subclasscheck__
    for scls in cls.__subclasses__():
TypeError: descriptor '__subclasses__' of 'type' object needs an argument

A: This is a bug in the python version you're using (see https://github.com/python/typing/issues/266); and it's also an open issue in Telethon repo (see https://github.com/LonamiWebs/Telethon/issues/1177).
Upgrade your python to the latest version and the problem will go away.


text:
Q: Probabilty problem related to two cabinets containing gold and silver coins. Each of the two cabinets has 3 drawers. Cabinet I contains a gold coin in each drawer and cabinet II contains a gold coin in one of its drawers and a silver coin in the other. A cabinet is randomly selected ,one of its drawers is opened and a gold coin is found. Find the probability that there is a gold coin in the other drawer.
The answer given in book is 3/4

A: I have no idea what $C$ is doing there. There is no need to specify the event that a cabinet is chosen, as that event is guaranteed to happen, and doesn't affect any probabilities.
Try using the events $L$ for picking the left cabinet and $G$ for picking a gold drawer. You want $$P(L\mid G)=\frac{P(L\cap G)}{P(G)}$$ $P(L\cap G)=P(L)$ is immediately seen to be $\frac12$, while $P(G)$ takes some calculation.
Alternately, as long as we are in land the land of assuming that $G$ occurs, there are $4$ equally likely possibilities. Three of them are in the all-gold cabinet and one isn't.

A: I assume the second cabinet also has an empty drawer to make three.  In that case, we are equally likely to select each drawer.  There are six possibilities, but we discard the two where we get the silver and nothing. leaving four.  Three of them have a gold coin in another drawer, so the chance is $\frac 34$.
A more careful approach is that there is $\frac 12$ chance we choose the first cabinet.  In that case we surely choose a gold coin and have another in another drawer.  There is $\frac 16$ chance we choose the second cabinet and then the gold drawer.  Here we do not have another gold coin, so the chance we have another gold coin given that we found one in the first drawer is $$\frac {\frac 12}{\frac 12+\frac 16}=\frac 34$$


text:
Q: R conditional variable for longitudinal data I have data for each month for a year on insured people. All variables are dummy variables and I need to create a new variable that shows when a person became uninsured. I am calling the variable duration. My dataset (df) looks something like this:

ID Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
101 1   1   1   1   0   0   1   1    1   1   1   1
102 1   1   1   1   0   0  0   0     0   0   0   0
103 1    1   1  1    1   1  1   1    1   1   1   1
104 1    1   1  1    0   1  1   0    1   1   1   1

In the dataset, 1 is insured and 0 is uninsured.My new variable would have the have the col position for when the person changed from 1 to 0. For instance in the first row, my variable duration would have the value 5 for may. I am only insterested in the first instance of 0. For  example, in row 4, i only need 5 for may and can ignore august. Also, if the person does not become uninsured like in the case of 103, the new variable would just have the value "0".
I began by using ifelse statement below but it would take me a lot of time to keep repeating it. if you have an easier solution for this, please share. Thanks!

df$duration=ifelse(df$feb==1,0,2)

A: Another idea that seems valid:
tmp = !DF[-1]
max.col(tmp, "first") * as.logical(rowSums(tmp))
#[1] 5 5 0 5

Where
DF = structure(list(ID = 101:104, Jan = c(1L, 1L, 1L, 1L), Feb = c(1L,
1L, 1L, 1L), Mar = c(1L, 1L, 1L, 1L), Apr = c(1L, 1L, 1L, 1L),
    May = c(0L, 0L, 1L, 0L), Jun = c(0L, 0L, 1L, 1L), Jul = c(1L,
    0L, 1L, 1L), Aug = c(1L, 0L, 1L, 0L), Sep = c(1L, 0L, 1L,
    1L), Oct = c(1L, 0L, 1L, 1L), Nov = c(1L, 0L, 1L, 1L), Dec = c(1L,
    0L, 1L, 1L)), .Names = c("ID", "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame", row.names = c(NA,
-4L))

A: There are more efficient alternatives, but maybe this is sufficient:
apply(DF[,-1], 1, function(x) which(x==0)[1])
#[1]  5  5 NA  5


text:
Q: SQLAlchemy alias a joined table in a many-to-many relation In a legacy database we have, there is a pretty special datastructure where we have two many-to-many relations joining the same two tables companies to paymentschedules.
There is a many-to-many relation using an association table called companies_paymentschedules, and a second many-to-many relation using an association table called companies_comp_paymentschedules.
Both relations serve different purposes.
companies_paymentschedules stores paymentschedules for which the company has a discount, companies_comp_paymentschedules stores paymentschedules that are linked to the company.
(I know that this could be simplified by replacing these tables with a single lookup table, but that is not an option in this legacy database.)
The problem is that I need to join both types of companies (discounted and linked) in the same query. SQLAlchemy joins both tables without problems, but it also joins the companies table, and calls them both "companies", which leads to a SQL syntax error (using MSSQL BTW).
This is the query:
q = Paymentschedules.query
# join companies if a company is specified
if company is not None:
    q = q.join(Paymentschedules.companies)
    q = q.join(Paymentschedules.companies_with_reduction)

The many-to-many relations are both defined in our companies model, and look like this:
paymentschedules_with_reduction = relationship("Paymentschedules", secondary=companies_paymentschedules, backref="companies_with_reduction")

paymentschedules = relationship("Paymentschedules", secondary=companies_comp_paymentschedules, backref="companies")

The problem is that the JOINS trigger SQLAlchemy to create a SQL statement that looks like this:
FROM paymentschedules
JOIN companies_comp_paymentschedules AS companies_comp_paymentschedules_1 ON paymentschedules.pmsd_id = companies_comp_paymentschedules_1.pmsd_id
JOIN companies ON companies.comp_id = companies_comp_paymentschedules_1.comp_id
JOIN companies_paymentschedules AS companies_paymentschedules_1 ON paymentschedules.pmsd_id = companies_paymentschedules_1.pmsd_id
JOIN companies ON companies.comp_id = companies_paymentschedules_1.comp_id

The two lookup tables have different names, but the related companies table is called "companies" in both cases, causing a SQL error:
[SQL Server Native Client 11.0][SQL Server]The objects "companies" and "companies" in the FROM clause have the same exposed names. Use correlation names to distinguish them. (1013) (SQLExecDirectW); ...]

I have been looking for a way to alias a join, or perhaps alias one of the relations from my lookup-tables to the companies table, but I was unable to do so.
Is there a way to alias a joined many-to-many table?
update:
Based on the suggestion by @IljaEverilä I found this: http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=onclause (see "Joins to a Target with an ON Clause") as a method to alias a joined table, but the example only shows how to alias a one-to-many type join. In my case I need to alias the other side of my lookup table, so I can't apply the example code to my situation.


text:
Q: Should I put a lot of initialization work in constructor or in a member method? Should I put a lot of initialization work in constructor or in a member method ?
 class A {
 public:
    A() {
        //a lot of initialization work...
    }
    ~A() = default;
    //or put those work in it
    void init() {
        /*
         After creating object of this class, I invoke
         init method to do some heavy initialization work...
        */
    }
 }

A: I really like the following way of looking at this, but, as mentioned at the bottom of this post, it has a single, massive, drawback:
The constructor's job is to establish the class invariant.
A class invariant is the description of the legal state a class can be in in between calls to public member functions, and each and every public member function should be well-behaved for any and all possible invariant state. So it's always a good idea to keep your class invariants as strict as possible.
In light of all this: the amount of work being done in a constructor should be whatever is needed to set up as strict an invariant as reasonably possible for the class.
For example:
If I have a class that holds a pointer to an OS window:
class Window {
  native_window* w_;
  ...
};

The class invariant could be "w_ is always either null, or points to an instance of a window.", but that's annoying, since it means that most member functions will have to perform a null check. If the invariant was "w_ points to a valid window handle", then you can rely on that assumption and greatly simplify the rest of the class.
However! This means that should the constructor fail to establish an invariant (the OS call to create the window failed because of reasons), then the only way you can handle the failure is to throw an exception. So if you are operating in a codebase where exceptions are not permitted, then this whole approach to class design is moot.


text:
Q: Why is 4 dimensional vector better performant than 4 dimensional std::array here #include <iostream>
#include <vector>
#include <array>
#include <chrono>

#define D1  8
#define D2 16
#define D3 12
#define D4 16

struct my_big_Struct {
    uint64_t data[16] = {0};
};

struct my_vector_class {
    std::vector<std::vector<std::vector<std::vector<struct my_big_Struct>>>> myobj;
    my_vector_class() {
        myobj.resize(D1);
        for (auto i = 0; i < D1; i++) {
            myobj[i].resize(D2);
            for (auto j = 0; j < D2; j++) {
                myobj[i][j].resize(D3);
                for (auto k = 0; k < D3; k++) {
                    myobj[i][j][k].resize(D4);
                }
            }
        }
        for (auto i = 0; i < D1; i++) {
            for (auto j = 0; j < D2; j++) {
                for (auto k = 0; k < D3; k++) {
                    for (auto l = 0; l < D4; l++) {
                        myobj[i][j][k][l].data[0] = rand();
                    }
                }
            }
        }
    }
};

struct my_array_class {
    std::array< std::array < std::array < std::array<struct my_big_Struct, D1>, D2>, D3>, D4> arr;
    my_array_class() {
        for (auto i = 0; i < D1; i++) {
            for (auto j = 0; j < D2; j++) {
                for (auto k = 0; k < D3; k++) {
                    for (auto l = 0; l < D4; l++) {
                        arr[i][j][k][l].data[0] = rand();
                    }
                }
            }
        }
    }
};

#define LOOP_COUNT 1

int main() {
    struct my_vector_class vec;
    struct my_array_class arr;
    uint64_t sum = 0;
    auto start = std::chrono::high_resolution_clock::now();

    for (auto lc = 0; lc < LOOP_COUNT; ++lc) {
        for (auto i = 0; i < D1; i++) {
            for (auto j = 0; j < D2; j++) {
                for (auto k = 0; k < D3; k++) {
                    for (auto l = 0; l < D4; l++) {
                        sum +=vec.myobj[i][j][k][l].data[0];
                    }
                }
            }
        }
    }
    auto stop  = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = stop-start;
    std::cout << "Elapsed vec " << diff.count() << "\n";
    auto start2 = std::chrono::high_resolution_clock::now();
    for (auto lc = 0; lc < LOOP_COUNT; ++lc) {
        for (auto i = 0; i < D1; i++) {
            for (auto j = 0; j < D2; j++) {
                for (auto k = 0; k < D3; k++) {
                    for (auto l = 0; l < D4; l++) {
                        sum +=arr.arr[i][j][k][l].data[0];
                    }
                }
            }
        }
    }
    auto stop2  = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff2 = stop2-start2;
    std::cout << "Elapsed arr " << diff2.count() << "\n";
    auto start3 = std::chrono::high_resolution_clock::now();
    for (auto lc = 0; lc < LOOP_COUNT; ++lc) {
        for (auto i = 0; i < D1; i++) {
                for (auto j = 0; j < D2; j++) {
                    for (auto k = 0; k < D3; k++) {
                        for (auto l = 0; l < D4; l++) {
                            sum +=vec.myobj[i][j][k][l].data[0];
                        }
                }
            }
        }
    }
    auto stop3  = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff3 = stop3-start3;
    std::cout << "Elapsed vec " << diff3.count() << "\n";
    auto start4 = std::chrono::high_resolution_clock::now();
    for (auto lc = 0; lc < LOOP_COUNT; ++lc) {
        for (auto i = 0; i < D1; i++) {
            for (auto j = 0; j < D2; j++) {
                for (auto k = 0; k < D3; k++) {
                    for (auto l = 0; l < D4; l++) {
                        sum +=arr.arr[i][j][k][l].data[0];
                    }
                }
            }
        }
    }
    auto stop4  = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff4 = stop4-start4;
    std::cout << "Elapsed arr " << diff4.count() << "\n";
};

So, I have created a 4D - vector and 4D array of a biggish object (128B) and tried to loop through them twice...To zero out cache warming effects... I consistently found array version to be 2x slower...
gcc-5.2.0/bin/g++
g++ -std=c++11  main.cpp -o vecvsarr
./vecvsarr
Elapsed vec 0.475446
Elapsed arr 0.846845
Elapsed vec 0.441586
Elapsed arr 0.829504

By adding the optimization -O3 I get some sppedups.. But I expected significant difference
With optimizations:
Elapsed vec 2.58e-07
Elapsed arr 1.52e-07
Elapsed vec 1.21e-07
Elapsed arr 1.15e-07

A: Used godbolt as suggested by Bob_ and found out there are loop optimizations with optimization enabled. With the print enabled and running for a considerable saw 2x speed up.
Elapsed vec 15.7311
Elapsed arr 7.78011
Elapsed vec 14.7511
Elapsed arr 7.24151
Sum 2486663010270848384


text:
Q: Can't import cv2 on Python 3.5 DLL load failed I've been struggling with this problem for a day and haven't been able to find a working solution. When I import cv2 with python-v, I get
>>> import cv2 Traceback (most recent call last):
File "<stdin>", line 1, in <module> File "<frozen importlib._bootstrap>",
line 969, in _find_and_load File "<frozen importlib._bootstrap>",
line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>",
line 666, in _load_unlocked File "<frozen importlib._bootstrap>",
line 577, in module_from_spec File "<frozen importlib._bootstrap_external>",
line 914, in create_module File "<frozen importlib._bootstrap>",
line 222, in _call_with_frames_removed
ImportError: DLL load failed: The specified module could not be found.

I am using Python 3.5 with Anaconda3 on windows 10 64 bit. I have gone through all the other posts on stackoverflow regarding this. Based on that here is some information of the things I have done:

*

*I installed Visual Studio 14.0 from the from the VC++ 2015 standalone tools here http://landinghub.visualstudio.com/visual-cpp-build-tools

*I deleted my old isual C++ redistributable packages and installed https://www.microsoft.com/en-gb/download/details.aspx?id=48145. My msvcp140.dll is present here: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\redist\x64\Microsoft.VC140.CRT

*I installed opencv python from this link https://pypi.python.org/pypi/opencv-python#downloads

*I copied the cv2.pyd package into my Lib/site-package directory
Any suggestions on what I'm missing?
Thanks in advance!!

A: Suggest to download OpenCV 3.2.0 for Python 3.5 either Windows 32-bit or 64-bit form this Unofficial Windows Binaries for Python Extension Packages website. Look for file with suffix as opencv_python‑3.2.0+contrib‑cp35‑cp35m for your case. The +contrib is the ones with opencv_contrib modules.
Then type below command to install the binary from your location drive:

*

*pip install opencv_python‑3.2.0+contrib‑cp35‑cp35m‑win32.whl (32-bit
version) or

*pip install opencv_python‑3.2.0+contrib‑cp35‑cp35m‑win_amd64.whl (64-bit version)

Before install this binary, make ensure the previous installation is completely removed or you may create a new conda env to install it. If it's successfully installed, it would be showed up in conda list.  Then you can check its version by import cv2, print cv2.__version__.


text:
Q: "Cannot format given Object as a Date" error when formatting google api client DateTime I need to convert the DateTime object, of google api client package, to a simple string. Should be easy, but i am new to android.
com.google.api.client.util.DateTime  date = new com.google.api.client.util.DateTime(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateAsISOString = df.format(date);

This gives the following exception:

java.lang.IllegalArgumentException: Cannot format given Object as a
  Date

I guess DateFormat should be from some google package too, but can't find where.

A: You are getting the error because you are trying to use SimpleDateFormat with wrong Date Object.
You should be using java.util.Date instead if you want to make use of SimpleDateFormat.
Here is the corrected code snippet:
java.util.Date date = new java.util.Date(System.currentTimeMillis());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateAsISOString = df.format(date);
System.out.println(dateAsISOString);


text:
Q: Solving a power series centered at 0 by integrating another power series Problem: Find the power series for g(x) centered at 0 by integrating the power series f(x). Give answer in sigma notation along with the first four nonzero terms.
$$g(x)=\ln{(1-3x)}\space \land \space f(x)=\frac{1}{1-3x}$$
I'm struggling to understand whether I've provided the appropriate answer. Any helpful hints would be much appreciated. Here's my work.
I begin with the fact that $\sum_{k=0}^\infty x^k = \frac{1}{1-x}$.
Then I integrate:
$\int \frac{1}{1-3x}dx \space=\space\int \sum_{k=0}^\infty (3x)^k dx \space=\space \int(1+3x+\frac{(3x)^2}{2}+\frac{(3x)^3}{3}+\cdots)dx$
Then multiply by -3:
$-\frac{\ln{(1-3x)}}{3}+C \space=\space \sum_{k=0}^\infty\frac{(3x)^{k+1}}{k+1}+C \space=\space x+\frac{(3x)^2}{2}+\frac{(3x)^3}{3}+\cdots+C$
$\ln{(1-3x)} \space=\space -3\sum_{k=0}^\infty \frac{(3x)^{k+1}}{k+1}+C \space=\space -3(x+\frac{(3x)^2}{2}+\frac{(3x)^3}{3}+\cdots) +C$
$\therefore \space \ln(1-3x) \space=\space -3\sum_{k=0}^\infty \frac{(3x)^{k+1}}{k+1} \space=\space -3x-\frac{3*(3x)^2}{2}-\frac{3*(3x)^3}{3}-\frac{3*(3x)^4}{4}-\cdots$
Is this correct, or am I missing something? I keep thinking I'm missing something with the constant $C$. Also, Should this be represented as a Maclaurin series?


text:
Q: Swift3: How to load data from external database using PHP and Swift 3 I am trying to load the table by fetching data from the external database using PHP. I have the script on the server, and able to fetch the data. I'm trying to get help and understand the logic, but still I cant get it.
At the moment, I have only set up my tableview but there is not data.
Please let me know how can I fetch the data.
Thanks
code:
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var group = [Group]()

    @IBOutlet weak var tableview: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableview.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return myarray.count
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
       // cell.textLabel?.text = myarray[indexPath.item]
        return cell
    }

}

Code:(how can I get the data displayed on the table view)?
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

//let myarray = ["item1", "item2", "item3"]

var group = [Group]()

@IBOutlet weak var tableview: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "http://www.myurl/myfile.php")

    let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in

        guard let data = data, error == nil else { return }

        print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
    }

    task.resume()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tableview.reloadData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //return myarray.count
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
   // cell.textLabel?.text = myarray[indexPath.item]
    return cell
}

}

A: Here is the tutorial for load data on iOS via Web Services from iOS side and create Web Services from Server side.
Create a simple PHP/MySQL web service for iOS app.

https://www.raywenderlich.com/2941/how-to-write-a-simple-phpmysql-web-service-for-an-ios-app

To call that Web Service from iOS app

http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service

A: You need to create a array or Dictionary based on your response using below code
You need to pass string to these func which you are using within print statement.
If response return as a dictionary
func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

Get array from dictionary to bind with tableview.
If response return as an Array
func convertToArray(text: String) -> [Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }

Then bind data from this array to tableView.


text:
Q: incorrect mapping of test case XRay with Jira @Xray(requirement = "QA", test = "TM-3553" ,ProjectName="QA")
@Test()
public void GETGradeForGuestStudent() {

}

why the execution is not getting mapped to TM-3553 Rather its getting mapped always to TM-3601
mapped to jira
my testng report.xml-pastebin.com/iHc4hJmD
In jenkins postbuild action i am calling this sh command
token=$(curl -H "Content-Type: application/json" -X POST --data @"./cloud_auth.json" https://xray.cloud.xpand-it.com/api/v2/authenticate| tr -d '"')
curl -H "Content-Type: application/xml" -X POST -H "Authorization: Bearer $token" --data @"./target/surefire-reports/testng-results.xml" https://xray.cloud.xpand-it.com/api/v2/import/execution/testng?projectKey=TM&testExecKey=TM-3563"

A: The TestNG XML report you shared seems to have the correct format, as detailed here. The Test issue key is being mapped to an attribute named "test" under the <attributes> element, which in turn is inside the <test-method> element.
I changed your XML report, so that the first reference to TM-3553 is one of my existent Tests ... and it worked fine in my scenario.
Therefore, I think your scenario needs to be analyzed by the Xray team in more depth to figure out exactly why this association is not being done in Xray side.
Let me just add that the annotation you shared is not correct, as "requirement" must be an issue key and "ProjectName" doesn't exist/is supported by Xray during the import process..
Therefore, this needs to be changed:
@Xray(requirement = "QA", test = "TM-3553" ,ProjectName="QA")
to something like:
@Xray(requirement = "TM-1243", test = "TM-3553")
Another note about the TestNG XML report, is that it contains several references to the same test method GETGradeForGuestStudent.. which I find weird at first sight but it depends on how you're running the tests.


text:
Q: Nested yield returns collection instead of string I'm trying to use yield to return string on each iteration, but instead of a string, my res has type {Namespace.Class.<getMutations>d__10}. I get all the results I want, but they are returned all at once and not one by one. What am I doing wrong?
public static IEnumerable<string> generate(string mask)
{
     foreach (List<string> pattern in list)
     {
         var res = getMutations(pattern);
         yield return "result:  " + res;
     }
}

private static IEnumerable<string> getMutations(List<string> pattern)
{
    IEnumerable<string> mutations = null;
    switch (pattern.Count)
    {
        case 4:
            mutations =
            from m0 in pattern[0]
            from m1 in pattern[1]
            from m2 in pattern[2]
            from m3 in pattern[3]
            select "" + m0 + m1 + m2 + m3;
            break;
        case 5:
            mutations =
            from m0 in pattern[0]
            from m1 in pattern[1]
            from m2 in pattern[2]
            from m3 in pattern[3]
            from m4 in pattern[4]
            select "" + m0 + m1 + m2 + m3 + m4;
            break;
    }

    foreach (var mutation in mutations)
        yield return mutation;
}

A: I would have liked to answer you this question, but I found a better and complete answer to your question that you can find in the link below.
What is the yield keyword used for in C#?
For this you need to understand the Deferred Execution :
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/deferred-execution-example

A: In each iteration you are returning the result of getMutations and that is an enumerable.
If you want to return strings you have to iterate over the result of getMutations and yield those strings.


text:
Q: Django model is truncating a decimal place when passed to the view when DecimalField is set Django Model:
class TwoDecimal(models.Model):
   two_decimal = models.DecimalField(decimal_places=2, max_digits=10)

View:
def two_decimal(request):
    test = TwoDecimal(
        two_decimal = 30.00
    )
    test.save()
    return render(
        request,
        "test-template.html",
        {"test": test}
    )

Template:
{{ test.two_decimal }}  #==> Displays as 30.0 instead of 30.00 (Despite it being a two decimal field.)

This displays properly if it is a query from already saved data.
Why is django truncating this decimal place?

A: You should pass it a decimal, right now you pass it a float. The fact that it is then saved in a DecimalField does not make the attribute a Decimal. If you would later retrieve it, then it indeed will be retrieved as a decimal.
from decimal import Decimal

def two_decimal(request):
    test = TwoDecimal(
        two_decimal = Decimal('30.00')
    )
    test.save()
    return render(
        request,
        'test-template.html',
        {'test': test}
    )
Note that it is important to pass the value as a string to the Decimal constructor. Otherwise it might introduce small rounding errors, and furthermore it does no longer contain information about the number of digits.


text:
Q: How to include ui-grid font files into the project I have been stuck with anjularjs ui-grid, it's showing some Chinese symbols in place of icons. After digging about it I get to know I have to use some font-files provided by ui-grid team, I downloaded the files and included them into my project but still m not getting the correct icon images and fonts, how to include these files into the project?
These are the file names which I downloaded and included in my project:
1 ui-grid.eot
2 ui-grid.svg
3 ui-grid.ttf
4 ui-grid.woff

A: I'm using Grunt I had to add
copy: {
      dist: {
        files: [
           ...
        //font di ui grid
         {
              expand: true,
              flatten: true,
              dest: 'dist/styles/',
              src: ['bower_components/angular-ui-grid/ui-grid.ttf',
                    'bower_components/angular-ui-grid/ui-grid.woff',
                    'bower_components/angular-ui-grid/ui-grid.eot',
                    'bower_components/angular-ui-grid/ui-grid.svg'
                    ]
            }
    ]},

to the Gruntfile.js In order to copy the ui-grid fonts in the style  directory.

A: With Gulp you can add this task into build.js file
gulp.task('copyfonts', function() {
   gulp.src('./bower_components/angular-ui-grid/**/*.{ttf,woff}')
   .pipe(gulp.dest(path.join(conf.paths.dist, '/styles/')));

});

A: I had the same issue, now it is rectified as follows
I updated the Ui-grid with either latest stable version(v3.0.0-rc.3) or the unstable version(v3.0.0-rc.16).
then
place the font files all in the same directory as your ui-grid.css lives, like this
app
- lib
  - ui-grid.js
  - ui-grid.css
  - ui-grid.eot
  - ui-grid.svg
  - ui-grid.ttf
  - ui-grid.woff

or
you can open the CSS and change the file path to the relative location in @font-face url's
check here
http://ui-grid.info/docs/#/tutorial/116_fonts_and_installation

A: I'm using Gulp and I added a fonts:dev task to be added as a dep to my serve task:
 gulp.task('fonts:dev', function () {
    return gulp.src($.mainBowerFiles())
      .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.tmp + '/serve/fonts/'));
  });

This solved it for me. More context here.

A: I know it's a little bit late but I just want to share my answer. I use bower to install ui-grid and gruntjs to load files. Its almost the same with Panciz answer but change it to *.{ttf,woff,eot,svg} for getting all font files needed without specifying them.
add this in copy:
copy: {
  dist: {
    files: [
      //other files here
      , {
          expand: true,
          flatten: true,
          cwd: '<%= yeoman.client %>',
          dest: '<%= yeoman.dist %>/public/app', //change destination base to your file structure
          src: [
            '*.{ttf,woff,eot,svg}',
            'bower_components/angular-ui-grid/*',
          ]
        }
    ]
  }
}

A: If you install ui grid using 'bower install' than the files should be installed in their proper location. The problem we had is that we're using ui-router, which requires all requests to be rewritten to index.html.  We had to add the font extensions to our rewrite rules so that Angular could load them. We're using a middleware plugin for running locally. On Apache/Nginx server the concept is the same.
middleware: function (connect) {
        return [
          modRewrite(['!\\.html|\\.js|\\.svg|\\.woff|\\.ttf|\\.eot|\\.css|\\.png$ /index.html [L]']),
          connect.static('.tmp'),
          connect().use(
            '/bower_components',
            connect.static('./bower_components')
          ),
          connect().use(
            '/app/styles',
            connect.static('./app/styles')
          ),
          connect.static(appConfig.app)
        ];
      }

A: In my project i usually use grunt to put fonts files in build/assets directory and vendors files in build/vendor/lib-name directory.
But ui-grid.css have relative path to get font file and doesn't have any mode to configure a different location without modify your css file. But i think that it's not a good idea because then you need to change this file for each vendor update.
So you can setup your grunt to put this particular font with your vendor files too.
This is your build.config.js:
module.exports = {
    ...
    vendor_files: {
        ...
        js: [
            'vendor/angular/bundle.min.js',
            'vendor/angular-ui-grid/ui-grid.min.js',
        ],
        css: [
            'vendor/angular-ui-grid/ui-grid.min.css',
        ],
        uigrid_fonts: [
            'vendor/angular-ui-grid/ui-grid.woff',
            'vendor/angular-ui-grid/ui-grid.ttf',
            'vendor/angular-ui-grid/ui-grid.eot',
            'vendor/angular-ui-grid/ui-grid.svg',
        ],
        ...
    }
    ...
}

Then on your Gruntfile.js you can manage this file:
module.exports = function (grunt) {

    grunt.loadNpmTasks('grunt-contrib-copy');
    //.. other require

    var userConfig = require('./build.config.js');
    var taskConfig = {
        copy: {
            //.. other copy task
            build_vendor_fonts: {
                files: [
                    {
                        src: [ '<%= vendor_files.fonts %>' ],
                        dest: '<%= build_dir %>/assets/fonts/',
                        cwd: '.',
                        expand: true,
                        flatten: true
                    }
                ]
            },
            build_uigrid_font: {
                files: [
                    {
                        src: [ '<%= vendor_files.uigrid_fonts %>' ],
                        dest: '<%= build_dir %>/',
                        cwd: '.',
                        expand: true,
                    }
                ]
            },
            build_vendor_css: {
                files: [
                    {
                        src: [ '<%= vendor_files.css %>' ],
                        dest: '<%= build_dir %>/',
                        cwd: '.',
                        expand: true
                    }
                ]
            },
            build_appjs: {
                files: [
                    {
                        src: [ '<%= app_files.js %>' ],
                        dest: '<%= build_dir %>/',
                        cwd: '.',
                        expand: true
                    }
                ]
            },
            build_vendorjs: {
                files: [
                    {
                        src: [ '<%= vendor_files.js %>' ],
                        dest: '<%= build_dir %>/',
                        cwd: '.',
                        expand: true
                    }
                ]
            }
        },
    };

    grunt.registerTask('build', [
        'clean',
        'concat:build_css',
        'copy:build_vendor_fonts',
        'copy:build_uigrid_font',
        'copy:build_vendor_css',
        'copy:build_appjs',
        'copy:build_vendorjs',
        'index:build'
    ]);

    //..
}

A: Pretty much the same answer as Panciz and Vicruz, but I specified the relevant directories slightly differently:
copy: {
     dist: {
        files: [{
           // other files here...
        }, {
           expand : true,
           cwd : 'bower_components/angular-ui-grid',
           dest : '<%= yeoman.dist %>/styles',
           src : ['*.eot','*.svg','*.ttf','*.woff']
        }]
     },


text:
Q: abcdefg.com resolves to 127.0.0.1. Why? This domain abcdefg.com doesn't use to resolve to anything. Suddenly it started to resolve to 127.0.0.1. I can see this happen in my corporate network, my home network and even on my mobile network.
Does anyone knows why?

A: Because whoever owns the domain changed DNS. It's their domain, they can do that.
MXToolbox query confirms it resolves to 127.0.0.1 with a TTL of 24 hours.


text:
Q: Documentclass IEEEtran is not working with glossaries style long At the moment I try to add an acronym list into my document with the IEEEtran documentclass.
Which is working but the spacing between the short and long acronym form is off:

So i tried to change the printglossary style to style=long, which gives me an error:
Package longtable Error: longtable not in 1-column mode.

Why do I get this error with IEEEtran, but not with other documentclasses like scrartcl? How can I change the spacing between the short and long acronym form inside the IEEEtran documentclass?
\documentclass[
    conference,
    ]{IEEEtran}

\usepackage[
    backend = biber,
    ]{biblatex}
\usepackage[
    acronym,
    automake,
    nopostdot,
    toc,
    nomain,
    ]{glossaries}

\makeglossaries

\newacronym[
    ]{GASNEV}{GasNEV}{Gasnetzentgeltverordnung}
\newacronym[
    ]{KWK}{KWK}{Kraft-Wärme-Kopplung}

\begin{document}

\printglossary[
    type=\acronymtype,
    nonumberlist,
%   style=long,
    ]

My Acronyms:

\gls{KWK}

\gls{GASNEV}

\end{document}

Thank you in advance :)


text:
Q: jquery not working in css I'm having trouble getting my code to work and I'm not sure why.
Here is the link to the jsfiddle.
Js fiddle

$(document).ready(funciton() {
  $("button").click(function() {
    $("h1").css("color", "red");
  });
});
<h1>
Testing123
</h1>
<button>
  Make the h1 red
</button>

A: you have to include the jquery library link in order to use the jquery nomenclature.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Also you have a typo in the first line
$(document).ready(funciton() {...

should be
$(document).ready(function() {...


text:
Q: Is there a way for me to programmatically get if the side menu is floating or fixed? I am developing a plugin on Buildfire platform. I see that an app can have either floating or fixed side menu. I would like to change the position of my plugin content depending on the side menu style.
I already checked appearance and there is nothing that can help me. Am I missing something?
Any help is appreciated.

A: I dont believe this is provided currently (as of Feb 2020). The closet method would be buildfire.appearance.getAppTheme which only returns fonts and colors
{
  "appName": "AlicanDemo2019",
  "colors": {
    "backgroundColor": "#18191a",
    "titleBar": "#09a3ee",
    "titleBarTextAndIcons": "#ffffff",
    "headerText": "#09a3ee",
    "bodyText": "#ffffff",
    "icons": "#09a3ee",
    "primaryTheme": "#09a3ee",
    "successTheme": "#14cb5d",
    "infoTheme": "#69d5ff",
    "warningTheme": "#faba41",
    "dangerTheme": "#ed4b4b",
    "defaultTheme": "#0677ae",
    "footerMenuBackgroundColor": "#18191a",
    "footerMenuIconColor": "#09a3ee"
  },
  "fontId": "Architects+Daughter",
  "fontName": "Architects Daughter"
}


text:
Q: Reading QWidgets values from qtDesigner .ui file to python I have UI file prepared using qtcreator.
I like to read values from QWidgets to python script.
This link shows how to link ui file to python script.
But I can't find the information for reading values from QWidgets to python script.
Say I like to read user's selected value in QSpinBox.
I used PyQT5 for Ui design.


text:
Q: Android studio 0.5.3 is not generating AAR file for a library project since the update to 5.3 android studio is not generating the ".aar" file nor the "build/libs" folder,
i have tried to create a new library project , same issue
anyway to fix this issue? maybe try to force the output file name?

A: Right click the task you want and click "Run".


text:
Q: Differential equations on manifolds I am currently trying to understand a paper on wave maps on Lorentzian manifolds. The setup is the following:
Let $u: V \rightarrow M$, where $(V,g)$ is a Lorentzian manifold and $(M,h)$ is a Riemannian manifold. Also $V=S \times R$, where $S$ is an $n$-dimensional orientable smooth manifold, $R$ is 1-dimensional. $M$ is $d$-dimensional. $g$ is a Robertson-Walker metric $g=-dt^2+R^2(t)\sigma$.
Now i $\partial_i u^A$ and $\partial_t u^A$ are mappings from $S \times R$ into $T^∗ V\otimes TM$.
$u$ is supposed to be a wave map, so $g.\nabla^2 u=0$.
Also, $D_i$, respectively $ D_t$ are defined as covariant derivative in the metrics $\sigma$ and pull back of $h$ of a mapping from $S$ into $T^∗ S\otimes TM$
Well now define
$y(t):= R^2(t)\int\limits_{S_t}( \vert D D_t u \vert +R^{-2} \vert D^2u \vert ^2) \mu_{\sigma}$
where $\mu_{\sigma}$ is some measure in the metric $\sigma$ and $S_t =S \times \{t\} \subset V$ submanifold.
Through computations one gets the inequality:
$y^{'} \leq CR^{-1} (C_{\sigma} e_0^{1/2} R_0 y^{1/2} + C_h C(\sigma)(e_0^{3/2} R_0^3+y^{3/2})y^{1/2})$
where $C, C_{\sigma}, C_h, C(\sigma)$ are some depending constants and $e_0$ comes from the definition
$e_t= \int\limits_{S_t} (\vert \partial_t u \vert^2 +R^{-2} \vert Du \vert^2) \mu_{\sigma}$
Now, the paper deals with solving this differential inequality. My problem is: as far as I see, $y$ is a function from $R$ into functions from $S$ to $\mathbb{R}$, correct? How do you solve such differential equalities/inequalities?
The paper says:
If you define $z=y^{1/2}$, then one can formulate the inequality as
$z^{'} \leq (a+K_hz^3)R^{-1}$ where $a= C(C_{\sigma}R_0e_0^{1/2}+C_hC(\sigma)R_0^3e_0^{3/2}$ and $K_h=C C_h^C(\sigma)$.
A solution for the initial value for $t=t_0$ , $b=z_0$ is such that
$F(z)\equiv  \int\limits_b^z \dfrac{d \xi}{a+ K_h \xi^3} = \int\limits_{t_0}^t R^{-1}( \tau) d \tau \equiv X(t)$, $z$ is given by the inverse function $F^{-1}(X)$.
I really can't see where this comes from. Is is a strategy of solving diff. equations on manifolds?
Thanks in advance for any help!


text:
Q: efficient way to remember array index of two large arrays I have two Fortran arrays in 2 and 3 dimensions, say a(nx,ny) and b(nx,ny,nz). In array a, I need to find out the satisfied points, say values > 0. Then I need to locate the vectors in array b having the same indexes of x and y of those satisfied points in a. What is the easiest and fast way to do it? The two arrays are big, and I don't want to search one element by one element. Hope I explain my problem clearly! thanks!

A: I'm not sure that this is the best method, but here's what I would do:
Put a where clause inside a do loop over the z-values. You can first get a 2D map of valid indices into a logical array if you don't want to recalculate the points every time:
program indices
    implicit none
    integer, parameter :: nx = 3000, ny = 400, nz = 500
    integer, dimension(nx, ny) :: a
    integer, dimension(nx, ny, nz) :: b
    logical, dimension(nx, ny) :: valid_points

    integer :: x, y, z

    do y = 1, ny
        do x = 1, nx
            a(x, y) = x - y
        end do
    end do

    valid_points = (a > 0)

    do z = 1, nz
        where(valid_points)
            b(:, :, z) = z
        else where
            b(:, :, z) = 0
        end where
    end do

end program indices


text:
Q: I want to take input from multiple text inputs and send them to my database, but only the last input sends I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.
I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.
Here is my html file and the script

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
 return {
  'getSuggestion' : function(suggestion,callback){
   $http.post('/getSuggestion', {
    'suggestion': suggestion
   }).success(function (response) {
    callback(response);
   })
   .error(function (data, status, header, config) {
    callback({
     'error': true,
     'message': "Something went wrong."
    });
   });
  }
 }
}]);

app.controller('app', function($scope,appService) {
 //message send Function
 $scope.$watch('messageInput', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("USERNAME");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput2', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput3', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });
});

<!DOCTYPE html>

    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username">

        <input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password">

        <input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf">

        <button id="clickButton" class="submitButton">submit</button>

      </form>

A: You have a $watch for each input, and you have a submit() for each input. This is why you send only the input that changed. If you want to send them all together you should hold one submit(), means one onClick() that will check all new values are not null and send them to the server, something like this:
$scope.$watch('allInput', function (newValues, oldValues) {
    //null check
    if (newValues.user !== null && newValues.pass !== null && newValues.pass2 !== null) {
        //wait for the button to be pressed
        button.onclick = function() {
            alert("USERNAME");
            alert("PASSWORD");
            alert("PASSWORD CONF");
            //call server query function
            appService.getSuggestion(newValues, function (response) {
                $scope.suggestionCollection = response.rows;
            });
        };
    }
});

and the html:
      <form class="defaultForm" id="loginForm">

    <input class="loginField" type="text" name="username" ng-model="allInput.name" placeholder="username">

    <input class="loginField" type="text" name="password" ng-model="allInput.pass" placeholder="password">

    <input class="loginField" type="text" name="username" ng-model="allInput.pass2" placeholder="pass conf">

    <button id="clickButton" class="submitButton">submit</button>

  </form>

Of course getSuggestion() will change as well:
app.service('appService', ['$http', function($http){
return {
    'getSuggestion' : function(data,callback){
        $http.post('/getSuggestion', {
            'name': data.name,
            'pass': data.pass,
            'pass2': data.pass2
        }).success(function (response) {
            callback(response);
        })
        .error(function (data, status, header, config) {
            callback({
                'error': true,
                'message': "Something went wrong."
            });
        });
    }
}

A: If I understand your question correctly, you want to watch for changes of values in all three input fields. If user types anything in any one of the three input fields, you want to send the values from all three input fields to your backend. And when user hits "Submit", you want to get values from all three input fields as well.
To solve this problem, you need two pieces:

*

*set up a persistent click event handler on the button, as opposed to adding one only when some change happens. Note that in your code, you are updating this click handler each time one of the three input fields changes. This would cause the new input handler to overwrite the old one. That's why you only get the last touched value. I would recommend looking into the ng-click directive.

*get inputs from all three form fields when any one of them is changed. This can be achieved through the ng-change directive. Or alternatively, you can put all three ngModels under one parent object and just $watch() that one parent object, as Hatzav Wolff suggests in his answer.
Here is how I would approach it:

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
return {
 'getSuggestion' : function(suggestion,callback){
  $http.post('/getSuggestion', {
   'suggestion': suggestion
  }).success(function (response) {
   callback(response);
  })
  .error(function (data, status, header, config) {
   callback({
    'error': true,
    'message': "Something went wrong."
   });
  });
 }
}
}]);

app.controller('app', function($scope,appService) {
  $scope.handleChange= function() {
    /* Do whatever you want with the input. They are all here */
    console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
  }

  $scope.handleSubmit= function() {
    /* Do whatever you want with the input. They are all here */
    console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
  }
});

<!DOCTYPE html>

    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" ng-change="handleChange()" placeholder="username">

        <input class="loginField" type="text" name="password" ng-model="messageInput2"ng-change="handleChange()" placeholder="password">

        <input class="loginField" type="text" name="username" ng-model="messageInput3" ng-change="handleChange()" placeholder="pass conf">

        <button id="clickButton" ng-click="handleSubmit()" class="submitButton">submit</button>

      </form>


text:
Q: Retrieve database messages (e.g., "Print" statement outputs but not error messages) in ADO I use ASP 3.0 on IIS 7 and SQL Server 2008 as my dbms.
I have a stored procedure coded in SQL Server. I have some "Print" statements in it and also a select statement that throws out a recordset after the procedure is executed.
I can retrieve the recordset by using

Set recordSet = Server.CreateObject("ADODB.RecordSet")
recordSet.Open "Execute my_procedure", dbConn

What I wish to do here is to retrieve the outputs of the "Print" statements that I am executing in the stored procedure.
Please help. Thanks in advance!

A: In ADO, the output from PRINT statements is populated in the Errors collection, so you simply have to loop through that collection:
Dim e
For Each e In dbConn.Errors
    Response.Write e.Description
Next

A: You can try to use the SqlInfoMessage event to trap the print statement from the connection object.
SQLConnection.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
{
   string printresponse = e.Message;
};

You can get much more details from this link,
http://www.dotnetcurry.com/ShowArticle.aspx?ID=344
Hope this helps.


text:
Q: Preserving SQLServer permissions How can I stop a particular user from accessing the database for a period of time but at the same time not lose the permissions the user has on db objects.
Basically when he comes back (ie when access is given back) he should have all the permissions he had before his access was cut off. If I use sp_revokedbaccess 'myuser' the user myuser loses all permissions he had on db objects.
Is there a way to preserve myuser's permissions without resorting to cumbersome backup permissions and restore permissions kind of workarounds?

A: Thoughts:

*

*DENY CONNECT user or DENY CONNECT SQL TO login (sp_revokedbaccess is deprecated)

*You cannot use ALTER_LOGIN with the DISABLE argument to deny access to a Windows group (quoted from link)

*Assign all rights to a database role, then revoke rights from user. Add user to role when needed. It's a bad idea to assign object rights to users directly anyway.

*If user has sysadmin rights, you can't deny them anything at all (perhaps CONNECT SQL?)

*If user has db_owner rights (assumes set up in DB), you can't deny them anything in the database except CONNECT

A: The simplest way i see it is to disable the login.  You can do this on the login properties in SSMS under the status page.
You can achieve the same thing with the following T-SQL:
Assuming your login is bob a sql login, but can also be a windows login
ALTER LOGIN bob DISABLE

Then, to enable the login
ALTER LOGIN bob enable

A: You should be able to explicitly DENY him a permission, then revoke the deny.
You can also disable the login with ALTER LOGIN ... DISABLE, but will block at server level, not database level.
A hack solution is to map the user to a different login, then map him back (ALTER USER .. LOGIN = ...), but is a hack and I'm not sure even works correctly.

A: How is the user accessing the database?  If via an application, then just log the user out and require the user to re-authenticate.

A:
we want to remove access during maintenance but bring him back after it is done.

Have the maintenance process acquire exclusive locks on whatever tables it is processing. This locks everyone out until the processing is complete.

A: Can you switch the database to single user mode? http://msdn.microsoft.com/en-us/library/ms345598.aspx
Or script up the permissions before you remove them: http://www.sql-server-performance.com/articles/dba/object_permission_scripts_p1.aspx.  I know this is "backup permissions and restore permissions" - but this script makes the process a lot less cumbersome.

A: If the current password is known, change the password to a temporary value during the maintenance window.  Re-setting the password to its initial value serves this purpose without making any material changes to the account.

A: If you are using Windows authentication and you can lock out this user from everything on the domain, you can set the times the user is allowed to log on in Active Directory.  I can't provide detailed instructions but there should be something on ServerFault by now.


text:
Q: Upgrade Application Authentication to Core 2.0+ We are switching form .NET 4x to .NET Core and now I have problem with the authentication.
The main problem is, that the authentication is in an assembly and I am pretty new to Core, but read into it. There are some problems occuring, for example IPrincipal.
So I created my middleware and registered it in the StartUp.cs. After that I am Invoking it to start the authentication process.
In .NET i used this:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            NameValueCollection header = new NameValueCollection();
            header.Add(Request.Headers);
            IPrincipal princ = new CompanyPortalPrincipal(header);

            Context.User = princ;
            CompanyPortalPrincipal pp = Context.User as CompanyPortalPrincipal;
...

In Core I cannot use this.
First of all my MW:
private void BeginInvoke(HttpContext context)
        {
            NameValueCollection header = new NameValueCollection();
            header.Add(context.Request.Headers);

            IPrincipal principal = new CompanyPortalPrincipal(header);
            context.User = principal;
...

The first problem is in header.Add(context.Request.Headers); because it says that it cannot convert from Microsoft.AspNetCore.Http.IHeaderDictionary to Collection.Specialized.NameValueCollection.
The second problem is that in Core you use something like ClaimsPrincipal? Which I cannot use, because I am not allowed to touch the CompanyPortalPrincipal and this is using IPrincipal. Thus I cannot do context.User because in short it cannot convert from IPrincipal to ClaimsPrincipal

A:
The first problem is in header.Add(context.Request.Headers); because it says that it cannot convert from Microsoft.AspNetCore.Http.IHeaderDictionary to Collection.Specialized.NameValueCollection.

ASP.NET Core now uses the IHeaderDictionary to store headers. You could convert IHeaderDictionary to a NameValueCollection in following way:
NameValueCollection header = ctx.Request.Headers
    .SelectMany( kvp => kvp.Value, (kvp, value) => (kvp.Key,value))
    .Aggregate( new NameValueCollection(), (seed, current) =>{
        seed.Add(current.Key,current.value);
        return seed;
    });

// now you get the header
IPrincipal principal = new CompanyPortalPrincipal(header);

The second problem is that in Core you use something like ClaimsPrincipal? Which I cannot use, because I am not allowed to touch the CompanyPortalPrincipal and this is using IPrincipal. Thus I cannot do context.User because in short it cannot convert from IPrincipal to ClaimsPrincipal

Not sure how your CompanyPortalPrincipal is defined. But the ClaimsPrincipal constructor accepts a parameter of IIdentity, so you could create a new ClaimsPrincipal as below:
var userPrincipal =  new ClaimsPrincipal(principal.Identity);
// if you have multiple identity, invoke :
// ... userPrincipal.AddIdentity(...)
context.User = principal;

There's no magic in the ClaimsPrincipal( source) or ClaimsIdentity(source) . You could modify the principal as you like,for example, add claim add identities.


text:
Q: How to set cursor position with Jquery using focus? I'm having trouble with my function. I made a text editor with BBcode.
Its working very well but the cursor always get back to the end of the textarea.
Here is how it works;
var element = document.getElementById('textEdit');
var lastFocus;
$(document.body).on('click','.editBout', function(e) {
    e.preventDefault();
    e.stopPropagation();
var style = ($(this).attr("data-style"));
// Depending on the button I set the BBcode
    switch (style) {
        case 'bold':
            avS = "[b]";
            apS = "[/b]";
            break;
    }
    if (lastFocus) {
        setTimeout(function () { lastFocus.focus() }, 10);
        var textEdit = document.getElementById('textEdit');
        var befSel = textEdit.value.substr(0, textEdit.selectionStart);
        var aftSel = textEdit.value.substr(textEdit.selectionEnd, textEdit.length);
        var select = textEdit.value.substring(textEdit.selectionStart, textEdit.selectionEnd);
        textEdit.value = befSel + avS + select + apS + aftSel;
        textEdit = textEdit.value
        textEdit = BBcoder(textEdit);
        document.getElementById('editorPreview').innerHTML = textEdit;
    }
    return (false);
});

This last part here triggers the preview event
$(document.body).on('blur', '#textEdit', function() {
   lastFocus = this;
});

So i want it to come back to last focus but at a given position computed out of my selection + added bbcode length.


text:
Q: Selected ListView item doesn't change text color even with ColorStateList resource assigned I want the text color of an item in a ListView to change when selected. I read the following post (How to set ListView selected item alternet text color in android) and made the following changes:
Created a ColorStateList resource @drawable/list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ffffff00" /> <!-- default -->
<item
    android:state_pressed="true"
    android:color="#ff000000" />
<item
    android:state_selected="true"
    android:color="#ffff0000" />
<item
    android:state_focused="true"
    android:color="#ff0000ff" />

Assigned the resource to textColor attribute in the target TextView
<TextView
    android:id="@+id/person_active_list_name"
    android:paddingLeft="@dimen/person_list_name_left_padding"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/person_list_image_size"
    android:layout_toEndOf="@id/person_active_thumbnail"
    android:layout_toLeftOf="@id/person_active_list_arrow"
    android:layout_toRightOf="@id/person_active_thumbnail"
    android:layout_toStartOf="@id/person_active_list_arrow"
    android:gravity="center|start"
    android:textColor="@drawable/list_item" />

For some reason, only the default color in @drawable/list_item.xml is applied (so the ColorStateList resource is indeed being consumed by the TextView). There is no change, however, in text color when a list item is pressed, selected, etc. Any help is appreciated!

A: From the documentation:

Note: Remember that the first item in the state list that matches the current state of the object will be applied. So if the first item in the list contains none of the state attributes above, then it will be applied every time, which is why your default value should always be last

So, change your definition to this instead:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_pressed="true"
        android:color="#ff000000" />

    <item
        android:state_selected="true"
        android:color="#ffff0000" />

    <item
        android:state_focused="true"
        android:color="#ff0000ff" />

    <item android:color="#ffffff00" /> <!-- default -->

</selector>


text:
Q: Removing duplicates from query i have the query below that is getting the percentage time that a device is on throughout the day, however as there are duplicates in the data that i cant easily get rid off, what would be the best way to do this?
I have tried using distinct and Max(dtReading)
    SELECT DISTINCT
  workStationNo,
  controllerID,

  CAST(DATEPART(DAY, DATEADD(DAY, DATEDIFF(DAY, 0, MAX(dtReading)), 0)) AS varchar) AS date,
  (CAST(COUNT(*) AS float(1)) / CAST((DATEPART(HOUR, GETDATE()) * 30) AS float(1)) * CAST(100 AS float(1))) AS dayPercentage

FROM Controller
INNER JOIN ManufacturingLayout
  ON Controller.machID = ManufacturingLayout.workStationID
INNER JOIN ReaderData
  ON Controller.ctrlID = ReaderData.controllerID

WHERE dtReading >= CONVERT(datetime, '09/05/2018', 103)
AND dtReading <= DATEADD(HOUR, 24, CONVERT(datetime, '16/05/2018 23:59:59', 103))
AND (EventType = '(0x05)Open switch')
GROUP BY controllerID,
         DATEADD(DAY, DATEDIFF(DAY, 0, dtReading), 0),
         workStationNo
ORDER BY 1, 2

Query output
Workstation no controllerID  date dayPercentage
ZW01006            38         15    80.20833
ZW01006            38         16    142.0833
ZW01007            30         15    62.5
ZW01007            30         16    120.2083
ZW01008            31         15    92.70833
ZW01008            31         16    141.0417
ZW01010            40         15    0.625

source data
workStationNo   controllerID    dtReading
ZW01007            30           2018-05-16 15:42:39.000
ZW01007            30           2018-05-16 15:42:38.000
ZW01007            30           2018-05-16 15:40:38.000    <- duplicate
ZW01007            30           2018-05-16 15:40:38.000    <- duplicate
ZW01007            30           2018-05-16 15:38:37.000
ZW01007            30           2018-05-16 15:38:37.000
ZW01007            30           2018-05-16 15:36:37.000
ZW01007            30           2018-05-16 15:36:37.000
ZW01007            30           2018-05-16 15:34:36.000

A: You could use a derived table for your JOIN to ReaderData, in order to remove duplicates before the JOIN:
...
INNER JOIN (SELECT DISTINCT controllerID, dtReading
            FROM ReaderData) ReaderData
...


text:
Q: How to figure out design pattern for this particular solution? While working on a project I've come up with some design solution. I am having a hard time relating it to any general design pattern or analyzing this situation in details. This is also prohibiting me to find any better design for this.
This is a simple analogy of my solution -
Both Kangaroo and Tiger can walk but only Kangaroo can jump and only Tiger can run.
Animal<TLeg> where TLegs: ILegs
{
    TLegs Legs;
    void Walk(){ Legs.Walk(); }
}

Kangaroo: Animal<IJumpingLegs>
{
    void Jump() { Legs.Jump(); }
}

Tiger: Animal<IRunningLegs>
{
    void Run() { Legs.Run(); }
}

ILegs
{
   void Walk();
}

IRunningLegs : ILegs
{
   void Run();
}

IJumpingLegs : Ilegs
{
   void Jump();
}

[Edit]
Problem Description:
Here, Kangaroo and Tiger share common functions and a property Legs. Therefore, I have a base class for common functions. Base class needs to have access to this property Legs.
Functions in subclasses too rely on Legs and based on type of Legs, subclass will need to call different functions of this property.
Basically, two concrete animals need some common methods and their uncommon methods(Jump and Run) require different TYPE of a common property.
For this problem, I have come up with the solution described above. Hoping that I am able to describe my problem, I would like to know if there could be any alternate solution.
Does this problem/solution sound familiar? Is there anything that can be improved?

A: This described problem reminds me the Adapter and Facade Patterns: Being Adaptive.
While reading your question, i also have remembered a famous funny old saying:

If it walks like a duck and quacks like a duck, then it must be a turkey wrapped with a duck adapter...

You may get detailed explanation from the following book - Head First Design Patterns
In addition, there are SOLID principles and Liskov Substitution Principle is one of them. It also addresses this issue with a different flavor.

If it looks like a duck, quacks like a duck, but needs batteries – you probably have the wrong abstraction

A: It is a mistake to use inheritance with the Legs classes and interfaces.(But if your teacher/boss insists that you have to...you'll probably have to give in.)
Your design works well enough for the requirements you listed. But suppose there is a Horse that can both run and jump. How do you implement that?
I suggest that WalkingLegs, RunningLegs, and JumpingLegs should all be separate classes with no inheritance. The Tiger would have  WalkingLegs and RunningLegs, the Kangaroo would have WalkingLegs and JumpingLegs, and the Horse would have all three.
The above suggestion confuses the Legs metaphor. What we are really modeling is behavior, not types of legs.
Using classes to represent a behavior is part of the strategy pattern. In the strategy pattern, behaviors have different implementations (in this example, different implements of walking, jumping, etc.)

A: To me, it seems like case of bad abstraction. Base classes are for abstracting behavior that is same for all expected children. Which is wrong in your example. In your case you either want Move virtual method, and then override it in concrete animals. Or you want Jump and Run methods, but then there is nothing common between them, so abstracting it away doesn't make sense.
And there is one rule I like when doing this :

Abstractions should always be seen from point of who will use those abstractions. Not from the inside of the implementation.

If you are writing some abstraction and you haven't written code that will use this abstraction, then you are doing something wrong.

A: I would probably implement something along the lines of this:
public abstract class Animal: ILegs
{
    public virtual void Walk(){/*Base logic for walking*/}
}

public interface ILegs
{
    void Walk();
}

public interface IJumpingLegs
{
    void Jump();
}

public interface IRunningLegs
{
    void Run();
}

public class Kangeroo : Animal, IJumpingLegs
{
    public void Jump()
    {
        //Logic for Jumping
    }
}

public class Tiger : Animal, IRunningLegs
{
    public void Run()
    {
        //Logic for Jumping
    }
}

//Custom Implementation
public class OtherAnimal : Animal
{
    public override void Walk() { /*Custom how I walk*/ }
}

When instanciating my objects I would use
OtherAnimal a = new OtherAnimal();
a.Walk(); //Custom override logic fro OtherAnimal class

Tiger t = new Tiger();
t.Run();  //Custom Run logic
t.Walk(); //Logic from Animal abstract class

Each Tiger/Kangeroo class only implements the necessary interface for each class and is not inheriting any unnecessary logic and not breaking the Liskov Substitution Principle mentioned by @Yusubov.
The Tiger/Kangeroo class also use the base Walk() logic from the Animal abstract class and have the option if necessary to override it lie the OtherAnimal class does.
Just don't implement a Fish class or similar extending the Animal. Fish don't walk, or have Legs!!


text:
Q: Switch Apple ID I bought an iPad 2 last May and used my husband's Apple ID that he uses for iTunes.
I have used his ID to buy apps for my iPad 2 and even bought iTunes cards to put on his account. Well, now I have an iPhone, iMac and have my own Apple ID.
Question - can I switch it to my ID without him losing his ID?  I have found where I can edit my ID but I don't want him to lose his account.

A: He won't lose his account if you switch Apple IDs. However, you might want to  continue to share his ID for iTunes and App Store purchases (for all of your Apple devices) so you will keep convenient access to the apps and media you've already purchased and you can both share your purchases on your various devices. You can use your new Apple ID for iCloud services.

A: You can only have one Apple ID linked to a device, and considering you now have the iPhone and a Mac it is a good idea to sign up for your own Apple ID rather than edit his.
In order to keep all your previous purchases you will need to sync the device with your computer.
However before you sync with the computer you should authorize both your new Apple ID and his old one. iTunes will then sync all the purchases made on both accounts to your devices, while keeping iCloud content linked to only your devices


text:
Q: pandas `read_sql_query` - read `double` datatype in MySQL database to `Decimal` I'm trying to use read_sql_query() to read a query from  MySQL database, one of the field in the database, its type is double(24, 8), I want to use dtype= parameter to have full control of the datatypes and read it to decimal, but seems like pandas can't recognize decimal type so I had to read it to Float64
In the database, the values for this field look like this:
Value
100.96000000
77.17000000
1.00000000
0.12340000

Then I'm trying to read it from Python code:
from decimal import *

dtypes = {
        'id': 'Int64',
        'date': 'datetime64',
        'value': 'Float64'
    }

df = pd.read_sql_query(sql_query, mysql_engine, dtype=dtypes)

but after reading the data from the code above, it looks like this:
Value
100.96
77.17
1.0
0.1234

How can I read this column to decimal and keep all the digits? Thanks.

A: What "the data looks like in the database" is tricky.  This is because the act of printing it out feeds the bits through a formatting algorithm.  In this case it removes trailing zeros.  To see what is "in the database", one needs to get a hex dump of the file and then decipher it; this is non-trivial.
I believe that DECIMAL numbers hold all the digits specified, packed 2 digits per byte.  No, I don't know how they are packed (0..99 versus 2 hex digits; what to do if the number of digits is odd; where is the sign?)
I believe that FLOAT and DOUBLE exactly conform to IEEE-764 encoding format.  No, I don't know how the bytes are stored (big-endian vs little-endian).  I suspect Python's Float64 is IEEE DOUBLE.
For DECIMAL(10,6), I would expect to see "1.234" to be stored as +, 0001, and 234000, but never displayed with leading zeros and optionally displayed with trailing zeros -- depending on the output formatting package.
For DOUBLE, I would expect to find hex 3ff3be76c8b43958 after adjusting for endianism, and I would not be surprised to see the output be 1.23399999999999999e+0.  (Yes, I actually got that, given a suitable formatting in PHP, which I am using.)  I would hope to see 1.234 since that is presumably the intent of the number.
Do not use DOUBLE(m,n).  The (m,n) leads to extra rounding and it is deprecated syntax.  Float and Double are not intended for exact number of decimal places; use DECIMAL for such.
For FLOAT:  1.234 becomes hex 3f9df3b6 and displays something like 1.2339999675751 assuming the output method works in DOUBLE and is asked to show lots of decimal places.
Bottom line:  The output method you are using is causing the problem.


text:
Q: Doctrine ODM query by subfield of reference-one I have an existing MongoDb database:
Foo
{
  "_id": ObjectId(123456789),
  "name": "foo_1",
  "barId": 123,
  "sellerId": 456
}

Bar
{
  "_id": "123",
  "ref": "A1",
  "status": "paid"
}

Here is my mapping:
<document name="Foo">
   <id />
   <field field-name="name" type="string" />
   <field field-name="status" type="string" />
   <reference-one target-document="Bar" field="barId" store-as="id"/>
</document>

<document name="Bar">
   <id strategy="NONE" type="string" />
   <field field-name="ref" type="string" />
   <field field-name="status" type="string" />
</document>

I want to query all Foo filtered by sellerId and Bar.status = "paid"
But I can only filter by Bar id and no other fields. How can I do that?
//FooRepository.php

public function getAll(string $sellerId)
{
     $query = $this->createQueryBuilder()
                   ->field('sellerId')->equals($sellerId) // ok
    //             ->field('barId.status')->equals('paid') // ko
                   ->field('barId')->equals('123') // ok
            ;

     $query->readOnly();

     return $this->paginate($query);
}

A: MongoDB's querying does not support "joins" like relational databases do. The closest thing to a LEFT JOIN is aggregation pipeline's $lookup. Please refer to ODM's documentation on how to use aggregation builder and its stages with the library.


text:
Q: Is there any alternative for PageFactory using net core I'm using Selenium v3.6.0 and .NET Core 2.0, the following code gives me an error on PageFactory.InitElements saying it doesn't exist in the currenct context.
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;

namespace Example
{
    public class Form
    {
        [FindsBy(How = How.Name, Using = "Filter")] // This does exist in current context using .NET Core
        public IWebElement Filter { get; set; }

        [FindsBy(How = How.TagName, Using = "Button")]
        public IWebElement Button;

        public Form(IWebDriver driver)
        {
            PageFactory.InitElements(driver, this); // This doesn't exist in current context using .NET Core
        }
    }
}

I'm a bit confused about this since the attributes FindsBy, FindsByAll and FindsBySequence are all available in the OpenQa.Selenium.Support.PageObjects namespace, but PageFactory is not. To my knowledge, these attributes only work with PageFactory.
Is there a different approach to this using .NET Core or is it just not (yet) implemented?

A: I'm using WebDriver V3.141.0.0 and .NET v4.5 and you can replace your code as follows:
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;

namespace Example
{
    public class Form
    {
        public IWebElement Filter => Driver.FindElement(By.Name("Filter"));
        /*
        [FindsBy(How = How.Name, Using = "Filter")] // This does exist in current context using .NET Core
        public IWebElement Filter { get; set; }
        */

        public IWebElement Button => Driver.FindElement(By.TagName("Button"));
        /*
        [FindsBy(How = How.TagName, Using = "Button")]
        public IWebElement Button;
        */
        public Form(IWebDriver driver)
        {
            //PageFactory.InitElements(driver, this); // This doesn't exist in current context using .NET Core
        }
    }
}

A: Not specific to .Net Core but for .Net Standard 2.0 and .Net Framework(s) 3.5, 4.0, & 4.5 you should be able to add DotNetSeleniumExtras.PageObjects to your project to get PageFactory functionality once OpenQA.Selenium officially drops it. You would reference this by: using SeleniumExtras.PageObjects;

A: There is no PageFactory class in WebDriver.Support.dll for version 3.6.0 (In visual studio you can open this dll in object explorer and see that there is no such class). So you've got just usual compilation error.
I've looked source code on github https://github.com/SeleniumHQ/selenium/blob/master/dotnet/src/support/PageObjects/PageFactory.cs
and see preprocessor directive #if !NETSTANDARD2_0  ... #endif in PageFactory class. I don't know why NETSTANDARD2_0 affected NETCORE2_0, and not sure that it's real reason, but for us as library users PageFactory is unaccessible for now.

A: DotNetSeleniumExtras.PageObjects.Core is supporting  .NETStandard 2.0.
The library contains PageFactory and supporting classes. It's a fork of DotNetSeleniumExtras.
It's Tested in netcore3.1 and Net5 and the package support PageFactory.InitElements(driver, this);
To use:
Install-Package DotNetSeleniumExtras.PageObjects.Core -Version 3.12.0

using OpenQA.Selenium;
using SeleniumExtras.PageObjects;


text:
Q: How to pass a dictionary with more arguments into a proc in tcl? proc test {a b c } {
       puts $a
       puts $b
       puts $c
}
set test_dict [dict create a 2 b 3 c 4 d 5]

Now I want to pass dict into test like this:
test $test_dict

How to make test only selects three elements in the dict with the same name of its parameters (the keys). The expected output should be:
2
3
4

Because it selects a b c in the dictionary but not d. How can I do this? I saw some code does like this but I can't make it work.

A: I think you should use dict get:
proc test {test_dic} {
  puts [dict get $test_dic a]
  puts [dict get $test_dic b]
  puts [dict get $test_dic c]
}

set test_dict [dict create a 2 b 3 c 4 d 5]
test $test_dict

Edit:
Another variant would be to use dict with:
proc test {test_dic} {
  dict with test_dic {
    puts $a
    puts $b
    puts $c
  }
}

set test_dict [dict create a 2 b 3 c 4 d 5]
test $test_dict

But test gets still a list.


text:
Q: Which Linux kernels and Linux distros are supported by G-WAN? I can find a statement at the beginning of the user's manual:

version 3 for Linux
  (tested with Debian and CentOS 32-bit and 64-bit)

I am using Ubuntu 12.10 64-bit for development.
So far, I found no problem with it, but I still have no confidence on it, since there is no official announcement from gwan about this.

A: At least G-WAN v3.3 should be compatible with the Linux distributions used when the development started in 2009 (Ubuntu 8+).
G-WAN v3.10+ added significant enhancements detailled below.
There are many different Linux distributions, but most of them use a common 'root' distribution, and the most commonly used are Debian (Ubuntu uses Debian) and Red Hat (CentOS uses Red Hat), both of which have been tested during development.
But the other distributions rely on the same Linux kernel, making any difference only possible in 'extensions' like file systems, etc. And, thanks to its users feedback, G-WAN v3.10+ has fixed non-standard file system issues (by handling those FSs that ignore system flags).
For this same reason, old GBLIC versions could also a problem for G-WAN v3.3, but G-WAN v3.10+ re-implemented those function calls that could pose problem so 10-year old Linux distribution should work fine now.
This is why list of Linux distributions that support G-WAN is very large - probably too large to be worth publishing.
Now, the kernel question is more interesting, not because it is a blocking issue (in G-WAN v3.10+, wrappers have been written for potentially missing syscalls since the Linux kernel 2.5.8) but because of the lack of performance on very old Linux kernels.
In those old kernels, G-WAN can't benefit as well as multicore systems because the OS kernel itself does not support multicore. But since G-WAN is fast server even when used with one single thread, G-WAN will not be the bottleneck.
Compatibility is an incremental process since new versions of the system parts (OS kernel, GLIBC, other system tools and libraries, etc.) are not always backward-compliant (remember the recent Linux linker issue).
In this regard, user feedback rules - and G-WAN has made tremendous efforts in this matter recently.

A: I've made a bash script to install most of (if not) all the required packages and dependencies used to run the 90+ G-WAN servlets with the latest G-WAN release (at the time of this post (03-16-2016): the last public G-WAN release #7.12.6 64-bit).
You can get this installation script (that also downloads and installs G-WAN itself): here
Then, use the following commands (in a terminal session - Desktop or Server flavor):
cd /the-folder-where-you've-downloaded-the-script
tar -xjf G-WAN_full-install.tar.bz2
sudo ./G-WAN_full-install

This script (with English (default tongue), French, German and Spanish dialogs used with regard to your OS language) will allow you to both install G-WAN and select the 15 different programming languages available with G-WAN (and their required packages depending of your OS distribution) to play with almost all the 90+ G-WAN free provided servlets with the following Linux distributions:
-ArchLinux
-Bridge
-CentOS
-Debian
-ElementaryOS
-Fedora
-LMDE
-Manjaro
-Mint
-RHEL
-Ubuntu and all its derivatives (Kubuntu, Lubuntu, etc.).

and whatever the kernel version.
The 15 programming languages currently are:
-ANSI C
-ASM
-C++
-C# (Mono)
-Gnustep
-Go
-Java
-Javascript (NodeJS)
-Lua
-Perl
-PH7 (the PHP compiler)
-PHP (the php5-cli mode)
-Python
-Ruby
-and Scala

Note: Objective C and Objective C++ are also available but only with Ubuntu Precise Pangolin (12.04 LTS).
Hope this helps.
Please feel free to come back to me for any impovement to make to this script.


text:
Q: Correct call PHP mysqli_fetch_array() My connection passes in class DB.connect.php with method mysqli_connect. How can I correct to call a function mysqli_fetch_array() inside my while cycle?
My code:
class DB_Functions {

private $conn;

// constructor
function __construct() {
    require_once 'DB_connect.php';
    // connecting to database
    $db = new Db_Connect();
    $this->conn = $db->connect();
} ...

...
public function getCount($date1, $date2) {

    $stmt = $this->conn->prepare("SELECT * FROM Sales WHERE date_of_sell >= ? AND date_of_sell <= ? ");

    $stmt->bind_param("ss", $date1, $date2);

    $stmt->execute();

    $stmt->store_result();
    // $count=5;
    //
    $count = $stmt->num_rows;

    if ($stmt->num_rows > 0) {
         while ($row = ???) {
             $count = $count + 1;
       }
    }

    $stmt->close();
    return $count;
  }
}

A: If I understood your question right, you want to return the number of rows after executing your sql query. If so, try this:
public function getCount($date1, $date2) {
    $stmt = $this->conn->prepare("SELECT * FROM Sales WHERE date_of_sell >= ? AND date_of_sell <= ? ");
    $stmt->bind_param("ss", $date1, $date2);
    $stmt->execute(); // Executes a prepared Query

    // Solution 1
    $arr = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    if(!$arr) exit('No rows');
    var_export($arr);
    $stmt->close();

    // Solution 2
    $result = $stmt->get_result();
    if($result->num_rows === 0) exit('No rows');
    $tmp = [];
    while($row = $result->fetch_assoc()) {
        $tmp[] = [
            "field1" => $row['field1'],
            "field2" => $row['field2'],
            "field3" => $row['field3']
        ];
    }
    $stmt->close(); // Closes a previously opened database connection
    return $tmp;
}


text:
Q: Executing php script on powershell Good Day!
I have a powershell code and I would like to run a php script at the very end. I have tried searching for solutions but I can't seem to bump on any. All I could find is to run php script through a batch file. Running a php script using powershell, Is this possible? If so, how?

A: Use the call operator (&):
# Set up references to executable and script
$PhpExe  = "C:\path\to\php\install\dir\php.exe"
$PhpFile = "C:\path\to\script.php"

# Create arguments from Script location
# usually php.exe is invoked from console like:
# php.exe -f "C:\path\myscript.php"
$PhpArgs = '-f "{0}"' -f $PhpFile

# Invoke, using the call operator
$PhpOutput = & $PhpExe $PhpArgs

A: I tried using @Mathias R. Jessens answer above but it wouldn't work for me, the reason was the $PhpArgs = '-f "{0}"' -f $PhpFile contained the first '-f' part. So using his answer (and what worked for me was)
# Set up references to executable and script
$PhpExe  = "C:\path\to\php\install\dir\php.exe"
$PhpFile = "C:\path\to\script.php"

# Create arguments from Script location
# usually php.exe is invoked from console like:
# php.exe -f "C:\path\myscript.php"
$PhpArgs = '"{0}"' -f $PhpFile //Changed this line!

# Invoke, using the call operator
$PhpOutput = & $PhpExe $PhpArgs

Hope it helps someone :)


text:
Q: Avoiding dbo.arcsde LOCK issue while exporting to ArcSDE? I had a spatial db connection open in arcmap. While exporting to SDE with a console app I get an error in the console:

Lock request conflicts with an established lock [DBO].

Does this just mean someone is using the same ArcSDE connection or is it the feature dataset?
Of course when I closed arcmap, and fired the console app again, my feature class exported to ArcSDE successfully.
Can I kill any locks programmatically if I am DBO (when other users are using the same FD)?
If that's not smart, how can I avoid this lock?
How does the GIS community deal with this issue, wait till all users are off and run it at 2am?
The console app will become a batch process updating FCs on a regular basis.

A: Your console app has its own connection since it is running on a different process - there is no "sharing of connections" in that use case.
Anytime ArcMap connects and opens a dataset, it creates a shared schema lock on a FC (and all related versioning, history, relationship clases, etc, tables). This is just to make sure that the schema doesn't change. Another thing to keep in mind is that if you open a FC inside FeatureDataset, this will cause your workspace to get a shared lock of all the FCs inside that FD as well.
On the other hand, exclusive locks are used for DDL operations (i.e. changing schema).
So I assume that your "load" operation is actually dropping the entire table (a schema change) and then recreating the table. For that, you would need an exclusive schema lock.
Consider just truncating the table using sdetable –o truncate before loading the new one. You may not need to kick anyone out.
Oh yeah, and don't remove locks just because. If you are, kick the users out instead of changing locks underneath them which will lead to bad things.

A: You can kill any active connections to the database from SQL Server, however this will also kill the connection you have opened in ArcMap.
Here is a link to a site with a stored procedure for clearing all connections to the DB:
http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/b41a7376-d5cd-4339-92b3-158e88a96dff?prof=required
Before firing that off, you can use the sp_who command to check if any other users are working with that database.

A: The ESRI commandline tools for ArcSDE are your best option to kill a process or connection without risking a corruption or damage to your Geodatabase.
From the looks of what your message says; it does appear that someone is reading/connected to that feature dataset. And you are not able to make changes to a FD while any of the containing layers are in use.