text:
Q: Pandas yahoo finance DataReader I am trying to get the Adj Close prices from Yahoo Finance into a DataFrame. I have all the stocks I want but I am not able to sort on date.
stocks = ['ORCL', 'TSLA', 'IBM','YELP', 'MSFT']
ls_key = 'Adj Close'
start = datetime(2014,1,1)
end = datetime(2014,3,28)
f = web.DataReader(stocks, 'yahoo',start,end)

cleanData = f.ix[ls_key]
dataFrame = pd.DataFrame(cleanData)

print dataFrame[:5]

I get the following result, which is almost perfect.
              IBM   MSFT   ORCL    TSLA   YELP
Date
2014-01-02  184.52  36.88  37.61  150.10  67.92
2014-01-03  185.62  36.64  37.51  149.56  67.66
2014-01-06  184.99  35.86  37.36  147.00  71.72
2014-01-07  188.68  36.14  37.74  149.36  72.66
2014-01-08  186.95  35.49  37.61  151.28  78.42

However, the Date is not an Item. so when I run:
print dataFrame['Date']

I get the error:
KeyError: u'no item named Date'

Hope anyone can help me adding the Date.

A: Date is in the index values.
To get it into a column value, you should just use:
dataframe.reset_index(inplace=True,drop=False)

Then you can use
dataframe['Date']

because "Date" will now be one of the keys in your columns of the dataframe.

A: Use dataFrame.index to directly access date or to add an explicit column, use dataFrame["Date"] = dataframe.index
stocks = ['ORCL', 'TSLA', 'IBM','YELP', 'MSFT']
ls_key = 'Adj Close'
start = datetime(2014,1,1)
end = datetime(2014,3,28)
f = web.DataReader(stocks, 'yahoo',start,end)

cleanData = f.ix[ls_key]
dataFrame = pd.DataFrame(cleanData)
dataFrame["Date"] = dataframe.index
print dataFrame["Date"] ## or print dataFrame.index

A: This should do it.
import pandas as pd
from pandas.io.data import DataReader

symbols_list = ['ORCL', 'TSLA', 'IBM','YELP', 'MSFT']
d = {}
for ticker in symbols_list:
    d[ticker] = DataReader(ticker, "yahoo", '2014-12-01')
pan = pd.Panel(d)
df1 = pan.minor_xs('Adj Close')
print(df1)

#df_percent_chg = df1.pct_change()

A: import pandas_datareader.data as web
import datetime

start = datetime.datetime(2013, 1, 1)
end = datetime.datetime(2016, 1, 27)
df = web.DataReader("GOOGL", 'yahoo', start, end)

dates =[]
for x in range(len(df)):
    newdate = str(df.index[x])
    newdate = newdate[0:10]
    dates.append(newdate)

df['dates'] = dates

print df.head()
print df.tail()

A: The sub-package pandas.io.data is removed from the latest pandas package and it is available to install separately as pandas-datareader
use git to install the package.
in the linux terminal:
git clone https://github.com/pydata/pandas-datareader.git
cd pandas-datareader
python setup.py install

now you can use import pandas_datareader to your python script for Remote data Access.
For more information Use this link to visit the latest documentation

A: f is a Panel
You can get a DataFrame and reset index (Date) using:
f.loc['Adj Close',:,:].reset_index()

but I'm not sure reset_index() is very useful as you can get Date using
f.loc['Adj Close',:,:].index

You might have a look at
http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing
about indexing

A: print(dataFrame.index[0])
2014-01-02 00:00:00

A: import pandas_datareader.data as web
import datetime
start = datetime.datetime(2015, 1, 1)
end = datetime.datetime(2016, 1, 1)
web.DataReader('GOOGL', 'yahoo', start, end)


text:
Q: appleevent versus notification I am looking for a high performance inter process communication system in macos X.
What is the best system? AppleEvents or NSNotifications?

A: Distributed notifications (i.e. notifications sent through NSDistributedNotificationCenter) are most likely not a good option if your goal is high performance and/or reliability. Here is Apple's own take on this subject:

Posting a distributed notification is an expensive operation. The notification gets sent to a system-wide server that distributes it to all the tasks that have objects registered for distributed notifications. The latency between posting the notification and the notification's arrival in another task is unbounded. In fact, when too many notifications are posted and the server's queue fills up, notifications may be dropped. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDistributedNotificationCenter_Class/Reference/Reference.html

Depending on what you mean by "high performance", you might want to look into distributed objects, or plain old Unix IPC mechanisms (sockets, pipes, shared memory etc).

A: If you control both the sender and the recipient, you can open a socket between the two processes ( man socketpair ), which is quite high performance.  You can also open a file in a shared location ( like /tmp ) and write to it from one process and read from the other, which is quite speedy.  You can also open two TCP/IP ports on the local machine, one in each process, and then send from one to the other "over the network".
If your only two choices are NSNotifications or AppleEvents, well, AppleEvents will likely perform better.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Name a good guide for the implementation of an STL compatible sequence container) I'd like to implement a sequence container with the bells and whistles required for an STL class - for example, my own deque class that can use all of the STL algorithms and utilities that the normal deque class could use.  I'm aware all the STL components and how they work, but I'd definitely miss alot trying to do this on my own.
Does anyone know a good tutorial or reference/checklist that I could use for this purpose?  I'm trying to reinforce the mechanisms in my mind by making one of these classes.
PS - I'm just looking for a link with the information that I need and a half-sentence description, I don't need a discussion of what is best and why as long as the information is there :)

A: A container must implement a series of Concepts.
A comprehensive list can be found here:
http://www.sgi.com/tech/stl/Container.html
Simply implement the requirements there, and you got yourself a container.


text:
Q: How to pass model to controller action using ajax call? Im using ajax call to pass model data in to my controller action , but controller receives empty model when I call via ajax ,
Here is my controller
[HttpPost]
public ActionResult Edit( int id, ALDS.Web.Areas.Direct2M3.Models.ItemInputModel collection)
{
    try
    {
        // TODO: Add update logic here
        return View("Index");
    }
    catch
    {
        return View();
    }
}

And here is my input model
public class ItemInputModel
{
    [Key]
    public long ID { get; set; }
    [DisplayName("Buyer Code")]
    public string ModelCode { get; set; }
    [DisplayName("BOM Description")]
    public string BOMDescription { get; set; }
    //BUYER CODE
    [DisplayName("UOM")]
    public string UOM { get; set; }
    [DisplayName("Alternative UOM")]
    public string AltUOM { get; set; }
    [DisplayName("Garment Color Wise")]
    public string ColorWise { get; set; }
    [DisplayName("Garment Size Wise")]
    public string SizeWise { get; set; }
    [DisplayName("RM Color Wise")]
    public string RMcolorWise { get; set; }
    [DisplayName("RM Size Wise")]
    public string RMsize { get; set; }
    [DisplayName("Procument Group")]
    public string BrandixProcurementGroupCode { get; set; }
    [DisplayName("Designation CPT")]
    public string DesignationCPT { get; set; }
    [DisplayName("Item Name")]
    public string ItemName { get; set; }
    [DisplayName("Fabric Composition")]
    public string FabricComposition { get; set; }
    [DisplayName("Hierachy Code ")]
    public string HierarchyCode { get; set; }
    [DisplayName("GSM Value")]
    public string GSMValue { get; set; }
    [DisplayName("RM Width")]
    public string RMWidth { get; set; }
}

Here is my ajax call from the view
$.ajax({
    type: 'POST',
    dataType: 'application/json; charset=utf-8',
    cache: false,
    url: '/ItemMaster/Edit',
    data:{ id: collection.ID, collection:collection},
    success: function (data, textStatus, jqXHR) {
        alert("ok");
        //Do Stuff
        //$("#DailyInvoiceItems").html(data.Id);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('Failed');
        //Do Stuff or Nothing
    }
});

and im using this model to pass to the action from the , ajax
var model = {
    ID: $('#ID').val(),
    ModelCode: $('#txtModelCode').val(),
    BOMDescription: $('#txtBOMDescription').val(),
    UOM: $('#txtUOM').val(),
    AltUOM: $('#txtAltUOM').val(),
    ColorWise: $('#ddnColorWise').val(),
    SizeWise: $('#ddnSizeWise').val(),
    RMcolorWise: $('#ddnRMcolorWise').val(),
    RMsize: $('#ddnRMsize').val(),
    BrandixProcurementGroupCode: $('#ddnBrandixProcurementGroupCode').val(),
    DesignationCPT: $('#txtDesignationCPT').val(),
    ItemName: $('#txtItemName').val(),
    FabricComposition: $('#txtFabricComposition').val(),
    HierarchyCode: $('#txtHierarchyCode').val(),
    GSMValue: $('#txtGSMValue').val(),
    RMWidth: $('#txtRMWidth').val()
};

I put a break point inside the action method and inspect the collection parameter but it is an empty input object , with null properties !
Can anyone help me????
Thankz,.

A: There are a number of errors with ajax code. First your method returns html (a view - although it should be a partial view) so it need to be dataType: 'html', or you can omit it altogether. Second because your sending an object containing objects, you would need to stringify the data (using data: JSON.stringify({ id: collection.ID, collection: model}), and add the contentType: 'application/json; charset=utf-8', option (note the name of your javascript object is model, not collection.
However most of this code is unnecessary. Your model already contains a property long ID so there is no need to post and bind it twice and you controller method can be just
[HttpPost]
public ActionResult Edit(ItemInputModel model)
{
    ....
    return PartialView(..), // not View(..)
}

Assuming you have generated your form controls correctly using the strongly typed HtmlHelper methods, for example
@Html.HiddenFor(m => m.ID)
@Html.TextBoxFor(m => m.ModelCode)
....

then you can use the .serialize() method to correctly serialize all the form controls, so that your ajax becomes
var data = $('form').serialize(); // or use the id of the form is you have given it one
$.ajax({
    type: 'POST',
    dataType: 'html', // this can be omitted - the ajax() function will work it out
    cache: false,
    url: '/ItemMaster/Edit',
    data: data,
    success: function (data, textStatus, jqXHR) {
        ... // append the partial view you return to the DOM?
    },
    error: function (jqXHR, textStatus, errorThrown) {
        ....
    }
});

Side note: You should always use Url.Action() to generate the correct url's, for example url: '@Url.Action("Edit", "ItemMaster")',. If this script is in an external file, then generate it in the main view (e.g. as a data-* attribute an the button element your handling) and pass it to the function.


text:
Q: How to add new partitions automatically in partitioned table based on data inserted in GreenPlum.? I have a partitioned table in greenplum(modeled after psql), which has been partitioned with specific range of values.
Now, i have to insert the data again into the same table. New values for Partitions might overlap with existing ones. I have created alter command with new start and end dates. But, if the overlaps are there, the command fails. So, i need to create partition for each date, in order to avoid whole command failure.
Just wondering, if there is a way in greenplum to create partitions based on the inserted data automatically, just like hive does.
thanks for your help.

A: Greenplum does not (currently) create additional partitions for data which does not fit into an existing partition.
If you have a default partition on the table it will receive all the records which do not fit into one of the specified partitions. You can then use ALTER TABLE ... SPLIT DEFAULT PARTITION (see the documentation if required) to create the new partitions for any new dates at the end of the load batch.


text: Q: intuitive explanation for expected value of the square of a uniform variable I'm confused about something that should be simple. Suppose I have a random uniform variable $X$ on $[0,1]$. It's fairly clear that the expected value of $X$ is 1/2. By integrating $x^2$ on $[0,1]$, I get that the expected value of $x^2$ is 1/3. I'm struggling to understand this intuitively, as I would expect it to be $1/4$ i.e. $(1/2)^2$.


text:
Q: Feathers.js -> Change the layout of the after create hook I've set up nuxt.js, converting my feathers project. So far it is functioning. Added something through postman appears in my browser on the webpage. There is on difference, namely when I post something the entire dataarray is pushed which doesn't match the initial array.
Sample
{ "message_txt": "Hello todays2" }
{ "id": 17, "message_txt": "Hello YESd", "updated_at": "2017-03-25T11:15:44.000Z", "created_at": "2017-03-25T11:15:44.000Z" }

So the first line is how the data is configured to be returned. This is set in my hooks file:
'use strict';

const globalHooks = require('../../../hooks/index');
const hooks = require('feathers-hooks');

exports.before = {
    all: [],
    find: [
        getRelatedInfo()
    ],
    get: [
        getRelatedInfo()
    ],
    create: [],
    update: [],
    patch: [],
    remove: []
};

exports.after = {
    all: [],
    find: [],
    get: [],
    create: [
        getRelatedInfo()
    ],
    update: [],
    patch: [],
    remove: []
};

function getRelatedInfo() {
    return function (hook) {
        hook.params.sequelize = {
            attributes: [
                'message_txt'
            ],
            order: [
                ['created_at', 'DESC']
            ]
        };
        return Promise.resolve(hook);
    };
}

Currently, my client loads the data with this part:
<template>

        idnex.vue

                {{ message }}

</template>

Question
What do I need to do make sure the "this.messages.push(message)" is in the same structure, so only "message_txt". I tried adding the function in the hooks to the "after create" but it doesn't work.
Solving
Okay, so changing the component file of the client gives access to the service, model, and hooks and what else of the service as configured in the client. The 'service.find()' is just there for I copied it from a more complex service where more columns are in the find hook and I only want specific ones.
<template>

        idnex.vue
        todo: eagle.js slideshow
        todo: first info

                {{ message }}

</template>

With this code, the page still loads but the 'this.listMessages' still also give stuff like the created_at. Also, when I didn't have nuxt and a client/server situation (client and server were one) I didn't need the 'on created' for the list displayed to be updated real time. I still need to have the line for realtime update.
Important note, I just noticed that in postman you also see the entire record information and not the same information as with the GET
So nearly there. I figured out what to do in my hooks file
exports.after = {
    all: [],
    find: [],
    get: [],
    create: [
        hooks.remove('createdAt'),
        hooks.remove('updatedAt')
    ],
    update: [],
    patch: [],
    remove: []
};

In this file I have the above section. If I change the column in the remove to a 'custom' one (which is in the model) it will work. These two don't work

A: this.messages.push(message.message_txt); ?...
Ahh I think I see what you are really asking now. Only params.query will be passed between the client and the server for security reasons. If you would like to set params.sequelize based on query parameters you have to sanitize and map it in a hook:
app.service('myservice').before(function(hook) {
  const query = hook.params.query;

  hook.params.sequelize = {};

  if(query.someSequelizeParameter) {
    hook.params.sequelize.myParameter = sanitize(query.someSequelizeParameter);
    delete query.someSequelizeParameter;
  }
});

The other options is to just use Feathers hooks instead. Also, not part of your question, but if you are using sockets anyway, you really don't need a need Axios and the REST stuff updated via methods, you can just tie the service to the socket and use something like RxJS to stream all updates in real time. What you are doing is fine and will work, but with a lot more code to maintain.


text:
Q: Generic log-table for CRUD operations that support both single and composite Primary Keys I'm trying to come up with a decent table design for a table that will log CRUD operations for a small application. There won't be a lot of traffic, which could justify a single table for all events. So far, my idea looks like this
ID int identity primary key,
[Schema] nvarchar(128),
[Table] nvarchar(128),
ObjectID int, -- primary key of the object we're logging
Action nchar(1) , -- the type of event (I/U/D, short for INSERT, UPDATE etc
Field nvarchar(128), -- the changed column, in the event of UPDATE
OldValue nvarchar(1000),
NewValue nvarchar(1000),
ChangedAt datetime2,
ChangedBy nvarchar(128)

This would cover most of our use cases. There is, however, one itch with this design, and that is when I want to log changes to records where the Primary Key spans multiple columns, aka a Composite Primary Key.
In order to satisfy this need, I would have to extend the proposed table-design with yet another ID-column, allowing us to store both sides of the composite primary key.
You probably see that this is heading down the wrong path. What if I later need to log events for a table containing a Primary Key spanning 3 columns or more? Simply extending the log-table with "ObjectID_2" and "ObjectID_3" columns sounds asinine. Not to mention that the majority events will only have NULL-markers in those columns, as most our tables use single-column primary keys.
I am no fan of generic tables and column in general, and I'm starting to think a better solution would be to keep a separate log-table for each table that needs auditing. Am I going about this the wrong way?
Change Tracking does not solve this problem. The log-table needs to be exposed to the web and in a human-readable format. I have considered both CDC and Temporal Tables, but then we'd already be in the realm of "log everything for a single table", which is not my use-case. The log-table will be used by the application to log whatever events they care about, not every DML operation. That's is why I opted for a single-table solution.

A: Your issue sounds like it colud make use of a dimensional model, with the objects to be tracked as Dimension(s) and the events to be measured as Facts, especially if this table needs to be human readable and exposed to end users. Check out this resource for further reading BACK TO DIMENSIONAL MODELING BASICS and The 10 Essential Rules of Dimensional Modeling


text:
Q: Xpath for Text of  tag until Following-sibling::h2[text()='some text'] I want xpath for all text of
 tag following by first h2 until Next h2
Xpath should be like //h2[text()='Title 1']/following::p  with condition
----other code-----

Title 1

Title 1 text

Title 1 text

Title 2

Title 2 text

Title 2 text

----other code-----

I expect the result as Title 1 text, but actual output is Title 1 text and Title 2 text
Note: count of the
 tag is not fixed.

A: using xpath 2.0, use this.
   distinct-values(//p[following-sibling::h2[text()='Title 2'] or preceding-sibling::h2[text()='Title 1']]/text())


text:
Q: Get formatted log message When you log a message, for example:
log.error("This is a message");

The message is formatted by the layout before logged in a file. For example:
2014-12-12 13:45:18 ERROR This is a message
How can I get this formatted message programmatically?
I'm using JAVA with log4j.
Thanks.
EDIT:
I think one solution is generating a LoggingEvent programmatically and call the format method of my custom Layout, but I think it will not have the same timestamp.

A: I will assume you are using log4j 2 (haven't got the reputation to comment to ask for clarification - the answer would differ a lot for log4j 1.2).  The solution below gives you programmatic access to a String object that contains the exact same string as the message output to the file.
In this case - you can get the actual formatted string as follows:

*

*get the MessageFactory : myFactory = Logger.getMessageFactory();

*call String formattedCopyOfMessage = myFactory.newMessage("This is a message").getFormattedString();
This is an unusual use case.
Note - the method I suggest doesn't give you acces to the actual object the logger generates, it is a different String object that will contain the same string of characters.

A: You question is not clear. Did you mean how to set the layout of an log4j appender programmatically? If so here's how you would do it
  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN));
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

You can then remove all existing appenders on the root logger with
 Logger.getRootLogger().getLoggerRepository().resetConfiguration();


text:
Q: How to write this nested query? Here are 2 queries. Which one is correct?
SELECT link.[xlink:Show].
       Location.[xlink:show],
       link.[xlink:actuate],
       Location.[xlink:actuate],
  FROM Sem
  JOIN Location AND
         Link join Location ON
         link. link_id = Location.link_id);

Error: Incorrect syntax near the keyword 'AND'.
SELECT link.[xlink:Show],
       Location.[xlink:show],
   link.[xlink:actuate],
       Location.[xlink:actuate],
       Sem.SemRole
  FROM Sem, Link
  JOIN Location ON link. link_id = Location.link_id);

Error: The multi-part identifier " Sem. SemRoleId" could not be bound.

A: Try this:
SELECT LI.[xlink:Show],
       LI.[xlink:actuate],
       LO.[xlink:show],
       LO.[xlink:actuate],
       S.SemRole
FROM Sem AS S
INNER JOIN Location AS LO ON S.SemRoleId = LO.SemRoleId
INNER JOIN Link  AS LI ON LI.link_id = LO.link_id;


text:
Q: I need plugin or method suggestion I am trying to help a local entrepreneurship society to add a feature to our website where people who want to build a team around a business idea could post their project description with contact details so that it will be shown on the website for visitors.
We have WordPress with Elementor, any idea or suggestion on how we could accomplish this

A: This his how I would do it.
Create a page with a form for the user to input their info, title, body text...
then with code make that form info create a post with a category only for this.
finnaly just show this on your page, or have a specific page to show this posts only.
Using only elementor, its possible to create the page form, and in the beginning add a custom shortcode that gets the form info and create the post.
To give here the shortcode code to insert into functions.php only having the form values.


text:
Q: Compiles using clang, but not g++5 - ld: symbol(s) not found for architecture x86_64 I have an OpenCV program that compiles using clang without and errors, I am looking to try and compile this program using g++5 however I am getting the following error:
ld: symbol(s) not found for architecture x86_64

The command I am using when trying to build the file is:
g++-5 -std=c++11 -pthread main.cpp -o testcomp `pkg-config --cflags --libs opencv`

Am I correct in assuming that the OpenCV libraries are 32 bit but g++5 is designed for 64 bit?
If I try to compile the code using the following command, the program builds successfully:
g++ -std=c++11 -pthread main.cpp -o testComp `pkg-config --cflags --libs opencv`

I am using OSX and have installed g++ through home-brew.
The full compilation error is below:
Undefined symbols for architecture x86_64:
  "cv::drawMatches(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> > const&, cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> > const&, std::vector<cv::DMatch, std::allocator<cv::DMatch> > const&, cv::Mat&, cv::Scalar_<double> const&, cv::Scalar_<double> const&, std::vector<char, std::allocator<char> > const&, int)", referenced from:
      processingThread(cv::Mat, int)  in ccw6qwZp.o
  "cv::FeatureDetector::create(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
      __static_initialization_and_destruction_0(int, int) in ccw6qwZp.o
  "cv::DescriptorExtractor::create(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
      __static_initialization_and_destruction_0(int, int) in ccw6qwZp.o
  "cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)", referenced from:
      _main in ccw6qwZp.o
  "cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)", referenced from:
      _main in ccw6qwZp.o
  "cv::FeatureDetector::detect(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> >&, cv::Mat const&) const", referenced from:
      preProcessing()     in ccw6qwZp.o
      processingThread(cv::Mat, int)  in ccw6qwZp.o
  "cv::DescriptorMatcher::match(cv::Mat const&, cv::Mat const&, std::vector<cv::DMatch, std::allocator<cv::DMatch> >&, cv::Mat const&) const", referenced from:
      processingThread(cv::Mat, int)  in ccw6qwZp.o
  "cv::DescriptorExtractor::compute(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> >&, cv::Mat&) const", referenced from:
      preProcessing()     in ccw6qwZp.o
      processingThread(cv::Mat, int)  in ccw6qwZp.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

Compiler output as per comment with -Wl,-v added:
collect2 version 5.2.0
/usr/bin/ld -dynamic -arch x86_64 -macosx_version_min 10.11.0 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk -weak_reference_mismatches non-weak -o testcomp -L/usr/local/lib -L/usr/local/Cellar/gcc5/5.2.0/lib/gcc/5/gcc/x86_64-apple-darwin15.0.0/5.2.0 -L/usr/local/Cellar/gcc5/5.2.0/lib/gcc/5/gcc/x86_64-apple-darwin15.0.0/5.2.0/../../.. -L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/lib -v /var/folders/nc/_drhkj6n3fnd1g3jmwq8mtm80000gn/T//ccfpdMCy.o -lopencv_calib3d -lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_gpu -lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_nonfree -lopencv_objdetect -lopencv_ocl -lopencv_photo -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_video -lopencv_videostab -lstdc++ -no_compact_unwind -lSystem -lgcc_ext.10.5 -lgcc -lSystem
@(#)PROGRAM:ld  PROJECT:ld64-253.3.3
configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7k armv7m armv7em
Library search paths:
    /usr/local/lib
    /usr/local/Cellar/gcc5/5.2.0/lib/gcc/5/gcc/x86_64-apple-darwin15.0.0/5.2.0
    /usr/local/Cellar/gcc5/5.2.0/lib/gcc/5
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/lib
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/lib
Framework search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/
Undefined symbols for architecture x86_64:
  "cv::drawMatches(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> > const&, cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> > const&, std::vector<cv::DMatch, std::allocator<cv::DMatch> > const&, cv::Mat&, cv::Scalar_<double> const&, cv::Scalar_<double> const&, std::vector<char, std::allocator<char> > const&, int)", referenced from:
      processingThread(cv::Mat, int)  in ccfpdMCy.o
  "cv::FeatureDetector::create(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
      __static_initialization_and_destruction_0(int, int) in ccfpdMCy.o
  "cv::DescriptorExtractor::create(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)", referenced from:
      __static_initialization_and_destruction_0(int, int) in ccfpdMCy.o
  "cv::imread(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)", referenced from:
      _main in ccfpdMCy.o
  "cv::imshow(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)", referenced from:
      _main in ccfpdMCy.o
  "cv::FeatureDetector::detect(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> >&, cv::Mat const&) const", referenced from:
      preProcessing()     in ccfpdMCy.o
      processingThread(cv::Mat, int)  in ccfpdMCy.o
  "cv::DescriptorMatcher::match(cv::Mat const&, cv::Mat const&, std::vector<cv::DMatch, std::allocator<cv::DMatch> >&, cv::Mat const&) const", referenced from:
      processingThread(cv::Mat, int)  in ccfpdMCy.o
  "cv::DescriptorExtractor::compute(cv::Mat const&, std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint> >&, cv::Mat&) const", referenced from:
      preProcessing()     in ccfpdMCy.o
      processingThread(cv::Mat, int)  in ccfpdMCy.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status


text:
Q: Laravel 4 : How to display SQL queries ran? In my app/config/app.php file, I have turned on 'debug'=>true.
I have tried
//run eloquent functions
$allMessages = Messages::with('User')->whereIn('conv_id',$conv_id)->orderBy('created_at','aadesc')->take(10);

$q= DB::getQueryLog();
dd($q);

but it returns an empty array. So I guess it is useless to do end($q) as suggested.
I have also tried the accepted answer to a question and added it to the end of my routes file but nothing happened. I'm still new to Laravel and need some guidance. Thank you!

A: A popular method is to monitor the Event for Eloquent, and output any queries run on the database as you are going along:
Event::listen('illuminate.query', function($query, $params, $time, $conn)
{
    dd(array($query, $params, $time, $conn));
});

$allMessages = Messages::with('User')->whereIn('conv_id',$conv_id)->orderBy('created_at','aadesc')->take(10);

That will output the query that is run.
Another option is to use a Laravel4 Debugger package, which automatically shows you the queries run: https://github.com/barryvdh/laravel-debugbar


text:
Q: problem generating random no in java i have written a code like this but it is giving exceptions.actually i want to generate a random value.save into the database and return the same to the user
import java.math.BigInteger;
import java.security.SecureRandom;

public static String recoverpassword(String uid,String ans) {
    try {
        verifyans.setString(1,uid);
        verifyans.setString(2,ans);
        ResultSet resultSet = verifyans.executeQuery();

        if (resultSet.next()) {
            SecureRandom random = new SecureRandom();
            String newpass = new BigInteger(130, random).toString(32);
            resetpass.setString(1,newpass);
            resetpass.setString(2,uid);
            resetpass.executeUpdate();
            return newpass;
        } else {
            return "xxx";
        }

    } catch(Exception e) {
        System.out.println("exception" +e);
        e.printStackTrace();
        return "xxx";
    }
}

i m getting null pointer exceptions like:
com.ibm.lims.Users@1d193c9]
exceptionjava.lang.NullPointerException
java.lang.NullPointerException
    at org.tranql.connector.jdbc.ConnectionHandle.connectionError(ConnectionHandle.java:103)
    at org.tranql.connector.jdbc.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:105)
    at com.ibm.lims.LimsHandler.recoverpassword(LimsHandler.java:940)
    at org.apache.jsp.recoverpasswordresult_jsp._jspService(recoverpasswordresult_jsp.java:78)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.geronimo.tomcat.valve.DefaultSubjectValve.invoke(DefaultSubjectValve.java:56)
    at org.apache.geronimo.tomcat.GeronimoStandardContext$SystemMethodValve.invoke(GeronimoStandardContext.java:406)
    at org.apache.geronimo.tomcat.valve.GeronimoBeforeAfterValve.invoke(GeronimoBeforeAfterValve.java:47)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:567)
    at org.apache.geronimo.tomcat.valve.ThreadCleanerValve.invoke(ThreadCleanerValve.java:40)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Unknown Source)

hey i tested the code removing those securerandom class call.i just passed a string value in double quotes like "sample" and it worked. means the problem is with the securerandom class.i think the value is going as an integer in a string value field so database server is sending exception. plz give me some code to generate random string alternatively –

A: There are several problems playing a role here.
First the root cause of the NPE:
java.lang.NullPointerException
    at org.tranql.connector.jdbc.ConnectionHandle.connectionError(ConnectionHandle.java:103)

This is clearly a bug in the TranQL JDBC driver. There was some unexpected null pointer during the ConnectionHandle#connectionError() method so that it was unable to handle the actual connection error. To fix this particular problem (so that you don't get a NPE, but a more clear and driver-specific SQLException), either upgrade the driver or replace it by a more decent one (I've never heard of TranQL before).
As to the real cause of the whole problem; judging from the stacktrace it look like that there's no means of an active connection. Judging from the non-threadsafe code it look like that the preparedStatement was already used before and has somehow implicitly been closed / detached from the connection.
At least it clearly boils down to the non-threadsafe and non-resourceleak-safe JDBC code you have there. The normal JDBC idiom is that you should always acquire and close the Connection, PreparedStatement and ResultSet in the shortest possible scope. Thus, already inside the very same (non-static!) method block. The statement and resultset should never be shared among threads. The connection can be, but you shouldn't take it in your own hands. Use a decent connection pool API for this, e.g. C3P0.
Here's an example according the ideal JDBC idiom:
public String recoverPassword(Long userId, String answer) throws SQLException {
    Connection connection = null;
    PreparedStatement verifyAnswer = null;
    ResultSet resultSet = null;
    String newPassword = null;
    PreparedStatement resetPassword = null;

    try {
        connection = database.getConnection();
        verifyAnswer = connection.prepareStatement(SQL_VERIFY_ANSWER);
        verifyAnswer.setLong(1, userId);
        verifyAnswer.setString(2, answer);
        resultSet = statement.executeQuery();

        if (resultSet.next()) {
            SecureRandom random = new SecureRandom();
            newPassword = new BigInteger(130, random).toString(32);
            resetPassword = connection.prepareStatement(SQL_RESET_PASSWORD);
            resetPassword.setString(1, newPassword);
            resetPassword.setLong(2, userId);
            resetPassword.executeUpdate();
        }
    } finally {
        // Always free resources in reversed order.
        if (resetPassword != null) try { resetPassword.close(); } catch (SQLException logOrIgnore) {}
        if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
        if (verifyAnswer != null) try { verifyAnswer.close(); } catch (SQLException logOrIgnore) {}
        if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
    }

    return newPassword;
}

Note that I hinted the userId to be a Long. You really don't want to have String ID's in both your code and datamodel. You can find more information, hints and other examples about writing solid JDBC code here.
That said, the following part of the stacktrace
at com.ibm.lims.LimsHandler.recoverpassword(LimsHandler.java:940)
at org.apache.jsp.recoverpasswordresult_jsp._jspService(recoverpasswordresult_jsp.java:78)

implies that you're writing raw Java code in a JSP file using the old-fashioned scriptlets. To save future maintenance and debugging problems, I would strongly recommend you not to do so, but just use a Servlet class for that.

A: Have you tried stepping through this with a debugger?
From the code posted it looks like maybe uid is being passed in as null at the top of the method.
You also shouldn't store passwords as plain text in the database, you should use a salted one-way hash of the password instead.

A: The problem you have is not related to random gen of number. You might take a look at you DB connection parameters, at the sql request you are trying to execute, ... But please, be more specific "I'm getting NPE" is not a question :)


text:
Q: C++/CLI Dictionary of Dictionaries Is there a way to create a Dictionary of Dictionaries in C++ CLI? I was previously using a Dictionary of String,ArrayList pairs and found it useful to have my ArrayList converted to a Dictionary of String,CustomValueStruct pairs instead to make use of the key matching.
The code I had for the Dictionary of String,ArrayList pairs:
Dictionary<String^, ArrayList^> myDictionary = gcnew Dictionary<String^, ArrayList^>();

How can I convert this to use a Dictionary of Dictionaries?
The code I tried using, which doesn't compile is:
Dictionary<String^, Dictionary<String^, CustomValueStruct>> myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomValueStruct>>();

Where CustomValueStruct is just a custom struct in my code, which previously lived in the ArrayList.
The result of the attempted line is:
error C3225: generic type argument for 'TValue' cannot be 'System::Collections::Generic::Dictionary<TKey,TValue>', it must be a value type or a handle to a reference type

A: As the compiler said, you forgot a ^:
auto myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomValueStruct>^>();

Note that you need create a Dictionary<String^, CustomValueStruct> when adding items to myDictionary:
myDictionary.Add("Key", gcnew Dictionary<String^, CustomValueStruct>());

Finally, be sure you really want CustomValueStruct to be a value type; you're usually better off writing
ref class CustomRefClass { /* ... */ };

which in turn requires a ^ for the nested Dictionary:
 auto myDictionary = gcnew Dictionary<String^, Dictionary<String^, CustomRefClass^>^>();


text:
Q: Can't install rospy I need to use rospy for my app, and when i try to install it via pip3 install rospy or pip3 install python-rospy it results an error: ERROR: Could not find a version that satisfies the requirement python-rospy (from versions: none) ERROR: No matching distribution found for python-rospy
I have no idea how to use it and where to download it
Thanks for any responces!

A: There could be multiple reasons behind these errors. I think you should first check if you have ROS1 installed on your system. Since you're going to use Python3, you'll have to install ROS1 Noetic. You can follow the instructions mentioned on http://wiki.ros.org/noetic/Installation/Ubuntu
If you already have ROS1 Noetic on your system, you should check if you've source ROS1 in your .bashrc. If source /opt/ros/neotic/setup.bash is already there, then something went wrong during the installation. You should install ROS again.
Hope this helps.


text:
Q: Can I use the same Vector2 struct across multiple librarys that implement their own Vector2 structs? I'm making a 2D game that will use one library for rendering graphics to the screen, and another for physics. The problem is that both libraries implement their own Vector2 struct. This means I have to convert between the two very often and it can be confusing which Vector2 I'm referring to because they are both called "Vector2". Ideally, I would like to use the same Vector2 class across both libraries. How can I achieve this with C#?

A: You can write your own MyVector2 struct that supports implicit conversion to the other Vector2 types.
struct MyVector2
{
    public float x;
    public float y;

    public static implicit operator GraphicsLib.Vector2(MyVector2 v)
    { return new GraphicsLib.Vector2(v.x,v.y); }

    public static implicit operator PhysicsLib.Vector2(MyVector2 v)
    { return new PhysicsLib.Vector2(v.x,v.y); }

    ...
}

Then instances of MyVector2 should be compatible with any function expecting a Vector2 from either library.
MyVector2 v = new MyVector2(5f, 20f);
GraphicsLib.DoSomethingWithVector(v);
PhysicsLib.DoSomethingWithVector(v);

The other answer that mentions using System.Runtime.CompilerServices.Unsafe.As<MyVector2, PhysicsLib.Vector2>(ref v); might also be possible to use inside the conversion operators if optimization is crucial.

A: If they have the same internal layout, you can use System.Runtime.CompilerServices.Unsafe to convert between them. You can also create extension methods that for each kind. E.g.  public static Lib1.Vector2 ToLib1(this Lib2.Vector2 v) = > System.Runtime.CompilerServices.Unsafe.As<Lib2.Vector2, Lib1.Vector2>(ref v);
Personally, I use MonoGame but use System.Numerics.Vector2 everywhere I can for SIMD support (it might be an unnecessary micro-optimization but I sleep better knowing that I use SIMD instructions when I can).


text:
Q: forwarding a file write with ShellExecute in c++ I'm basically trying to launch a command prompt from my program. that command terminal is supposed to do whatever command it gets from my main program (I'm getting input with getline) and THEN output it to a file (out.txt). then I want to display the contents of the file in the main program's console.
the problem is that the command is not exactly doing anything to the file, although the command I forward seems to be the right one (for example, "dir > out.txt"). I thought that maybe it doesn't have permissions, but I opened a non-elevated command prompt in the source folder and it can easily do whatever I tell it to.
here's the source code, it's visual c++ under windows. I'm guessing I did something wrong with ShellExecute. thanks in advance.
#include <iostream>
#include <conio.h>
#include <Windows.h>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    LPCSTR s;
    string command;
    string line;
    ifstream fd("out.txt");

    cout << "enter a command:\n";
    getline(cin, command);

    command += " > out.txt";

    cout << "command: " << command << endl;

    s = (LPCSTR)command.c_str();

    ShellExecute (NULL, "open", "cmd", s, " C:\\ ", SW_SHOW);

    cout << "s: " << s << endl;

    if(fd.is_open())
    {
        while(getline(fd, line))
            cout << line << endl;
        fd.close();
    }

    else cout << "unable to open file lel" << endl;

    _getch();
    return 0;
}


text:
Q: Can't test app on iPhone after updating iPhone I ran it fine, did all the certification hassle and my sister updates the iPhone and next day I can't test anything, Xcode doesn't simply recognize the damn iPhone. Please help. There is literally nothing I have found that solves this problem..
I should say that it worked fine a day ago. I'm so damn angry and frustrated I can't type..
Apple does a really really poor job of being clear what to do.
EDIT: I also see this "You don't have permission to save the file "iOS DeviceSupport" in the folder "Xcode"."

A: What version of Xcode do you have and what iOS-version does the test-device have?
To test applications with Xcode 4.2.1, the device has to be of iOS 5.0.1 or down. If you updated to the iOS 5.1 beta, you will need to download Xcode 4.3 beta as well, as Xcode 4.2.1 does not have the required DeviceSupport-files for the beta.
EDIT:
Since you have Xcode 4.2, you will need to update to 4.2.1 to be able to test your applications on an iOS 5.0.1-device.

A: You'll need Xcode 4.2.1 if your iPhone is version 5.0.1.

A: I had the same problem,
Here is my solution!
First Update both Xcode and phone with the latest software.
Then go to the organizer and enable iPhone for development.
Done ..


text:
Q: How do I run a program with a user created package in java using command prompt Java program
It contains a user created package and has four class including one main class
How can I run this code in command prompt.

A: You need to create a executable jar file.
Create a top empty directory, create a folder inside with the name of your package, copy the compiled classes inside.From top directory execute ( With proper class names)
    jar cvfe myJarFile.jar package.MyMainClass package/*.class

And to run the jar file
java -jar myJarFile.jar

A: At the root directory of the project, you can do
javac package/*.java

(you may replace / with \ on Windows)
and then
java package.MainClass


text:
Q: python 3 List object assignment to dictionary error i've got the following issue:
Python assigning empty lists to my dictionary even the list contains elements. The list is stored in a variable, but if i provide the values manually, it assigns given values to the dictionary properly
i've tested to provides the values manually (worked), create a new dictionary and assigning the list from variable (not worked)
valueable_data = list()
output_data3 = dict()
for k,v in output_data.items():
    valueable_data.clear()  #emptying the list

    for list in input_data[1:]:
        for element in list:
            if list.index(element) == int(v) and element != '':
                print(element)
                valueable_data.append(element.replace("'",""))
                #print(valeuable_data)
    if len(valueable_data) != 0:
        print(len(valueable_data))  #19 elements
        print(type(valueable_data))  #<class> 'list'
        output_data3[k] = valueable_data
        #valeuable_data.clear()

for k,v in output_data3.items():
    print(len(v))  #result []

The desired output would be something like this:
letters ('a','b','c')
numbers ('1','2','3')
if i do the determination this way:
output_data3[k] = ('a','b','c')

the result is (as desired):
k ('a','b','c')

thank you for helping me out!


text:
Q: Line breaking issue to move csv file in Linux [I have moved the csv file into Linux system with binary mode. File content of one field is spitted into multiple lines its comment sections,I need to remove the new line , keep the same format, Please help on shell command or perl command
here is the example for three records, Actual look like]
Original content of the file
[After moved into linux, comments field is splitted into 4 lines , i want to keep the comment field in the same format but dont want the new line characters
"First line
Second line
Third line
all lines format should not change"
]2

A: As I said in my comment above, the specs are not clear but I suspect this is what you are trying to do.  Here's a way to load data into Oracle using sqlldr where a field is surrounded by double-quotes and contains linefeeds where the end of the record is a combination carriage return/linefeed. This can happen when the data comes from an Excel spreadsheet saved as a .csv for example, where the cell contains the linefeeds.
Here's the data file as exported by Excel as a .csv and viewed in gvim, with the option turned on to show control characters.  You can see the linefeeds as the '$' character and the carriage returns as the '^M' character:
100,test1,"1line1$
1line2$
1line3"^M$
200,test2,"2line1$
2line2$
2line3"^M$

Construct the control file like this using the "str" clause on the infile option line to set the end of record character.  It tells sqlldr that hex 0D (carriage return, or ^M) is the record separator (this way it will ignore the linefeeds inside the double-quotes):
LOAD DATA
infile "test.dat" "str x'0D'"
TRUNCATE
INTO TABLE test
replace
fields terminated by ","
optionally enclosed by '"'
(
cola char,
colb char,
colc char
)

After loading, the data looks like this with linefeeds in the comment field (I called it colc) preserved:
SQL> select *
  2  from test;

COLA                 COLB                 COLC
-------------------- -------------------- --------------------
100                  test1                1line1
                                          1line2
                                          1line3

200                  test2                2line1
                                          2line2
                                          2line3

SQL>


text:
Q: False discovery rate calculation in target-decoy matching context A common strategy in mass spectrometry of biological molecules is to upload observed spectra to a server so that they can be matched to a LARGE database of theoretical spectra of known molecules (a.k.a. target database). In order to control for false positives, a decoy database consisting of incorrect/irrelevant spectra is used.
I have been reading more into this subject and have come up some questions regarding the calculation of the FDR measure from this target-decoy strategy. The basic idea of the FDR value is very intuitive:
$FDR = \frac{FP}{FP + TP}$
where FP and TP stands for false and true positives respectively. This makes perfect sense to me; if I'm trying to guess some peoples' names out of a phone book, and get 8 right and 2 wrong, I would have 2 false out of 10 total guesses, and thus my false discovery rate would be 20%.
However reading this tutorial on how this is done in large scale on the servers, I got introduced to two different calculations, depending on whether or not the target and decoy databases are concatenated (page 2).
I don't think that this is a typo as I found other occurrences * of the mysterious factor 2 in front of FP in scientific literature. However the motivation behind this is never explained (at least I couldn't find it).
I would appreciate some insight on where this doubling comes from. Likewise I wonder whether or not FDR calculation this way assumes that the error rate for each spectra match is the same for the target database and decoy database (i.e. assuming that getting 25 decoy hits implies 25 target hits are also false positives). It's not really clear for me why the error rate has to be the same for the two databases. Any comments on this subject is also appreciated.
* one such reference is Elias et al Nature Methods - 2, 667 - 675 (2005)

A: I believe you multiply by 2 because you need to control for your database being twice as large. There are other ways to do this calculation such as
decoy spectra identified /  target spectra identified
The use of the term FDR for this calculation is totally confusing and is why people have started calling it target/decoy rate in the last year or so. It's also doubly confusing as people often fail to specify if they are using a spectra target/decoy or a peptide target/decoy...and there is no way to consistently calculate a protein target/decoy as different programs will weigh peptide --> protein evidence differently...It's a mess...Having said that I will always make this calculation just to double check I or the software has not done something stupid. For that it is very useful.


text:
Q: Azure devops - Support if building iOS App with extensions My iOE source code hosted in VSTS using TFVC. I am evaluating automated build and release/publish to appstore. My iOS app has extensions.
I tried hosted macOS agent, but it doesn't support building of extensions.
I tried APP Center, but it doesn't support TFVC yet.
Any other options?


text:
Q: htmlentities with exceptions I have some set of possible tags for example "<main>", "<text>", "<tag>". Rest of characters I would like to treat with htmlentities (htmlspecialchars)
<main>
<text>
<tag> <>  X&Y <  <falsetag> <tag attr="123" /> </tag>
</text>
</main>

The result should be
<main>
<text>
<tag> <>  X&Y <  <falsetag> <tag attr="123" /> </tag>
</text>
</main>

What's the best way to do it.

A: You can run htmlentities on the text then use a regular expression to replace the allowed tags <>
Example...
$str = '<main>
<text>
<tag> <>  X&Y <  <falsetag> <tag attr="123" /> </tag>
</text>
</main>
';

$allowed_tags = array( 'tag', 'text', 'main' );

$escaped_str = htmlentities( $str );

$replace_what = array_map( function($v){ return "~<(/?)$v(.*?)>~"; }, $allowed_tags );
$replace_with = array_map( function($v){ return "<$1$v$2>"; }, $allowed_tags );

echo preg_replace( $replace_what, $replace_with, $escaped_str );

A: The only solution I see is to load it into an XML parser and then recursively build the output string yourself, but this will take a little work.
Note: A regular expression solution (like what Galen proposed) will not work in all cases because attribute values may contain >.

A: I have a simple Solution that worked good for me:
$text = htmlentities($text, ENT_QUOTES, "UTF-8");
$text = htmlspecialchars_decode($text);
$text = strip_tags($text, "<p><b><h2>");


text:
Q: PHP Output MS SQL to a downloadable CSV or Excel file I'm trying to output data returned by an MS SQL query to an Excel or CSV file with PHP.
I've used the script in this answer and can output the file OK. Without the header lines (at the bottom of my code) it saves in my server's folder structure rather than outputs as a download to the browser.
If I add the header lines, it ouputs to a CSV file but writes the page's HTML to the file rather than the extract from the database! Am I missing a setting somewhere? I tried running the code on a page with no HTML in it (PHP and SQL code only), but it still happens.
        // Give the file a suitable name:
            $FileName= $PartNumber.".csv";
            $fp = fopen($FileName, 'w');
        // Connect to MS SQL server; the actual database is chosen in the form
        // ConnSQL defined in inc/dbconn/config.php
            ConnSQL($idDatabase);

        // the query is a biggie; here it is:
            require 'inc_sql.php';

        // run it through the SQL server
            $rstBOM = sqlsrv_query($GLOBALS['ConnSQL'], $sqlBOM);

        while ($export= sqlsrv_fetch_array($rstBOM, SQLSRV_FETCH_ASSOC)) {
            if (!isset($headings))
                {
                    $headings = array_keys($export);
                    fputcsv($fp, $headings, ',', '"');
                }
                fputcsv($fp, $export, ',', '"');
            }

        // force download csv - exports HTML to CSV!
            header("Content-type: application/force-download");
            header('Content-Disposition: inline; filename="'.$FileName.'"');
            header("Content-Transfer-Encoding: Binary");
            header("Content-length: ". filesize($FileName));
            header('Content-Type: application/excel');
            header('Content-Disposition: attachment; filename="'.$FileName.'"');

            fclose($fp);

Any ideas where I'm going wrong please?

A: You need to output your csv file to the browser simply by putting
readfile($FileName);

At the end of your code after the fclose($fp); function.
Otherwise, browser receives the headers for files, but no content in sent from your PHP code.
You could also generate your csv file on the fly and just echo $csvFileContents; instead. This would prevent server from creating and writing data to file, which could lead to security breaches.
Good luck!


text:
Q: android connect to local host from connectify me to consure a web service First of all I will tell you what can I do:

*

*I can connect my real device to my servlets on my website using my computer IP

*I can connect my emulator to my servlets on my website using 10.0.2.2 IP

*I can connect my emulator to my web services using 10.0.2.2 IP
My problem.
I can't connect my real device to the web services;
I tried this (It works for emulator);
public class Client {

    private String server;

    public Client(String server) {
        this.server = server;
    }

    private String getBase() {
        return server;
    }

    public String getBaseURI(String str) {
        String result = "";
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpGet getRequest = new HttpGet(getBase() + str);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }

    public String getBaseURIText(String str) {
        String result = "";
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpGet getRequest = new HttpGet(getBase() + str);
            getRequest.addHeader("accept", "text/plain");
            HttpResponse response = httpClient.execute(getRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }

 private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
            StringBuilder result = new StringBuilder();
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
            String output;
            while ((output = br.readLine()) != null)
                result.append(output);

            return result;
      }
}

Then I call that client like this:
Client client = new Client("http://46.57.164.64:8080/test2/eattel/");
            client.getBaseURI("image/image");

This totally works for emulators. but now for my real device :(
I connect my real device to my computer using cable .
my computer and my device are connected to connectify-me wireless network.
please help
I am sure it is something about IP

A: I think what went wrong here is you are connecting your computer and your real device through a cable. Your real device should be connected to wireless network throngh WiFi. Your computer also should be connected the Wireless Network either via a cable or WiFi. Then, once you type your computer IP address on the Internet Browser of Real Device, you should be able to see the home page of the server that you are running on your computer. If that is coming your application can communicate with your web services in the computer. If that is not coming that means your IP Addresses are not set properly Wireless Network. You might have to restart the Wireless Network and try out again.

A: Have you try to discover your computer ip address for connectify connection?
If you are using windows OS, Go to command prompt, type ipconfig and search the ipv4 address under Wireless LAN Adapter Local Area Connection. It usually start with 192.168.xxx.xxx if you use connectify


text:
Q: How to send mail through a contact form using Recaptcha, AJAX and Laravel I am trying to use Recaptcha for my form to prevent bots from spamming my email account. I am using AJAX so the form submits without reloading the page and I am using PHP Laravel for my backend. The form worked fine before trying to implement ReCaptcha to my form. However, when trying to send the form, I receive the error messaging "Please check the ReCaptcha box." when I have already clicked the ReCaptcha box.
My HTML Form code:
<form class="wpcf7-form" id="form-id">
    {{ csrf_field() }}

            <input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" placeholder="First Name" required />

            <input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Last Name" required />

            <input type="email" name="email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email" aria-required="true" aria-invalid="false" placeholder="E-mail Address" required/>

            <input type="text" name="phone" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false" placeholder="Phone Number" required />

            <textarea name="message" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea" aria-invalid="false" placeholder="Your Message" required ></textarea>

            <button type="submit" class="button button-simple btn-submit mt-30">SEND</button>

</form>

Here is the AJAX code:
$("form.wpcf7-form").submit(function(e){
    e.preventDefault();
    var token = $("input[name=_token]").val(); // The CSRF token
    var first_name = $("input[name=first-name]").val();
    var last_name = $("input[name=last-name]").val();
    var email = $("input[name=email]").val();
    var phone = $("input[name=phone]").val();
    var bodyMessage = $("textarea[name=message]").val();
    var recaptcha_token = $("#g-recaptcha-response").val();

    $.ajax({
       type:'POST',
       url:'/contact',
       dataType: 'json',
       data:{_token: token, first_name:first_name, last_name:last_name, email:email, phone:phone, bodyMessage:bodyMessage, recaptcha_token:recaptcha_token},
       success:function(data){
           $(".email-success-messge").append(data.success).fadeIn(999);
       }
    });
});

My ContactController file:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Mail;
use Session;

class ContactController extends Controller
{
    public function postContact(Request $request){
        $this->validate($request, ['email' => 'required|email'] );

        $data = array(
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'bodyMessage' => $request->bodyMessage,
            'recaptcha_token' => $request->recaptcha_token
        );

        if ($data['recaptcha_token']){
            Mail::send('emails.contact', $data, function($message) use ($data){
                $message->from($data['email']);
                $message->to('jafar@**********.com');
                $message->subject('Contact Details');
            });
            return response()->json(['success' => 'Thank you for getting in touch!'], 200);
        }else{
            return response()->json(['success' => 'Please check the ReCaptcha box.'], 200);
        }
    }
}


text:
Q: file up and download openapi generation I am trying to implement a file upload/download against a springboot server. Implementing manually is already working, but I'd like to generate both server and clients with Openapi.
This does not work and I do not see why. I have uploaded both example to GitHub, so you can see what I have done.
Could you please provide feedback how I generate it the right way or what I do wrong?
The link: https://github.com/moley/swaggerUpAndDownload
In upload I get:
{"timestamp":"2020-04-01T08:53:42.181+0000","status":400,"error":"Bad Request","message":"Required request part 'file' is not present","path":"/documentstore/upload"}-400

Would be very nice to get a hint to the right direction.
Cheers
Markus


text:
Q: Covariance between coordinate x and distance in a circle. Let $\Omega$ be a circle of radius $r$ and let $Z$ be the random variable that measures the distance from the center of the circle to a point. Let $X$ be the random variable that given $(x,y)$ associates the value of $x$. Calculate $cov(X,Z)$.
I'm having trouble thinking in a way to relate $X$ and $Z$ in order to find $E[XY]$. What limits should I consider when integrating? What I have done so far is define $p_{X,Y}(x,y)$ as:
$$
p_{X,Y}(x,y) = \frac{1}{\pi r^2},\;\text{for } x^2+y^2 ≤ r^2
$$
and
$$
p_{X,Y}(x,y) = 0\;\text{otherwise}
$$
Because I need to find $E[X]$, $E[Z]$ and $E[XZ]$ I defined first $p_{Z}$ as:
$$
p_{Z}(t) = \frac{2x}{r^2},\;\text{for } 0<t≤r
$$
Which resulted in: $E[Z]=\frac{2}{3}r$.
Then with $p_{X,Y}$ I integrated with the limits where $x$ is inside the circle to find $p_{X}$ as follows:
$$
p_X(x) = \int_{-\sqrt{r^2-x^2}}^{\sqrt{r^2-x^2}}p_{X,Y}dy = \int_{-\sqrt{r^2-x^2}}^{\sqrt{r^2-x^2}}\frac{1}{\pi r^2}dy = \frac{1}{\pi r^2}\int_{-\sqrt{r^2-x^2}}^{\sqrt{r^2-x^2}}dy = \frac{1}{\pi r^2}\left(\sqrt{r^2-x^2} + \sqrt{r^2-x^2}\right)= \frac{2}{\pi r^2}\sqrt{r^2-x^2}
$$
This left me with:
$$
E[X] = \int_{-r}^{r}xp_{X}(x)dx = \int_{-r}^{r}x\cdot\frac{2}{\pi r^2}\sqrt{r^2-x^2}dx = 0
$$
My main problem comes when finding $E[XZ]$. How should I define $p_{X,Z}$? I think I should be doing the double integral of $p_{X,Z}$, but how? I guess it is with establishing it as follows:
$$
\int_{-r}^{r}\int_{\sqrt{r^2-x^2}}^{\sqrt{r^2-x^2}}xtp_{X,Z}dxdt
$$
I don't know if that's the way to go, because I've seen the limits of $p_{Z}$ defined from $0$ to $r$ instead of $-r$ to $r$. Any help in defining $p_{X,Z}$, the limits of these integrals or in telling me what should I do is appreciated.

A: Let $(Z,\Phi)$ be the polar analogous of $(X,Y)$. Then $\Phi\sim U(0,2\pi)$, $Z\sim \dfrac{2z}{R^2}$, and $\Phi \perp\!\!\!\perp Z$, so
$$E\{XZ\} = E\{Z^2\cos(\Phi)\} = E\{Z^2\}E\{\cos(\Phi)\} = 0$$
because $E\{\cos(\Phi)\}=0$.
Also $E\{X\}=0$, so $cov(X,Z)=0$

A: Here is a nicely written solution for your own reference.
Let $\Sigma$ be a disc of radius $R$ centered about the origin, and suppose $(X,Y)\sim \mathcal{U}(\Sigma)$. The density of $(X,Y)$, namely $f_{XY}$, has formula $f_{XY}(x,y)=\frac{1}{\pi R^2}$ for $(x,y)\in \Sigma$ and $f_{XY}(x,y)=0$ elsewhere. You're trying to compute $$\text{cov}(X,Z)=\mathbb{E}\Big(X\sqrt{X^2+Y^2}\Big)-\mathbb{E}(X)\mathbb{E}\Big(\sqrt{X^2+Y^2}\Big)$$ From the law of the unconscious statistician, $$\mathbb{E}\Big(X\sqrt{X^2+Y^2}\Big)=\int_{-R}^R \int _{-\sqrt{R^2-x^2}}^{\sqrt{R^2-x^2}}x\sqrt{x^2+y^2}f_{XY}(x,y)dydx=0$$ $$\mathbb{E}\big(X\big)=\int_{-R}^R \int _{-\sqrt{R^2-x^2}}^{\sqrt{R^2-x^2}}xf_{XY}(x,y)dydx=0$$ $$\mathbb{E}\Big(\sqrt{X^2+Y^2}\Big)=\int_{-R}^R \int _{-\sqrt{R^2-x^2}}^{\sqrt{R^2-x^2}}\sqrt{x^2+y^2}f_{XY}(x,y)dydx=\frac{2R}{3}$$ Putting this all together we get $$\text{cov}(X,Z)=0$$


text:
Q: How to get rid of column border of gridview using CSS I am trying to manually style a gridview in ASP.NET to make it look like one of the default gridview styles. the default style is like this -

I have come pretty close. after applying my own style to a barebone gridview control, it look like this -

But I can't seem to remove the white borders in the header section of the Gridview.
My SCSS looks like this -
table{
    &.table-grid{
        color:Black;
        background-color:White;
        border-width: 1px;
        border-style:None;
        border-spacing: 0px;
        font-size:10pt;
        width:100%;
        border-collapse:collapse;
        margin-left:auto;
        margin-right: auto;
        td {
            border: none;
            border-top: 1px solid $table-bg-color;
        }
        tr {
            border-collapse:collapse;
            &:first-child{
                color:White;
                background-color:$table-bg-color;
                font-weight:bold;
            }
            th{
                border-collapse:collapse;
            }
        }
    }
}

and my gridview attributes are -
<asp:GridView ID="gv" runat="server" CssClass="table-grid" EnableViewState="false" cellspacing="0" cellpadding="4" border="0" AutoGenerateColumns="false">

can anyone tell me how to get rid of these white borders?
here's a JsFiddle Demo

A: Just to expand slightly on the previous answer:
th{
border-collapse:collapse;
border-width: 0;
text-align: left;
}

To get the column headings to line up nicely too :)

A: try

th{
                border-collapse:collapse;
                border-width: 0;
            }


text:
Q: Could there be more than one correct answer for the indefinite integral $\int\tan x\,dx$? I solved this integral by multiplying the numerator and denominator by $\sec x$ in order to get: $$\int\frac {\tan x\sec x}{\sec x} \,dx$$
This would be in the form $\int \frac {du}{u} $ , out of which I should be able to get:$$\ln \left | \sec x\right |+ C$$ However, the answer my text later provides is: $$ -\ln \left |\cos x \right | +C$$
Can both of these be correct? If so, how are these answers equal to one another?
Thanks

A: They are indeed the same. As the comment section provides, $\sec(x)=\dfrac{1}{\cos(x)}$
What this means is that
$$\ln|\sec(x)|=\ln|\dfrac{1}{\cos(x)}|=\ln|1|-\ln|\cos(x)|=0-\ln|\cos(x)|=-\ln|\cos(x)|$$
I used the rule that $\ln(\dfrac{a}{b})=\ln(a)-\ln(b)$

Also generally speaking, an indefinite integral is a family of functions. Notice that you can also add constants to your indefinite integral and it is still the same. For example the answer could have also been $1-\ln|\cos(x)|$, since the constant goes away when you take the derivative of it.

A: They are the same as shown by @KSplitX and the comment, but I think it's worth knowing how your text is likely to have proceeded to get their answer. Using the standard log integral
$$
\int \frac{f'(x)}{f(x)} \, dx = \log |f(x)|+C
$$
Your integral is
$$
\int \frac{\sin x}{\cos x} \, dx = -\int \frac{-\sin x}{\cos x} \, dx
=-\log|\cos x|+C
$$


text:
Q: Fabricjs detect hovered control box I have a fabricjs canvas and onto that i am adding image. when we click the image the image is in selected mode.
is there a way to know if the mouse if over the grapples(the square boxed around the image) but not the one used to rotate?
and if it is can i fire a javascript command from there?

A: the rotation square is called 'mtr' inside fabricjs.
You can hook a 'mousedown' or 'mouseover' event to the object in this way:
object.on('mouseover' myfunction.bind(object));
the function you pass will receive an object parameter that we will call opt, just for example.
function(opt) {
  var mouseevent = opt.e;
  if (this.__corner === 'mtr') {
    callMyOtherFunction(mouseevent);
  }
}

this will not stop the rotation handling during mousemove or firing modified on mouseup
this.__corner referes to the object (this) and the last findTargetCorner result. Is not documented and is not a public feature, is mostly used for internal fabric logic, but is there and you can use it.
You should propose on the fabric issue tracker to make it an official feature, removing the double dash in front and documenting it in the docs.


text:
Q: fancybox v3 beta not running on ajax loaded content Niche question, hoping some other people have been using fancybox too.
On my site, I have subpages that are loaded using the .load() jquery function.  Thus, I need to put almost all my scripts in the primary index.html file.
Using this method, I had the fancybox v2 running fine - with the script:
$(document).ready(function() {
  $('.fancybox').fancybox();
});

on the main index page, rather than on the photo page.
I tried to update to fancybox v3 to use the touch controls for mobile, but now this same method isn't working.
Has anyone dealt with this problem, or have a solution?  Applying scripts to .load(ed) content can be tricky, but I thought I had this figured out.
Recommendations for other good mobile/touch enabled lightboxes are also cool.


text:
Q: Spring Roo No add-ons Known I attempt the following command in the roo shell
database reverse engineer --package ~.domain --schema PUBLIC
and yield the following...
Spring Roo automatic add-on discovery service currently unavailable
When I simply attempt to do an addon search I get the following
No add-ons known. Are you online? Try the 'download status' command
The download status is fine though. There is potentially an issue with being behind a proxy but I've already fixed the settigs.xml and the proxy settings, unless I am missing anything. Any help would be appreciated.

A: If this is not related to proxy then probably it is related with a current bug in RooBot Add on registration. See the Jira issues - ROO-3184, ROO-3191. It is not fixed yet.

A: I had a similar experience.  Whenever I typed addon list, roo would doubt I was online.  When I typed proxy configuration, roo would tell me I had none configured.
To get roo to use your proxy setup, create a ROO_OPTS environment variable and specify -Djava.net.useSystemProxies=true
Restart roo and it will use your proxy

A: Tried osgi start command. Download driver and issue ROO command:
osgi start --url file:C:\dev\h2DataBase\h2\bin\h2-1.3.168.jar


text:
Q: Magento2: How to correctly render a json in grid field I created a field in my order grid table, I have an observer set up that will fill the field with a JSON string of the ordered items. I want to have this field rendered to HTML so the ordered items will show on order grid. However, I can not find any information on how to properly render a JSON in UI grid system of Magento 2. I am planning to share it in a public repository so I would like to have the code as clean as possible. I have the following code right now:
namespace Qxs\OrderLinesGrid\Ui\Component;

class Grid extends \Magento\Ui\Component\Listing\Columns\Column {

  /**
  * Logger Interface
  *
  * @var \Psr\Log\LoggerInterface
  */
  protected $logger;

  public function __construct(
      \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
      \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
      \Psr\Log\LoggerInterface $logger,
      array $components = [],
      array $data = []
  ){
      $this->logger = $logger;
      parent::__construct($context, $uiComponentFactory, $components, $data);
  }

  public function prepareDataSource(array $dataSource) {
    if (isset($dataSource['data']['items'])) {
      foreach ($dataSource['data']['items'] as & $item) {
        if (!empty($item['order_lines'])) {
          $json = $item['order_lines'];
          $this->logger->debug("JSON Data".$json);
        }
      }
    }
    return $dataSource;
  }
}

However I cannot edit the JSON it returns an empty string, the JSON is showed in the grid but not on var_dump($json). Can anybody guide me in the right direction?

A: Try below code. You have to decode your json data to see it. Check your log file. Please make sure that you are getting correct data in function.
Please check $dataSource array.
<?php namespace Qxs\OrderLinesGrid\Ui\Component;

class Grid extends \Magento\Ui\Component\Listing\Columns\Column
{

    /**
    * Logger Interface
    *
    * @var \Psr\Log\LoggerInterface
    */
    protected $logger;

    public function __construct(
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        \Psr\Log\LoggerInterface $logger,
        array $components = [],
        array $data = []
    ){
        $this->logger = $logger;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource) {
        if (isset($dataSource['data']['items'])) {
            $this->logger->debug("JSON Data".json_decode($dataSource['data']['items']));
            foreach ($dataSource['data']['items'] as & $item) {
                $json = $item['order_lines'];
                //var_dump($json);
            }
        }
    return $dataSource;
    }
}


text:
Q: Java OpenGL blending image colors I'm trying to blend 2 images together in the following way:
Image 1 should be drawn as the base image. Image 2 should be drawn overtop of image 1. Anywhere image 2 is non-transparent, it should replace the contents of image 1 (not blend, but overwrite what is there). Wherever image 2 is transparent, image 1 should show through. I've tried to do this with the following code, but I'm obviously doing something incorrectly with the blending.
            gl.glEnable(GL.GL_BLEND);
            if (iconTexture1 != null)
            {
                gl.glEnable(GL.GL_TEXTURE_2D);
                iconTexture1.bind();
                double red = (double) fillColor.getRed() / 255.0;
                double green = (double) fillColor.getGreen() / 255.0;
                double blue = (double) fillColor.getBlue() / 255.0;
                gl.glColor4d(red, green, blue, this.getOpacity());
                gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
                TextureCoords texCoords = iconTexture1.getImageTexCoords();
                gl.glScaled(width, height, 1d);
                dc.drawUnitQuad(texCoords);
            }
            if (iconTexture2 != null)
            {
                gl.glEnable(GL.GL_TEXTURE_2D);
                iconTexture2.bind();
                // image2 is all white, so color it here
                gl.glColor4d(1d, 0d, 0d, 1d);

                // TODO: What blend function should I be using here to allow image 2 to overwrite what is already there?

                TextureCoords texCoords = iconTexture2.getImageTexCoords();
                gl.glScaled(width, height, 1d);
                dc.drawUnitQuad(texCoords);
            }

Any help to make this work correctly would be appreciated. Thanks.
Jeff

A: There are a few things that might be issues:

*

*You shouldn't turn the blending function on until after you have drawn image 1. Doing so before will blend image 1 with whatever was there already.

*I'm not a big texture user, but I think using texture will override the color of the quad, including any alpha you have specified; so unless the texture has alpha you won't get any blending.

*If you have z-buffering enabled, then maybe image 2 is behind image1; that would obscure it, even if image 2 is transparent. Special methods have to be used to draw transparent 3d.

A good way of working with OpenGL things that don't seem to work is to remove all the complexity, and then add it back bit by bit. The texture is your most complex part - leave that 'til last.


text:
Q: Unable to open Ambari login page with Hadoop (http://127.0.0.1:8080/) I have opened the virtual box, put in the password, and typed in ifconfig to find out the host address, which is http://127.0.0.1:8080/. However, I still cannot open the Ambari login page. I have tried multiple browsers, including IE, Chrome and firefox. None of them worked.
Basically the browser gives me the following message:
This page can't be displayed

•Make sure the web address http://127.0.0.1:8080 is correct.
•Look for the page with your search engine.
•Refresh the page in a few minutes.

I don't know what's wrong with it. Can someone help me with that?

A: I found that I had a conflict with my local IIS that was hosting a local website on port 8080.
I solved the problem by changing the ambari port to 8082.
This is how I did it.
1) I first checked to see if port 8082 was in use using netstat, you could also check if 8080 is in use to confirm you have the same problem.
2) Fireup the hadoop VM and login.
3) Follow the link below, this will show you how to change the ambari port
https://docs.hortonworks.com/HDPDocuments/Ambari-2.1.1.0/bk_ambari_reference_guide/content/_optional_changing_the_default_ambari_server_port.html
4) Restart ambari
https://ambari.apache.org/1.2.0/installing-hadoop-using-ambari/content/ambari-chap2-3.html
5) Re-configure port forwarding on your VirtualBox. There is a section in the following blog.
http://www.howtogeek.com/122641/how-to-forward-ports-to-a-virtual-machine-and-use-it-as-a-server/
I hope this helps

A: I had the same issue and I am using virtual box, i just started the "Hortonworks Sandbox" from Virtualbox and my ambari worked.
http://127.0.0.1:8080


text:
Q: Let $T : V → V$ be a linear transformation. Show that $T^2 = I $ if and only if $V = ker(T − I) ⊕ ker(T + I)$ Let $T : V → V$ be a linear transformation. Show that $T^2 = I $ if and
only if $V = ker(T − I) ⊕ ker(T + I)$
answer:
let $U=(T-I)$ , and $W=(T+I)$
$V=U \bigcap W$
$V\in ker(T-I) : (T-I)(v)=0, → Tv-v=0$
$V\in ker(T+I) : (T+I)(v)=0, → Tv+v=0$
$ [Tv-v=0]-[Tv-v=0] → v=0$
$V=V+Tv-Tv$
Am i on the right way to solve the question and how to complete it, and if not
would someone help me through !!!

A: Since for any $v\in V$
$$
v=\frac1{2}((T+I)v-(T-I)v)
$$
We have
$$V=W+U$$
where
$$
x=\frac1{2}(T+I)v, \:x\in W\quad\text{and}\quad y=\frac1{2}(I-T)v, \:y\in U
$$
 If there is a $z\in W\cap U$, then
$$
z=\frac1{2}(T+I)v'=-\frac1{2}(T-I)v'
$$
Hence we have $v'=0$ and so $z=0$.
Thus $W\cap U=0$ and we conclude
$$V=W\oplus U$$
Since
$$
(T-I)x=\frac1{2}(T-I)(T+I)v=0
$$
There is
$$
W=\ker{(T-I)}
$$
 Likewise since
$$
(T+I)y=-\frac1{2}(T-I)(T+I)v=0
$$
We have
$$
U=\ker{(T+I)}
$$
 Hence
$$
V=\ker{(T-I)}\oplus \ker{(T+I)}
$$

A: Assume first that $T^2 =I$. Then, we note automatically that $\ker (T-I) \cap \ker (T+I) = 0$, since if $v \in \ker(T-I)\cap \ker (T+I)$, then we see that $v = -v$, its additive inverse, so that $v = 0$ identically.
Now we employ rank nullity theorem: We know that $\dim V = \dim \textrm{im} (T-I) + \dim \ker (T-I)$, so that if we choose $v \notin \ker (T-I)$, we conclude that $v \in \textrm{im} (T-I)$ (basically, $V = \ker (T-I) + \textrm{im} (T-I)$).
Using this, assume this is so. Then, $v = (T-I)(u)$ for some $u \in V$. Now apply $T+I$ to both sides: We have:
$$(T+I)(v) = (T+I)(T-I)(u) = (T^2 - I)(u) = 0$$
Since $T^2 = I$. Thus, $\ker (T+I) = \textrm{im} (T-I)$. We can put this together with the above to conclude $V = \ker (T-I) \oplus \ker (T+I)$.
Conversely, suppose $V = \ker (T-I) \oplus \ker (T+I)$. Then, given $v \in V$, we know it is of the form $v = u + w$ with $u \in \ker (T-I)$, $w \in \ker (T+I)$.
Then apply $T$ once to both sides:
$$T(v) = T(u) + T(w) = u - w$$
Apply $T$ once more:
$$T^2 (v) = T(u) - T(w) = u + w = v$$
So that $T^2 = I$, as desired.


text:
Q: fancyhdr and cals vertical merge problem \documentclass[12pt,a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{cals}

\begin{document}

\headheight=81pt

\chead{
\begin{calstable}
\colwidths{{90pt}{90pt}}
\brow
\alignC
\nullcell{ltr}
\cell{b1}
\erow
\brow
\alignC
\nullcell{lr}
\cell{b2}
\erow
\brow
\alignC
\nullcell{lbr}\spancontent{a1, a2, a3}
\cell{b3}
\erow
\end{calstable}
}

\begin{calstable}
\colwidths{{70pt}{70pt}}
%
% 30 row alright,
% 31 row problem, because they begin a new page
%! Incompatible list can't be unboxed.
%\cals@row@dispatch@span ...nvbox \cals@backup@row
%                                                  \cals@issue@row }\fi \let ...
%l.159 \erow
%
%? H
%Sorry, Pandora. (You sneaky devil.)
%I refuse to unbox an \hbox in vertical mode or vice versa.
%And I can't open any boxes in math mode.
%
%? X
%No pages of output.
%
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\end{calstable}

\end{document}

A: One idea for workaround: let the other table be typeset by non-cals package. I enclose an example using the basic tabular environment and a preview of those two pages. Then the different dimensions/definitions should not interfere.
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{fancyhdr}
\pagestyle{fancy}
\usepackage{cals}

\begin{document}
\headheight=81pt

\fancyhead[C]{%
\begingroup
\renewcommand\arraystretch{1.5}
\begin{tabular}{|c|c|c|}
\hline
Hello&World&!!!\\ \hline
!!!&Hello&World\\ \hline
World&!!!&Hello\\ \hline
\end{tabular}
\endgroup
\ifx\relax
\begin{calstable}
\colwidths{{90pt}{90pt}}
\brow
\alignC
\nullcell{ltr}
\cell{b1}
\erow
\brow
\alignC
\nullcell{lr}
\cell{b2}
\erow
\brow
\alignC
\nullcell{lbr}\spancontent{a1, a2, a3}
\cell{b3}
\erow
\end{calstable}%
\fi
}%End of \fancyhead...

\begin{calstable}
\colwidths{{70pt}{70pt}}
%
% 30 row alright,
% 31 row problem, because they begin a new page
%! Incompatible list can't be unboxed.
%\cals@row@dispatch@span ...nvbox \cals@backup@row
%                                                  \cals@issue@row }\fi \let ...
%l.159 \erow
%
%? H
%Sorry, Pandora. (You sneaky devil.)
%I refuse to unbox an \hbox in vertical mode or vice versa.
%And I can't open any boxes in math mode.
%
%? X
%No pages of output.
%
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\brow
\cell{column1}
\cell{column2}
\erow
\end{calstable}

\end{document}


text:
Q: Can't import pmdarima even though it's installed properly I have a working installation of pmdarima in a conda enviroment

    (pmdarima) > pip list | findstr pmdarima
    pmdarima        1.1.0

And when I run python I am able to import pmdarima.

    (pmdarima) > python
    Python 3.7.2 | packaged by conda-forge | (default, Mar 20 2019, 01:38:26) [MSC v.1900 64 bit (AMD64)] :: Anaconda, Inc. on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from pmdarima.arima import auto_arima
    >>>

But when I run a python script which imports pmdarima package I get this error.

    (pmdarima) > python pmdarima.py
    Traceback (most recent call last):
    File "pmdarima.py", line 4, in
        from pmdarima.arima import auto_arima
    File "project_path\pmdarima.py", line 4, in
        from pmdarima.arima import auto_arima
    ModuleNotFoundError: No module named 'pmdarima.arima'; 'pmdarima' is not a package

After getting this error I reopen python in the same enviroment and I cant even import the package here anymore

(pmdarima) > python
    Python 3.7.2 | packaged by conda-forge | (default, Mar 20 2019, 01:38:26) [MSC v.1900 64 bit (AMD64)] :: Anaconda, Inc. on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from pmdarima.arima import auto_arima
    Traceback (most recent call last):
    File "", line 1, in
    File "project_path\pmdarima.py", line 4, in
        from pmdarima.arima import auto_arima
    ModuleNotFoundError: No module named 'pmdarima.arima'; 'pmdarima' is not a package

After restarting the terminal I can import the package again in python and the rest repeats itself

A: The problem was the name of my file. It was conficting with the name of the library. Thanks for your vote. It realy helped a lot!


text:
Q: how to fill array from JSON for image slider in android I have image slider in android studio, but images array from inside project.
I want to use images from JSON, how to the best solution..
this is my adapter
public class adapter_image_slider extends PagerAdapter {

Context mContext;

public adapter_image_slider(Context context) {
    this.mContext = context;
}

@Override
public int getCount() {
    return sliderImagesId.length;
}

private int[] sliderImagesId = new int[]{
        R.drawable.imghome1, R.drawable.imghome2, R.drawable.imghome3,
};

@Override
public boolean isViewFromObject(View v, Object obj) {
    return v == ((ImageView) obj);
}

@Override
public Object instantiateItem(ViewGroup container, int i) {
    ImageView mImageView = new ImageView(mContext);
    mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    mImageView.setImageResource(sliderImagesId[i]);
    ((ViewPager) container).addView(mImageView, 0);
    return mImageView;
}

@Override
public void destroyItem(ViewGroup container, int i, Object obj) {
    ((ViewPager) container).removeView((ImageView) obj);
}

}

and this is my main activity :
public class activity_img_slider_json extends Fragment {

private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] XMEN= {R.drawable.imghome1,R.drawable.imghome2,R.drawable.imghome3,};
private ArrayList<Integer> XMENArray = new ArrayList<Integer>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_img_slider_json,null);

}

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

    init();
}

private void init() {
    for(int i=0;i<XMEN.length;i++)
        XMENArray.add(XMEN[i]);

    mPager = (ViewPager)getActivity().findViewById(R.id.pager);
    mPager.setAdapter(new adapter_img_slider_json(getActivity(), XMENArray));
    CircleIndicator indicator = (CircleIndicator)getActivity().findViewById(R.id.indicator);
    indicator.setViewPager(mPager);

    // Auto start of viewpager
    final Handler handler = new Handler();
    final Runnable Update = new Runnable() {
        public void run() {
            if (currentPage == XMEN.length) {
                currentPage = 0;
            }
            mPager.setCurrentItem(currentPage++, true);
        }
    };
}

}

Thanks For Attention.