text:
Q: Run a lambda on every DynamoDb entry on schedule? Is there a way to run a Lambda on every DynamoDb table record?
I have a Dynamo table with name, last name, email and a Lambda that takes name, last name, email as parameters. I am trying to configure the environment such that, every day, the Lambda runs automatically for every value it finds within Dynamo; can't do all the records in one Lambda as it won't scale (will timeout once more users are added).
I currently have a CloudWatch rule set up that triggers the lambda on schedule but I had to manually add the parameters to the trigger from Dynamo - It's not automatic and not dynamic/not connected to dynamo.
--
Another option would be to run a lambda every time a DynamoDb record is updated... I could update all the records weekly and then upon updating them the Lambda would be triggered but I don't know if that's possible either.
Some more insight on either one of these approaches would be appreciated!

A:
Is there a way to run a Lambda on every DynamoDb table record?

For your specific case where all you want to do is process each row of a DynamoDB table in a scalable fashion, I'd try going with a Lambda -> SQS -> Lambdas fanout like this:

*

*Set up a CloudWatch Events Rule that triggers on a schedule. Have this trigger a dispatch Lambda function.

*The dispatch Lambda function's job is to read all of the entries in your DynamoDB table and write messages to a jobs SQS queue, one per DynamoDB item.

*Create a worker Lambda function that does whatever you want it to do with any given item from your DynamoDB table.

*Connect the worker Lambda to the jobs SQS queue so that an instance of it will dispatch whenever something is put on the queue.

A: Since the limiting factor is lambda timeouts, run multiple lambdas using step functions. Perform a paginated scan of the table; each lambda will return the LastEvaluatedKey and pass it to the next invocation for the next page.

A: I think your best option is, just as you pointed out, to run a Lambda every time a DynamoDB record is updated. This is possible thanks to DynamoDB streams.
Streams are a ordered record of changes that happen to a table. These can invoke a Lambda, so it's automatic (however beware that the change appears only once in the stream, set up a DLQ in case your Lambda fails). This approach scales well and is also pretty evolvable. If need be, you can either push the events from the stream to an SQS or Kinesis, fan out, etc., depending on the requirements.


text:
Q: How can I extend the reach of my antenna? I have a PN532 Board working with my Raspberry Pi to read and write to MIFARE Tags.  I want to be able to do this with tags that are about a foot away, not just a couple centimetres.
What can I do to extend the reach of my antenna?  Code-wise and/or hardware-wise?  I would appreciate some very specific instructions as I am totally new to this topic.

A: There is no 'simple' fix to increase the range of your board.
You'd have to redesign the Tx/Rx pickup antenna to get greater distance.
There are details of the antenna design here, which I hope highlights the complexity of the task.
You need to understand the datasheet for the PN532 and may get more help from the NXP application note AN1445 on NFC antennas.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weird shadows when changing the material of a model When changing the color of my model I end up with strange shadows on my model:

I tried different models already but had the same problem. Any ideas what might be wrong here?
Code below:
   async foo() {

    let myMaterial = this.addMaterial(0x7CD254);

    const leafNodeIds = await this.getLeafNodes();

    this.setMaterial(leafNodeIds, myMaterial);

  }

  addMaterial(color) {

    var material = new THREE.MeshPhongMaterial({
      color: color
    });

    this.viewer.impl.matman().addMaterial(
      this.guid(),
      material);

    return material;
  }

  static async setMaterial(dbId, material) {

    var fragIds = await this.getFragIds(dbId);

    fragIds.forEach((fragId) => {

      this.viewer.getFragmentList().setMaterial(
        fragId, material);
    });
  }

EDIT: A different angle, showing that these weird shadows also appear on the top

A: Shout out to Philippe Leefsma for finding the right solution.
You have to turn off the Ambient shadows option by either

*

*deselecting the option in the menu in the UI (gear icon)

*or by using the viewer.setQualityLevel(bool,bool) function in your code and setting the first argument to false

A: why not change a new color....

material.color=new THREE.Color(0,0,0);// like this

forge's phongmaterial is not same as ThreeJS
so shadows will be broken~~~


text:
Q: how to get the string before first occurrence of a special character i have a column containing hostnames in the format of :
oraclehost.server.region.company.net

How to extract the oraclehost part from the hostname i.e the string before the first ..
Please sugges.Thanks.

A: SELECT REGEXP_SUBSTR(HOSTNAMES, '[^.]+', 1, 1) FROM MYTABLE;

A: Alternatively, substr + instr combination which would probably perform better for large data sets:
substr(hostnames, 1, instr(hostnames, '.') - 1)

For example:
SQL> with mytable (hostnames) as
  2    (select 'oraclehost.server.region.company.net' from dual)
  3  select substr(hostnames, 1, instr(hostnames, '.') - 1) result
  4  from mytable;

RESULT
----------
oraclehost

SQL>


text:
Q: railway cross level detection using image processing technique railway track detection
how can I check this railway cross level are in  same level or not using image processing technique ?
Need to check is there any distance measuring algorithm to calculate the railway cross level detection.


text:
Q: Flex backkeypressedhandler not launching with states I'm developping an mobile program with the Flex 4.5 SDK, this for my thesis for school. I have a bug in my program that I can't fix.
I have a view where I have 2 states. When I change from state my program doesn't listen to the backKey event anymore.
I allready tried this:
backKeyPressed.mystate = "backKeyPressed(event)"

But this doesn't help.
I made a small program to show you:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" title="Home"
    initialize="init()"
    backKeyPressed="view1_backKeyPressedHandler(event)">

<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.events.FlexEvent;

        [Bindable]
        private var m_list:ArrayCollection = new ArrayCollection();

        private function init():void
        {

        }

        protected function button1_clickHandler(event:MouseEvent):void
        {
            currentState = 'state2';

        }

        protected function button2_clickHandler(event:MouseEvent):void
        {
            currentState = 'state1';

        }

        protected function view1_backKeyPressedHandler(event:FlexEvent):void
        {
            event.preventDefault();

        }

    ]]>
</fx:Script>
<fx:Declarations>
    <s:State name="state1"/>
    <s:State name="state2"/>
</fx:Declarations>
<s:Group id="stateOneGroup" includeIn="state1">
    <s:Button x="30" y="112" label="To State 2"
              click="button1_clickHandler(event)"/>
    <s:Label x="72" y="216" text="State1"/>
</s:Group>

<s:Group id="stateTwoGroup" includeIn="state2">
    <s:Button x="267" y="112" label="To State 1"
              click="button2_clickHandler(event)"/>
    <s:Label x="303" y="216" text="State2"/>
</s:Group>

 </s:View>

I also searched on adobe if it's a bug but I don't seem to find it.
I hope someone can help me.
Kind regards,
Thibault Heylen

A: I had the same issues today. At last i got it. In my issues, if it is the first view, the backkeypressed doesn't work, but for the other views, the backkeypressed works well.
Hope this helps


text:
Q: Associated primes and Cohen-Macaulay rings In the book Cohen-Macaulay rings by Bruns and Herzog. Part of theorem 2.1.2 states

Let $(R,m)$ be a Noetherian local ring, and $M\neq0$ a Cohen-Macaulay $R$-module. Then $\dim R/p=\operatorname{depth}M$ for all $p\in\operatorname{Ass}M$.

If $M=R$ and if $R/p$ is Cohen-Macaulay, then we would have $\operatorname{depth}R/p=\operatorname{depth}R$.
So, does there exist such C-M ring $(R,m)$ with some $p\in \operatorname{Ass}R$ so that $R/p$ is not Cohen-Macaulay? (I am especially curious about the case where $R$ is a Cohen-Macaulay affine ring (i.e. $R=k[x_1,...,x_n]/I$ for some ideal $I\in k[x_1,...,x_n]$ where $k$ is a field) if we don't assume $R$ to be local.)


text:
Q: Sending an audio packet every 20 milliseconds I have an application that needs to send an audio packet over UDP. To avoid jitter I want to schedule a thread or task to perform this task every 20 milliseconds. The pseudo code looks like this:
while(true)
{
    byte[] packet = GetNextPacket();
    socket.Send(packet);
    var waitUntill = DateTime.Now.AddMilliseconds(20);
    while(DateTime.Now < waitUntill) { }
}

This works fine, but it uses 100% of a CPU core. Which is of course undesirable. I've tried playing with Thread.Sleep and Thread.Yield and their task equivalents but in all cases I either end up with 100% load or an extremely jittery experience (which is to be expected).
Is there no way in C# to schedule a task at such a fine grained level? I don't need a 100% guarantee (Windows is not a real-time OS) but something that will work most of the time. Note that I'm not worried about the GC :).
I'm fine with calling any COM code to achieve this, though my ideal solution would be multi-platform. I'm currently using dotnet core 3.0.
If it is not possible in C#, how is it achieved in languages like C++ which do perform these kinds of tasks.

A: The System.Threading.Timer object is designed for this sort of thing, though I've never used it with such a low time interval.
var timer = new Timer(_ => socket.Send(GetNextPacket()), null, 0, 20);

A: Look into using a multimedia timer:
High resolution timer in C#
They're specifically designed for these kind of high-resolution applications.


text:
Q: Autopliot API - Trigger Journey - How to make it work? I'm struggling with the Autopilot API (http://docs.autopilot.apiary.io/).
I have a trigger journey to set up: when a post-method form is sent, I want to send a SMS (through Twilio) and an email (through Sendgrid) to the user with the information he filled the form with.
So far I understood that a Trigger Journey would be the best solution: I would place an API call in the code dealing with the form submit, and that trigger would send the SMS + the email via Autopilot.
Here's the thing: I don't know AT ALL where to begin. The docs speak about an HTTP Request to include the API key, then I have no clue of what to do to make the trigger work.
Hop you can help with this! Thanks a lot!

A: I am also working in Autopilot API integration for adding a contact to a journey.
In Autopilot API Documentation, To view the example code for "Adding a contact to a journey", Kindly click on the particular title. Once you click on the title, a page section will be opened in right side of the page.
For example, please see the below image.

For the comment:
From Official Documentation
Add Contact to a list
It is possible to add a contact and add them to a list in a single API call, you just need to provide an additional contact field called _autopilot_list with the list id, e.g."_autopilot_list": "contactlist_91053049-5582-40B4-A17F-78ADF8F25663"
You can obtain the list name with the fetch lists command documented in this API, or through the URL bar in your browser when viewing the list in Autopilot.If you provide this along with the request it will both add the contact and add them to the list.


text:
Q: Technical reason why objects were not movable in the first C++ versions? IMPORTANT I'm not asking about opinions, not about what's better or not, but about the objective facts: The actual reasons that Stroustrup or other collaborators used for taking the choice of imposing that objects cannot be relocatable.

I'm not able to locate the technical reason why it was decided that the address of an object cannot be changed (unfortunately any search about moving or copying objects gets cluttered with the move/copy semantics introduced later in the language).
I mean: C++ rightly imposes constructors when an object is copied (not doing so would go against the OOP paradigm). However, from the very beginning, it was decided that moving an object A from address addr1 to addr2 was not allowed, unless the copy constructor was invoked. What's the technical reason behind that choice? Why it was decided that its address was so important for an object?
Polymorphic objects have a pointer to their vtable, but the opposite is not true, so moving an object shouldn't break vtables. Thus, there must be another reason for it.
Also, there are other OOP languages in which objects can be freely moved. So, the OOP paradigm is not the reason.
Maybe some additional programming principles were considered undeniable when they designed the C++ language and that required to forbid moving objects? Which ones?

A:
I'm not able to locate the technical reason why it was decided that the address of an object cannot be changed

In C++ an object is the bytes it occupies1. Even std::memmove doesn't relocate an object, it merely copies it's bytes. (memmove and std::memcpy differ only in preconditions: memmove allows [src, src + size) to overlap [dest, dest + size), memcpy does not)
Also you seem to have a different definition of object than what C++ has. Almost everything with a type is an object (only function types and reference types don't categorise objects). ints are objects, pointers (including function pointers) are objects.
A class need not have a vtable2, if it has no virtual members, or if the compiler statically knows the dynamic type at every call site.

*

*plus a lifetime. Before it is created and after it is destroyed, those bytes can be something else.

*assuming that the implementation ordinarily uses vtables to dispatch virtual functions. Other methods of dynamic dispatch are possible.

A:
Maybe some additional programming principles were considered undeniable when they designed the C++ language and that required to forbid moving objects? Which ones?

The ones that say it should map efficiently onto the hardware implementation, which implies raw pointers, which implies address-identity.

Also, there are other OOP languages in which objects can be freely moved. So, the OOP paradigm is not the reason

Yes, these are languages which don't mind inserting an extra layer of indirection or complexity everywhere for the convenience of the garbage collector. This is more-or-less antithetical to C++'s goals.

it was decided that moving an object A from address addr1 to addr2 was not allowed, unless the copy constructor was invoked

The constructor is irrelevant, because in C++ all objects (which includes POD structs and even scalar primitives) have an identity. This identity is (or is bound to) their address. You can't move an int, either, you can only copy it. You can't move an object even with a copy constructor. You can't actually move an object even with a move constructor, because that's just a destructive copy. It doesn't pretend to mutate the address of an existing object.

I'm not able to locate the technical reason why it was decided that the address of an object cannot be changed

Well, the address of an object can't be changed now either.
This is only ever possible in languages which hide or abstract raw pointers. C++ exposes raw references and pointers to objects, so there's no way to change an object's address without potentially breaking references to it.
If you want to make an object which is movable in the sense that the Java runtime can shuffle memory around, you need to make sure it's only ever accessible via smart pointers with the required guarantees. Since the this pointer will always be a raw pointer in instance methods, you have to also make sure it either has no instance methods, or that your smart pointers can synchronize access to prevent relocation during a call.

A: To understand the historical development of C++, you need to understand the context of that development. C++ is of course historically rooted in C. That was not a random choice. C was and is historically very important.
To look at the success of C, we need to contrast it with its contemporaries. Languages like COBOL, Algol and FORTRAN were clunky and inflexible. Languages like Lisp, Smalltalk, and Modula-2 were more elegant, but did not perform well. And in the era where C blossomed, performance was still a very pressing concern. This was well before the era of multi-Ghz multi-core CPU's. C could give you almost the performance of assembly, with far more portability and far less development cost.
But as noted, C lacks some of the features that are really relevant when developing bigger programs. Even at the original home of C, this was noted in their own products. AT&T developed their phone switch (5ESS) in a sort of Object-Oriented fashion, but using their own C language. C++ made perfect sense in that context. Improvements in compiler technology made it possible to get the benefits of OO with lower costs than doing it manually. A string type did not need to be very expensive, and it's far easier to use than C's strcpy.
Now C++ needed to formalize how objects worked, and this was a very early decision - it's the key development that led to the fork from C. In fact, C++ redefined the C language such that many C programs were also correct C++ programs, and the struct from C became an object type in C++.
Now we come to your "move"  question. In C, you can memcpy a struct. That would break more complex types such as strings. Even memcpy'ing a char* in C is fragile. The C++ solution was the copy ctor, and the assignment operator. These inventions made C++ safer compared to C++, and allowed more useful datastructures. But the very decision here defined how C++ objects work. C structs by default stay put, and so do C++ objects, because else a C program would not be a valid C++ program.

A: I will rephrase the question as I understand the essence of it, and then answer it.

Why reallocating an array of objects must be done by invoking constructors and destructors? Why cannot we just copy bytes of an old object to a new address and be done with it?

To reiterate, my understanding of moving in OP's terminology is copying object's bytes to a new object (perhaps if it is guaranteed that the original object will not be used any more). It has nothing to do with C++ move semantics.
Copying bytes does not guarantee integrity of an object, for several reasons.

*

*An implementation is free to represent objects using hidden internal pointers. Objects that use multiple inheritance are often represented this way. Copying bytes to a new place invalidates these pointers. Copying bytes in this situation invalidates these pointers and destroys the integrity of the object.

*Programmers are also free to use internal pointers. An object can contain a pointer to its own subobject. An object can also point to dependent objects which can point back to their owner. Copying bytes in this situation invalidates these pointers and destroys the integrity of the object.

The second bullet point is of course also true for C objects. But in C one cannot simply assign such objects either. Internal pointers need to be updated.
In C++, assignment always works (well, of the user wrote correct copy constructor and assignment operator). It would be unreasonable to keep assignment always working and break reallocation of certain arrays. So it was not done.
Note that a C+ compiler is allowed to byte-copy objects instead of copy-constructing them, if it can prove that it will not change the semantics of the program.


text:
Q: BeautifulSoup - Scraping multiple pages but previous page data not being stored in the list BeautifulSoup - Scraping multiple pages but previous page data not being stored in the list.
I'm a beginner and have been scratching my head on this for some time. I'm trying to scrape 5 pages and store all data in one data frame and save it as cvs. Every time I run my code, I get 24 records just from the last page. Looks like my list is not holding the data from previous pages. What am I screwing up? Thanks!
#importing libraries

import pandas as pd
import requests
from bs4 import BeautifulSoup
import time

#send request
#Getting the first 5 pages
for x in range(0,6):
    url = 'https://apps.shopify.com/browse/all?page='
    page = requests.get(url+str(x))
#parse the html
    soup = BeautifulSoup(page.text, 'html.parser')
#read app name and add it to the app_name list
    app_name = []
    app_name_elm = soup.find_all(class_='ui-app-card__name')
    for item in app_name_elm:
        app_name.append(item.text)
#read app rating and add it to the app_rating list
    app_rating = []
    app_rating_elm = soup.find_all(class_='ui-star-rating__rating')
    for item in app_rating_elm:
        app_rating.append(item.text)
#read app review count and add it to the app_reviews list
    app_reviews = []
    app_reviews_elm = soup.find_all(class_='ui-review-count-summary')
    for item in app_reviews_elm:
        app_reviews.append(item.text)
#read app link and add it to the app_link list
    app_link = []
    app_link_elm = soup.find_all(class_='grid__item grid__item--tablet-up-half grid-item--app-card-listing')
    for item in app_link_elm:
        app_link.append(item.find('a').get('href'))
#creating a dataframe
    final_list = []
    for name, rating, review, link in zip(app_name,app_rating,app_reviews,app_link):
        final_list.append({'Application_Name':name,'Rating':rating,'Number_Of_Reviews':review,'Link':link})
    df = pd.DataFrame(final_list)

print(df)
#df.to_csv('part1_scrape.csv')

A: You are creating these variables app_name = [], app_rating = [] , app_reviews = [] etc inside the loop . Move them outside the loop.
And move the last part , that is , df = pd.DataFrame(final_list) outside the loop.

A: You are overwriting your variable df everytime in you loop. What you can do is save all the results in a list:
results = [] #create an empty list outside the loop
for x in range(0,6):
    url = 'https://apps.shopify.com/browse/all?page='
    page = requests.get(url+str(x))
#parse the html
    soup = BeautifulSoup(page.text, 'html.parser')
#read app name and add it to the app_name list
    app_name = []
    app_name_elm = soup.find_all(class_='ui-app-card__name')
    for item in app_name_elm:
        app_name.append(item.text)
#read app rating and add it to the app_rating list
    app_rating = []
    app_rating_elm = soup.find_all(class_='ui-star-rating__rating')
    for item in app_rating_elm:
        app_rating.append(item.text)
#read app review count and add it to the app_reviews list
    app_reviews = []
    app_reviews_elm = soup.find_all(class_='ui-review-count-summary')
    for item in app_reviews_elm:
        app_reviews.append(item.text)
#read app link and add it to the app_link list
    app_link = []
    app_link_elm = soup.find_all(class_='grid__item grid__item--tablet-up-half grid-item--app-card-listing')
    for item in app_link_elm:
        app_link.append(item.find('a').get('href'))
#creating a dataframe
    final_list = []
    for name, rating, review, link in zip(app_name,app_rating,app_reviews,app_link):
        final_list.append({'Application_Name':name,'Rating':rating,'Number_Of_Reviews':review,'Link':link})
    df = pd.DataFrame(final_list)
    results.append(df) #Append result to the list

print(results)


text:
Q: Error when running grunt sass compile task I have the following error when running a grunt task to compile a scss file:
Running "watch:sass" (watch) task
Waiting...
>> File "Content\sass\main.scss" changed.
Running "sass:dist" (sass) task
Error: expected "{".
@import "layout";
                ^
  Content\sass\main.scss 4:17  root stylesheet
Warning: Exited with error code 65 Use --force to continue.
Aborted due to warnings.

The sass file (main.scss) contains one line of code:
@import "layout";

And the layout file has a simple few lines of CSS.
The problem I'm having with this is that I have run this exact same config with the exact same code on different machines before without fail; the issue must be with this computer.
When I run node -v, I get v8.11.2. When I run npm -v, I get v5.6.0
I'm running a new install of Windows 10 using Visual Studio to code and command line to run the tasks.
Does anyone have any idea why this might be happening? Here is my package.json:
{
  "version": "1.0.0",
  "name": "SafeOnlineMVC",
  "private": true,
  "devDependencies": {
    "grunt": "0.4.5",
    "grunt-bower-task": "^0.4.0",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-jshint": "^1.1.0",
    "grunt-contrib-sass": "^0.9.2",
    "grunt-contrib-uglify": "^2.0.0",
    "grunt-contrib-watch": "^0.6.1"
  }
}

My gruntfile.js:
module.exports = function (grunt) {
    grunt.loadNpmTasks("grunt-bower-task");
    grunt.loadNpmTasks("grunt-contrib-watch");
    grunt.loadNpmTasks("grunt-contrib-sass");

    grunt.initConfig({
        sass: {
            dist: {
                options: {
                    style: "compressed"
                },
                files: [
                  {
                      "Content/main.css": "Content/sass/main.scss"
                  }
                ]
            }
        },
        watch: {
            sass: {
                files: ["Content/sass/*.scss"],
                tasks: ["sass"]
            }
        }
    });
};

Thanks.
Edit: Main scss file:
@import "_layout";

Edit: Layout scss file:
.inner{
    width: 1320px;
    margin: 0 auto;
    padding: 0 20px;
    max-width: 100%;
    box-sizing:border-box;
}

A: There is an error in your css, as indicated by the error message. You're missing an opening brace after a selector name.


text:
Q: Iframe wrong loading IE 11 I knwo that IE11 is not the most popular thing ever, but I want to ask for advice because I am stuck in this. Here is the situation I have a page that is responsive and redy to work in widget size. To laod the page in widget size I have a ifrmae that I call like this

and if I want to call the stend alone page I call it like this

This is working perfect for all other browser, but in IE11 even if the JS is detecting correct that here have to be a widget and is making the call with extra paramiter widget, the ifrma load the full content with no changes. I am stuck so ny help can be much appreciated.


text:
Q: Uploaded video from TikTok using the PyTikTokAPI module weighs less than a megabyte and does not open I seem to have recorded the api correctly, but if I try to download a video from TikTok without a watermark (using the api.downloadVideoByIdNoWatermark()), then it weighs less than a megabyte and is not readable, however, if I download it with a watermark (using the api.downloadVideoById()), then everything works fine.
Here is my code:
from TikTokAPI import TikTokAPI
cookie = {"s_v_web_id": "verify_leohz0ln_MYeosdFT_mOv0_4kwU_Bo7E_1CYuGCxbSakb"}
api = TikTokAPI(cookie=cookie)
video_id = '6843481669886954757'
save_path = 'C:/Users/User/Downloads/video.mp4'
api.downloadVideoByIdNoWatermark(video_id=video_id, save_path=save_path)


text:
Q: Check computation of limit distribution of $\max\{X_1, \ldots , X_n\}/\sqrt n$ for i.i.d. $(X_i)$ with PDF $2/x^3$ on $x>1$
$X_1$, $X_2$, . . . are iid random variables having pdf $$f_X(x)
 =\frac{2}{x^3}I_{(1,\infty)}(x)$$  Let $$T_n= \frac{\text{max}{\{X_1, . . . , X_n}\}}{\sqrt{n}}$$
  (a) Consider the sequence $T_1$, $T_2$, . . . and give the pmf or pdf of the limiting distribution.

I first note that the cdf of $X$ is given by
$$ F_{X}(x)=
\begin{cases}
1-\frac{1}{x^2} & x \gt 1 \\
0 & x\leq 1 \\
\end{cases} $$
We have
$$\begin{align*}
F_{T_n}(t)
&=\mathsf P(T_n\leq t)\\\\
&=\mathsf P\left(\frac{\text{max}{\{X_1,...,X_n}\}}{\sqrt{n}}\leq t\right)\\\\
&=\mathsf P\left(\text{max}{\{X_1,...,X_n}\}\leq \sqrt{n}\cdot t\right)\\\\
&=\mathsf P\left(X_1\leq \sqrt{n}\cdot t,...,X_n\leq\sqrt{n}\cdot t\right)\\\\
&=\prod_{i=1}^n \mathsf P\left(X_i \leq \sqrt{n}\cdot t\right)\\\\
&=\left(1-\frac{1}{(\sqrt{n}\cdot t)^2}\right)^n
\end{align*}$$
Altogether, we have
$$ F_{T_n}(t)=
\begin{cases}
\left(1-\frac{1}{(\sqrt{n}\cdot t)^2}\right)^n & t \gt \frac{1}{\sqrt{n}} \\
0 & x\leq \frac{1}{\sqrt{n}} \\
\end{cases} $$
Using the property that
$$\lim_{n\rightarrow\infty}\left(1+\frac{x}{n}\right)^n\rightarrow e^x$$
we get
$$ \lim_{n\rightarrow\infty}F_{T_n}(t)=
\begin{cases}
e^{-\frac{1}{t^2}} & t \gt 0 \\
0 & t \lt 0 \\
\end{cases} $$
Then
$$\frac{d}{dt}\left(e^{-\frac{1}{t^2}}\right)=\frac{2e^{-\frac{1}{t^2}}}{t^3}$$
Finally, we get
$$f_T(t)=\frac{2e^{-\frac{1}{t^2}}}{t^3}I_{(0,\infty)}(t)$$
Is this a valid solution?


text:
Q: What is the word for the study of witches and witchcraft? Is there an academic or scientific word to describe social or humanities studies focusing on witches and witchcraft? I expect it to be some something-o-logy? Compare with cryptozoology.

A: "Witchcraft Studies"
See for example "A Neglected Aspect of Witchcraft Studies", "Witchcraft studies in Austria, Germany and Switzerland" and "Witchcraft Studies from the Perspective of Women's and Gender History: A Report on Recent Research".
The term has been used for the study of modern practices of witchcraft like Wicca, Feri, 1734, etc. for the study of earlier practices these have sometimes claimed to descend from (including a range of positions as to whether that is the case) for the beliefs of those who claimed that witches were attacking society (from the witch crazes of the early modern period and earlier through to the "Satanic Panic" of the 1980s and beyond) and to other practices of magic that have been given the label "witchcraft". It has also been used for historical, sociological, political and other analyses of witchcraft.
As such it fits your question very well.
It's wide enough that you may wish to be narrower as with something like "history of witchcraft" etc.
It also overlaps with "pagan studies", in that something covering modern pagan witchcraft like Hutton's Triumph of the Moon or Joanne Pearson's Wicca and the Christian Heritage would definitely be in the overlap, something like Margot Adler's Drawing Down the Moon would be more "pagan studies" than "witchcraft studies" as while it is certainly significant in the latter it covers much in the wider scope, and something like Levack's The Witch-Hunt in Early Modern Europe would be "witchcraft studies" but not directly concerned with "pagan studies" as it doesn't look at modern witchcraft practices at all and as such is only relevant to actual witchcraft practices and (by extension) paganism in so far as the period it studies has a cultural significance among modern witches.

A: English-speaking academics in the humanities don't use -ology or -ics constructions much to distinguish what they do from what their colleagues in the same field or 'neighbouring' fields do: those suffixes designate disciplines rather than topics.
Topics are usually designated with the word studies, either following the name of the topic, if that is short—Shakespeare studies, Carolingian studies, textual studies—or followed by in + topic name if that is longer—studies in mediaeval pilgrimage, studies in 17th-century verse. I'd go with

Witchcraft studies ... or, if you need a book or seminar title,
Studies in Witchcraft, Benjamin, Spring semester 2015.

A: I nominate a neologism: wikkology
wikkology — The study of witches; the study of the practicing of witchcraft. cf. demonology
It is reasonably derived from some of the etymological sources for witch:
https://en.wiktionary.org/wiki/witch
It fills the need for a concise -ology form, and should not be controversial in any way.
This question has bothered me for many years, and is exacerbated each time I peruse a favorite book of mine, The Encyclopedia of Witchcraft & Demonology by Rossell Hope Robbins. In fact, I came here to pose this question, and discovered that a discussion was already underway. I formulated the neologism several months ago in a fit of determination but haven't been afforded an opportunity to use it. Since it seems there is no consensus about the existence of an accepted term, I offer wikkology to the world, and time will tell if it gains any traction.


text:
Q: List of emails clients which MAPISendMail can work Can someone give me a list of Client email programs which MAPI (MAPISendMail function) can be used on. I know I can use MAPI functionality in OUTLOOK, however I need to know does it support other emails clients like Thunderbird or Lotusnotes.

A: I think your asking the wrong question, MAPI is windows API so any windows client program should be able to use the api
Messaging Application Programming Interface (MAPI) is a messaging architecture and a Component Object Model based API for Microsoft Windows. MAPI allows client programs to become (e-mail) messaging-enabled, -aware, or -based by calling MAPI subsystem routines that interface with certain messaging servers.
The full Extended MAPI interface is required for interfacing messaging-based services to client applications such as Outlook. For example, several non-Microsoft e-mail server product vendors created "MAPI service providers" to allow their products to be accessed via Outlook. Notable examples include Axigen Mail Server, Kerio Connect, Scalix, Zimbra, HP OpenMail, IBM Lotus Notes, Zarafa, and Bynari.
MAPI also had a service provider interface of sorts. Microsoft used this to interface MS Mail to an email system based on Xenix, for internal use.
Extended MAPI is the main e-mail data access method used by Outlook, to interface to Microsoft Exchange, via MAPI service providers shipped with Outlook.
https://en.wikipedia.org/wiki/Messaging_Application_Programming_Interface


text:
Q: Symfony 3 - KNP paginator error - Route issue? I added a pagination using KNP Paginator. It works well except for one page that render a page for specific ID. This page worked well before I added the pagination. the function was
public function orderDetailAction($id)

For the pagination, I added the Request.
 /**
  * Display order detail
  *
  *@Route("/order/{id}", name="requestitem_order")
  *@Method("GET")
  */
  public function orderDetailAction(Request $request, $id)
  {
    $em = $this->getDoctrine()->getManager()->getRepository('ECAInventoryBundle:RequestItem');
    $query = $em->createQueryBuilder('r')
      ->innerJoin('r.item','i')
      ->select('i.name')
      ->addSelect('r.quantity')
      ->addSelect('i.id')
      ->addSelect('r.date')
      ->addSelect('r.remark')
      ->where('i.id = :ID')->setParameter('ID', $id)
      ->orderBy('r.date', 'DESC')
      ->getQuery();

    $details = $query->getResult();

    $paginator = $this->get('knp_paginator');
    $result = $paginator->paginate(
      $details,
      $request->query->get('page', 1)/*page number*/,
      5/*limit per page*/
  );

    $form = $this->createFormBuilder($details)
      ->add('id', TextType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('name', TextType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('quantity', TextType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('date', DateType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('remark', TextareaType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px', 'required' => false),'empty_data'  => null))
      ->getForm();

    return $this->render('requestitem/order_details.html.twig', array('details'=> $details, 'form' => $form->createView()));

  }

The Twig file is
{% extends 'base.html.twig' %}

{% block body %}
{% set Name = '' %}
{% for detail in details %}
  {% set Name = detail.name %}
{% endfor %}

Detail

{{Name}}

          Quantity
          Date
          Remark

        {% for detail in details %}

          {{ detail.quantity}}
          {{ detail.date|date('d M Y') }}
          {{ detail.remark}}

        {% endfor %}

{# display navigation #}

  {{ knp_pagination_render(details) }}

Back to Balance
{% endblock %}

I have the following error

Type error: Argument 2 passed to
  Knp\Bundle\PaginatorBundle\Twig\Extension\PaginationExtension::render()
  must be an instance of
  Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination, array given,
  called in
  C:\xampp\htdocs\inventory\var\cache\dev\twig\60\60f10f12ae3f80d30f6ac9425ed3eadb7f6a850a4574537165108f4cd8dfd500.php
  on line 107

The controller route is @Route("/order/{id}" and the paginator uses this kind of route ?page=2. I don't know if this is the problem.
How can I solve it?

A: You make some mistake:
1) You can pass the query object to the paginate method instead of the details object (You don't need to execute the query in order to paginate the result : knp do it for you)
2) You need to pass the result to the view instead of the details object.
So modify your controller as follow:
**
  * Display order detail
  *
  *@Route("/order/{id}", name="requestitem_order")
  *@Method("GET")
  */
  public function orderDetailAction(Request $request, $id)
  {
    $em = $this->getDoctrine()->getManager()->getRepository('ECAInventoryBundle:RequestItem');
    $query = $em->createQueryBuilder('r')
      ->innerJoin('r.item','i')
      ->select('i.name')
      ->addSelect('r.quantity')
      ->addSelect('i.id')
      ->addSelect('r.date')
      ->addSelect('r.remark')
      ->where('i.id = :ID')->setParameter('ID', $id)
      ->orderBy('r.date', 'DESC')
      ->getQuery();

    $paginator = $this->get('knp_paginator');

    $result = $paginator->paginate(
      $query,  // (1) pass the query instead of the result (better performance)
      $request->query->get('page', 1)/*page number*/,
      5/*limit per page*/
  );

    $form = $this->createFormBuilder($details)
      ->add('id', TextType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('name', TextType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('quantity', TextType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('date', DateType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px')))
      ->add('remark', TextareaType::class, array('attr' =>array('class' =>'form-control', 'style' =>'margin-bottom:15px', 'required' => false),'empty_data'  => null))
      ->getForm();

    return $this->render('requestitem/order_details.html.twig', array(
    'details'=> $result,  // (2) pass the result of the pagination
    'form' => $form->createView())
    );

  }

Hope this help

A: The problem was the route.I changed the route  and the function parameters to retrieve the id and page from the url. I make the following changes to make it work.
/**
  * Display order detail
  *
  *@Route("/order/{id}/{page}", name="requestitem_order", defaults={"page": 1})
  *@Method("GET")
  */
  public function orderDetailAction($id, $page)
  {
    $em = $this->getDoctrine()->getManager()->getRepository('ECAInventoryBundle:RequestItem');
    $query = $em->createQueryBuilder('r')
      ->innerJoin('r.item','i')
      ->select('i.name')
      ->addSelect('r.quantity')
      ->addSelect('i.id')
      ->addSelect('r.date')
      ->addSelect('r.remark')
      ->where('i.id = :ID')->setParameter('ID', $id)
      ->orderBy('r.date', 'DESC')
      ->getQuery();

    $details = $query->getResult();

    $paginator = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
      $details,
      $page,
      5
    );

Instead of using get(page,1) in $pagination, I use $page.
The answer of Paginate in KnpPager not work help me a lot.


text:
Q: Infinitely many transcendental numbers over Q My previous question was not well-framed so I will ask again:
Can you explicitly produce an infinite set of real numbers which is algebraically independent over $\mathbb Q$?

A: Yes, using the Lindemann-Weierstrass theorem.
Let $S$ be any infinite set of algebraic real numbers linearly independent over $\mathbb{Q}$, for example $\{\sqrt p : p \text{ is prime}\}$. (A maximal such set is a basis for $\overline{\mathbb{Q}}$ over $\mathbb{Q}$.)
Then $\{e^s : s \in S\}$ is algebraically independent.


text:
Q: How to attach files with metaWeblog to a blog post? I'm trying to post to my blog with images.
Yes, I can upload images and I can see that images in the content of post
but it's not in a attached file list.
How can I put the images that I upload in the attached file list?
When I'm posting with MS word 2010 to my blog, images that I put on the word are always updated in a attached file list. But my php source doesn't.
Is there any way to attach files to a blog post?

$cBlog = new blog;
$title = "This is a article's title";
$desc = "IT will be the content";
$return = $cBlog->writePost($title, $desc);

class blog
{
    public $g_blog_url;
    public $user_id;
    public $blogid;
    public $password;
    public $publish;

    function __construct()
    {
        $this->g_blog_url = "https://api.blog.naver.com/xmlrpc";
        $this->user_id = "globeseen";
        $this->blogid = "globeseen";
        $this->password = "password";
        $this->publish = true;
    }

    function writePost($title, $description, $category="")
    {
        $client = new xmlrpc_client($this->g_blog_url);
        $client->setSSLVerifyPeer(false);
        $GLOBALS['xmlrpc_internalencoding']='UTF-8';

        $img = $this->upload_image("D:\\1.jpg");

        $struct = array(
        'title' => new xmlrpcval($title, "string"),
        'description' => new xmlrpcval($description."", "string"),
        'categories' => new xmlrpcval($category, "string"),
        'tags' => new xmlrpcval('clothing', "string")
        );

        $f = new xmlrpcmsg("metaWeblog.newPost",
        array(
        new xmlrpcval($this->blogid, "string"),
        new xmlrpcval($this->user_id, "string"),
        new xmlrpcval($this->password, "string"),
        new xmlrpcval($struct , "struct"),
        new xmlrpcval($this->publish, "boolean")
             ));

        $f->request_charset_encoding = 'UTF-8';
        return $response = $client->send($f);
    }

    function upload_image($fpath) {
  global $api_url, $blog_user, $blog_passwd;

  $api_url = $this->g_blog_url;
  $blog_user = $this->user_id;
  $blog_passwd = $this->password;

  $imgbit = file_get_contents($fpath, FILE_BINARY);
      $img = new xmlrpcval(
       array (
        'bits' => new xmlrpcval($imgbit, 'base64'),
        'type' => new xmlrpcval('image/jpeg', 'string'),
        'name' => new xmlrpcval(basename($fpath), 'string')
       ), 'struct');

      $c = new xmlrpc_client($api_url);

      $c->setSSLVerifyPeer(false);
      $x = new xmlrpcmsg("metaWeblog.newMediaObject");
      $x->addParam(new xmlrpcval($blog_user, 'string'));
      $x->addParam(new xmlrpcval($blog_user, 'string'));
      $x->addParam(new xmlrpcval($blog_passwd, 'string'));
      $x->addParam($img);

      $c->return_type = 'phpvals';
      $r =$c->send($x);
      if ($r->errno=="0") {
          return $r->val['url'];
      } else {
          echo "There was an error
";
          print_r($r);
          echo "
";
          return null;
      }
     }

}


text:
Q: Kableextra: after updating to R 4.0.3 and reinstalling, I cannot run correctly old script with multiline wrapped text in each cell Dearest,
This is similar to one script I have been running for months on my platform.
I have some long text inside a column (called "description") and I want to wrap it (no more than 20 characters per line). In order to do this, I have a function which inserts a break line "\n" in the text whenever needed.
I then use kableextra's "linebreak" function on that text to make sure the linebreak is properly understood (and it is).
The final result is then processed via latex to generate a pdf.
The trouble is that the text inside the description column, although broken as I want, is no longer left aligned.
I am sure I have not had this in the past (before updating R to 4.0.3 and reinstalling kableextra).
Anyone who knows how to fix this will have my gratitude!
Thanks
library(tidyverse)
library(kableExtra)
#>
#> Attaching package: 'kableExtra'
#> The following object is masked from 'package:dplyr':
#>
#>     group_rows
library(formattable)

##Functions to wrap and format text in the table

wrapper2 <- function(x, width) {
    lapply(strwrap(x, width = width, simplify = FALSE), paste, collapse="\n")

}

wrapper_text <- function(x, width) {
 res <- wrapper2(x, width) %>% unlist
    return(res)
}

df <- structure(list(description = c("Total Goods", "85 Electrical machinery and equipment",
"84 Machinery and mechanical appliances", "63 Other made-up textile articles",
"94 Furniture; lamps and lighting fittings", "90 Optical, medical or surgical instruments",
"62 Apparel and clothing, not knitted or crocheted", "29 Organic chemicals",
"39 Plastics", "95 Toys, games and sports requisites", "87 Motor vehicles"
), y = c(8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8)), row.names = c(NA,
-11L), class = c("tbl_df", "tbl", "data.frame"))

df2 <-  df  %>%
    mutate(description=wrapper_text(description, 20))  %>%
    mutate(description=linebreak(description))

mytable <- df2 %>%
     kable("latex", booktabs = T, escape = F,align=c("l", "r")) %>%

    kable_styling( )

writeLines(
  c(

      "\\documentclass{article}",
      "\\usepackage{graphicx}",
      "\\usepackage{makecell}",
"\\usepackage{float}",
          "\\usepackage{booktabs}",
"\\begin{document}",
"\\pagestyle{empty}",
    mytable,
    "\\end{document}"
  ),
  "test_table.tex"
)

tools::texi2pdf("test_table.tex", clean = TRUE)

print(sessionInfo())
#> R version 4.0.3 (2020-10-10)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Debian GNU/Linux 10 (buster)
#>
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.3.5.so
#>
#> locale:
#>  [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C
#>  [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8
#>  [5] LC_MONETARY=en_GB.UTF-8    LC_MESSAGES=en_GB.UTF-8
#>  [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> other attached packages:
#>  [1] formattable_0.2.0.1 kableExtra_1.2.1    forcats_0.5.0
#>  [4] stringr_1.4.0       dplyr_1.0.2         purrr_0.3.4
#>  [7] readr_1.4.0         tidyr_1.1.2         tibble_3.0.3
#> [10] ggplot2_3.3.2       tidyverse_1.3.0
#>
#> loaded via a namespace (and not attached):
#>  [1] styler_1.3.2      tidyselect_1.1.0  xfun_0.18         haven_2.3.1
#>  [5] colorspace_1.4-1  vctrs_0.3.4       generics_0.0.2    viridisLite_0.3.0
#>  [9] htmltools_0.5.0   yaml_2.2.1        blob_1.2.1        rlang_0.4.8
#> [13] pillar_1.4.6      glue_1.4.2        withr_2.3.0       DBI_1.1.0
#> [17] dbplyr_1.4.4      modelr_0.1.8      readxl_1.3.1      lifecycle_0.2.0
#> [21] munsell_0.5.0     gtable_0.3.0      cellranger_1.1.0  rvest_0.3.6
#> [25] htmlwidgets_1.5.2 evaluate_0.14     knitr_1.30        fansi_0.4.1
#> [29] highr_0.8         broom_0.7.1       Rcpp_1.0.5        scales_1.1.1
#> [33] backports_1.1.10  webshot_0.5.2     jsonlite_1.7.1    fs_1.5.0
#> [37] hms_0.5.3         digest_0.6.25     stringi_1.5.3     grid_4.0.3
#> [41] cli_2.0.2         tools_4.0.3       magrittr_1.5      crayon_1.3.4
#> [45] pkgconfig_2.0.3   ellipsis_0.3.1    xml2_1.3.2        reprex_0.3.0.9001
#> [49] lubridate_1.7.9   assertthat_0.2.1  rmarkdown_2.4     httr_1.4.2
#> [53] rstudioapi_0.11   R6_2.4.1          compiler_4.0.3

Created on 2020-10-13 by the reprex package (v0.3.0.9001)

A: The problem seems to come from your wrapper functions rather than kableExtra. If you inspect your df2 data.frame, you'll see that it includes a lot of \makecell calls with weird alignment.
These makecells are inserted by the kableExtra::linebreak function. To get the behavior you want, change your wrapper function with this:
linebreak(description, align='l')

This change of behavior was introduced in a recent commit to the kableExtra repository.
For reference, I think that a more idiomatic (and easier) way to use kableExtra in this context would be to avoid wrapping text yourself, and to specify a column width using the column_spec function.
Note that I use the df frame specifically, rather than go through the df2 like you did:
library(kableExtra)

mytable <- df %>%
  kbl("latex", booktabs=TRUE, escape=FALSE, align="lr") %>%
  kable_styling() %>%
  column_spec(1, width="2in")

writeLines(c(
  "\\documentclass{article}",
  "\\usepackage{graphicx}",
  "\\usepackage{makecell}",
  "\\usepackage{float}",
  "\\usepackage{booktabs}",
  "\\begin{document}",
  "\\pagestyle{empty}",
  mytable,
  "\\end{document}"),
  "test_table.tex"
)
tools::texi2pdf("test_table.tex", clean = TRUE)

This produces a document with this table:


text:
Q: Failed Installation of Docker plugin for Intellij Idea CE 2016.1 due to  After upgrading Intellij Idea to version 2016.1 I got problem with Docker plugin due to missed dependency org.jetbrains.plugins.remote-run

Plugin Error
              Problems found loading plugins:
              Plugin "Docker integration" was not loaded: required plugin "org.jetbrains.plugins.remote-run" not installed.
              Disable Docker integration
              Open plugin manager

Do you any ideas where I can find this plugin ?

A: As stated here, One of the guys developing IntelliJ IDEA 2016.1 thought that the remote-run plugin was available in the Community Edition for IntelliJ IDEA (which it isn't). That was this morning (Dated: 18th March 2016), hopefully he'll extract the dependency sometime soon and update the plugin.
TL;DR: Wait a little while until the Docker plugin has been updated, a Jetbrains Developer screwed up.

A: According to the changelog the

The Docker plugin has been improved in many ways

Reinstall it to assure missing dependencies are provided.


text:
Q: How to visible or invisible the xml items(text view, image view, video view) using programming i want to visible or invisible the XML file items...i am parsing data using XML and and putting values in image view, video view and text view..the thing i want to show in my application is that if there is only "text" available in xml item then it hide the other itemViews and if text + image is available then show image with text and hide the rest..
This is my XML FILE DATA
 <items>
    <item id="1">
   <MessageID>1</MessageID>
   <PublishDateTime>xxxxxxxx</PublishDateTime>
   <MessageText>xxxxxxxxx</MessageText>
   <MediaURL></MediaURL>
   <MediaMIMEType></MediaMIMEType>
 <MediaSize>0</MediaSize>
 <Likes>10</Likes>
 <Shares>5</Shares>
 <PublishedBy>xxxxxxxxxxxx</PublishedBy>
</item>
<item id="2">
<MessageID>2</MessageID>
<PublishDateTime>xxxxxxx</PublishDateTime>
<MessageText>xxxxxxxx xxx  x
xxxxxx.
xxxxxxx</MessageText>
<MediaURL>https://www.xxxx.org/wp-content/xxx/xxx/xx/xxxxx.jpg</MediaURL>
<MediaMIMEType>image/jpeg</MediaMIMEType>
<MediaSize>111649</MediaSize>
<Likes>100</Likes>
<Shares>95</Shares>
<PublishedBy>xxxx xxxxx xxxxx</PublishedBy>
</item>
<item id="3">
 <MessageID>3</MessageID>
 <PublishDateTime>xxxxxxxx</PublishDateTime>
 <MessageText>xxxxxxx xxxxxxx xx https://www.xxxxxxx.org/</MessageText>
 <MediaURL>https://xxxxxxx xxxxx.org/wp-content/xxxx/xxxx/xx/xxxxx.jpg</MediaURL>
 <MediaMIMEType>image/jpeg</MediaMIMEType>
 <MediaSize>76602</MediaSize>
 <Likes>64</Likes>
 <Shares>42</Shares>
 <PublishedByxxxxxxxxxxxx</PublishedBy>
 </item>
 <item id="4">
 <MessageID>4</MessageID>
 <PublishDateTime>1482227547</PublishDateTime>
 <MessageText></MessageText>
 <MediaURL>https://www.youtube.com/watch?v=xxxxxxxxx</MediaURL>
 <MediaMIMEType>video/mpeg</MediaMIMEType>
 <MediaSize></MediaSize>
 <Likes>6100</Likes>
 <Shares>550</Shares>
 <PublishedBy>xxxxxxxxxxxxx</PublishedBy>
 </item>
 <item id="5">
 <MessageID>5</MessageID>
 <PublishDateTime>xxxxxxxx</PublishDateTime>
 <MessageText>xxxxxxxxxxxxxxxxxxxxx xx x x xxxxx xxxx</MessageText>
 <MediaURL></MediaURL>
 <MediaMIMEType></MediaMIMEType>
 <MediaSize></MediaSize>
 <Likes></Likes>
 <Shares></Shares>
 <PublishedBy>xxxxxxxx</PublishedBy>
 </item>
 <item id="6">
 <MessageID>6</MessageID>
 <PublishDateTime>xxxxxxxx</PublishDateTime>
 <MessageText></MessageText>
 <MediaURL>https://www.youtube.com/watch?v=xxxxxx xx</MediaURL>
 <MediaMIMEType>video/mpeg</MediaMIMEType>
 <MediaSize></MediaSize>
 <Likes>10110</Likes>
 <Shares>8011</Shares>
 <PublishedBy>xxxxx xxxxxx</PublishedBy>
  </item>
  <item id="7">
  <MessageID>7</MessageID>
  <PublishDateTime>xxxxxx</PublishDateTime>
  <MessageText>xxx xxx xxx</MessageText>
  <MediaURL>https://xxxxxxxx.org/wp-content/uploads/media/xxxxxx.mp3</MediaURL>
  <MediaMIMEType>audio/mp3</MediaMIMEType>
  <MediaSize></MediaSize>
  <Likes></Likes>
  <Shares></Shares>
  <PublishedBy>xxxxxxxxxx</PublishedBy>
  </item>
  <item id="8">
  <MessageID>8</MessageID>
  <PublishDateTime>xxxx</PublishDateTime>
  <MessageText>xxxxxxxxxxxx x xxxxx xxxxx.
xxxxx.
</MessageText>
  <MediaURL></MediaURL>
  <MediaMIMEType></MediaMIMEType>
  <MediaSize></MediaSize>
  <Likes></Likes>
  <Shares></Shares>
  <PublishedBy>xxxxxxxxxx <tel:+xxxxxxxxxxx></PublishedBy>
  </item>

ReadRss.java
  public class ReadRss extends AsyncTask<Void, Void, Void> {
     Context context;

String address="https://xxxxx xxxxx.org/xxxxxxx/feed/";

ProgressDialog progressDialog;
ArrayList<FeedItem> feedItems;
RecyclerView recyclerView;
VideoView videoView;
View view;
MyAdapter adapter;
MyAdapter.MyViewHolder myViewHolder;

   URL url;
   Uri uri;

public ReadRss(Context context, RecyclerView recyclerView) {
    this.recyclerView=recyclerView;
    this.context = context;
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Loading...");

}

@Override
protected void onPreExecute() {
    progressDialog.show();
    super.onPreExecute();
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    progressDialog.dismiss();
    adapter=new MyAdapter(context,feedItems);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.addItemDecoration(new VerticalSpace(50));
    recyclerView.setAdapter(adapter);
  //  videoView.setVideoURI(uri);
}

@Override
protected Void doInBackground(Void... params) {
    ProcessXml(Getdata());

    return null;
}

private void ProcessXml(Document data) {
    if (data != null) {
        feedItems=new ArrayList<>();
        Element root = data.getDocumentElement();
        //Node channel = root.getChildNodes().item(1);
        NodeList items = root.getChildNodes();
        for (int i = 0; i < items.getLength(); i++) {
            Node cureentchild = items.item(i);
            if (cureentchild.getNodeName().equalsIgnoreCase("item")) {

                FeedItem item=new FeedItem();
                NodeList itemchilds = cureentchild.getChildNodes();

                for (int j = 0; j < itemchilds.getLength(); j++) {

                    Node cureent = itemchilds.item(j);
                    if (cureent.getNodeName().equalsIgnoreCase("title")) {
                        item.setTitle(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("MessageText")) {
                        item.setDescription(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("PublishDateTime")) {
                        item.setPubDate(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("link")) {
                        item.setLink(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("MediaURL")) {
                        item.setMediaURL(cureent.getTextContent());
                    } else if (cureent.getNodeName().equalsIgnoreCase("MediaMIMEType")) {
                        item.setMediaType(cureent.getTextContent());
                    } else {
                        //Nothing here, ignore other occurances of XML childern
                    }
                }

                Log.e("MediaType: ",item.getMediaType());
                Log.e("Media URL",item.getMediaURL());
                Log.e("Message text",item.getDescription());

                switch (item.getMediaType())
                   {

                       case "image/jpeg":

                           if(item.getDescription().isEmpty()){

                               Log.e("Message Text Empty","Only Media is Present");
                                    myViewHolder.Thumbnail.setVisibility(View.VISIBLE);
                               myViewHolder.Description.setVisibility(View.INVISIBLE);
                                   myViewHolder.Thumbnail.getParent()).setVisibility(View.VISIBLE);

                           }
                           if(item.getMediaURL().isEmpty()){
                               myViewHolder.Description.setVisibility(View.VISIBLE);
                               myViewHolder.Thumbnail.setVisibility(View.INVISIBLE);
                           }

                           break;
                       case "video/mpeg":

                           break;
                       default:

                   }
                feedItems.add(item);
            }

        }
    }
}

public Document Getdata() {
    try {
        url = new URL(address);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStream inputStream = connection.getInputStream();
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        return xmlDoc;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
       }
    }
}

custum_row_news_item.xml

 <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/cv"
app:cardBackgroundColor="#FFFFFF"
app:cardElevation="4dp">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/date_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView
        android:id="@+id/description_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/thumb_img"
        android:autoLink="web"
        android:linksClickable="true"
        android:visibility="visible"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/thumb_img"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:src="@drawable/test"
        android:visibility="visible"
        android:layout_below="@+id/date_text"
        android:layout_alignParentStart="true"
        android:layout_marginTop="17dp" />

    <VideoView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:id="@+id/videoView"
        android:visibility="invisible"
        android:layout_above="@+id/title_text"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#90f79a20"
        android:gravity="center"
        android:lines="1"
        android:text="Large Text"
        android:visibility="visible"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_above="@+id/description_text"
        android:layout_alignParentStart="true" />

      </RelativeLayout>
    </android.support.v7.widget.CardView>

MyAdapter.java
    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<FeedItem> feedItems;
Context context;
ReadRss readRss;
int USER=0,IMAGE=1;
public MyAdapter(Context context, ArrayList<FeedItem> feedItems){
    this.feedItems=feedItems;
    this.context=context;
}
@Override
public int getItemCount()
{
    return feedItems.size();
}

@Override
public int getItemViewType(int position) {
    return super.getItemViewType(position);
   /* if(feedItems.get(position) instanceof String ){
        ((TextView) feedItems.get(position));

    }*/
}

    public void bindDataToAdapter(){

}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater layoutInflator=LayoutInflater.from(parent.getContext());
    View view= layoutInflator.inflate(R.layout.custum_row_news_item,parent,false);
    View messageTextOnly=layoutInflator.inflate(R.layout.messageonly,parent,false);
    MyViewHolder holder=new MyViewHolder(view);
    //MyViewHolder holder1=new MyViewHolder(messageTextOnly);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    YoYo.with(Techniques.FadeInLeft).playOn(holder.cardView);
    final FeedItem current=feedItems.get(position);
    holder.Title.setText(current.getTitle());
    holder.Description.setText(current.getDescription());
    holder.Date.setText(current.getPubDate());
   if(current.getMediaURL().isEmpty()){
    holder.Thumbnail.setImageResource(R.drawable.butterfly);
   }else {
        Picasso.with(context).load(current.getMediaURL()).into(holder.Thumbnail);
    }
    //Picasso.with(context).load(current.getVideoUrl()).into((Target) holder.videoView);
   /* holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent( context,NewsDetail.class);
            intent.putExtra("Link",current.getLink());
            context.startActivity(intent);
        }
    });*/

}

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView Title,Description,Date;
    ImageView Thumbnail;
    CardView cardView;
    VideoView videoView;

    public MyViewHolder(View itemView) {
        super(itemView);
        Title= (TextView) itemView.findViewById(R.id.title_text);
        Description= (TextView) itemView.findViewById(R.id.description_text);
        Date= (TextView) itemView.findViewById(R.id.date_text);
        Thumbnail= (ImageView) itemView.findViewById(R.id.thumb_img);
        cardView= (CardView) itemView.findViewById(R.id.cv);
       // videoView=(VideoView)itemView.findViewById(R.id.videoView);
        }
     }
 }

MainActivity.java
  public class MainActivity extends AppCompatActivity {

private Toolbar toolBar;
private Menu menu;

ProgressBar mnuProgressBar;
RecyclerView recyclerView;
VideoView videoView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolBar=(Toolbar)findViewById(R.id.tool_bar);
    setSupportActionBar(toolBar);
    toolBar.setTitle(R.string.app_name);
    mnuProgressBar= (ProgressBar) findViewById(R.id.progressBar);
    recyclerView= (RecyclerView) findViewById(R.id.recyclerview);
   // videoView=(VideoView)findViewById(R.id.videoView);
    ReadRss readRss=new ReadRss(this,recyclerView);
    readRss.execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu=menu;
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return super.onCreateOptionsMenu(menu);
    }
    }

FeedItem.java
public class FeedItem {
String title;
String link;
String description;
String pubDate;
String mediaUrl;
String mediaType;
String vtViewType;

public String getMediaURL() { return mediaUrl;     }

public void setMediaURL(String mediaUrl) { this.mediaUrl = mediaUrl; }

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getLink() {
    return link;
}

public void setLink(String link) {
    this.link = link;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getPubDate() {
    return pubDate;
}

public void setPubDate(String pubDate) {
    this.pubDate = pubDate;
}

public String getMediaType() {
    return mediaType;
}

public void setMediaType(String mediaType) {
    this.mediaType = mediaType;
}

public String getViewType() {
    return vtViewType;
}

public void setViewType(String viewType) {
    this.vtViewType = viewType;
    }
 }

All my links in xml file is working fine..please check the code and give me solution to how to Visible or Invisible the items and show in my activity...thanx in advace

A: You just need to set visibility to your views conditionally. For instance if value of a certain text view is not null set its visibility to visible else gone/invisible. setvisiblity is the property you need.


text:
Q: Fetch elements from a dictionary faster I have a dictionary containing a mapping from color code to class index like the following:
color_to_class_idx = {(0, 0, 0) : 0, (180, 120, 120): 1, (80, 50, 50): 2, (140, 140, 140): 3, (4, 250, 7): 4, (150, 6, 51): 5, (0, 102, 200): 6, (233, 255, 7): 7, (255, 31, 0): 8, (120, 120, 120): 9}

Now, I have a  list of color code values like the following:
list_ = [(0, 0, 0) , (80, 50, 50), (255, 255, 255)]

I would like to get another list with the class_idx. Note that, in the list_ there can be color codes for which are not present in the keys of color_to_class_idx. For these cases, it should have a default value (e.g. 0). So, the final output would look like - [0, 2, 0]
The list_ could be dimension 345600. So, speed matters for me. Following is the my implementation:
values = np.array([color_to_cls_idx.get(key, 0) for key in segmented_img_list])

But it is slow.
TIA

A: You can do a little bit better (by ~50%?) by converting most of your data structures to Numpy arrays. Here is an array of dictionary values, addressed by the color coordinates. Note that all elements that are not explicitly updated are 0:
lookup = np.zeros((256, 256, 256), dtype=int)
for i in color_to_class_idx:
    lookup[i] = color_to_class_idx[i]

Here is the result array:
result = np.zeros(len(segmented_img_list))

And here is the lookup loop:
for i,key in enumerate(segmented_img_list):
    result[i] = lookup[key]


text:
Q: accepts_nested_attributes_for does not update nested table I have 2 tables cardapios and produtos, and when I want to update cardapios accepts_nested_attributes_for does not update produtos and _destroy = "1" does not delete produto. Follow bellow my code:
class Cardapio < ActiveRecord::Base
  mount_uploader :imagem, CardapioImagemUploader

  belongs_to :empresa
  has_many :itens
  has_many :cardapios_produtos
  has_many :cardapios_eventos
  has_and_belongs_to_many :eventos
  has_and_belongs_to_many :produtos

  accepts_nested_attributes_for :cardapios_produtos, reject_if: proc { |a| a[:produto_id].blank? or a[:preco].blank? }, allow_destroy: true

  def update
    authorize @cardapio
    atualiza_imagem

    binding.pry
    if @cardapio.update_attributes(cardapio_params)
      if params[:parent_controller].present?
        redirect_to controller: params[:parent_controller], action: params[:parent_action], id: params[:parent_id].to_i, notice: 'Cardapio was successfully updated.'
      else
        redirect_to cardapios_path, notice: 'Cardapio was successfully updated.'
      end
    else
      render :edit
    end
  end

def cardapio_params
  params.require(:cardapio)
        .permit(
          :nome, :empresa_id,
          :imagem, :imagem_crop_x, :imagem_crop_y, :imagem_crop_w, :imagem_crop_h,
          evento_ids: [],
          cardapios_produtos_attributes: [
            :id, :cardapio_id, :produto_id, :preco, :destaque, :_destroy
          ]
        )
end

Bellow we have the result of binding.pry before update_attributes:
[1] pry(#<CardapiosController>)> cardapio_params
=> {"nome"=>"Cardapio BDD Light",
 "empresa_id"=>"3",
 "imagem_crop_x"=>"",
 "imagem_crop_y"=>"",
 "imagem_crop_w"=>"",
 "imagem_crop_h"=>"",
 "evento_ids"=>["", "1"],
 "cardapios_produtos_attributes"=>
  {"0"=>{"id"=>"4", "produto_id"=>"1", "preco"=>"5", "destaque"=>"0", "_destroy"=>"0"},
   "1"=>{"id"=>"5", "produto_id"=>"7", "preco"=>"20", "destaque"=>"1", "_destroy"=>"0"},
   "2"=>{"id"=>"22", "produto_id"=>"12", "preco"=>"13.5", "destaque"=>"0", "_destroy"=>"1"},
   "3"=>{"produto_id"=>"", "preco"=>"", "destaque"=>"0", "_destroy"=>"0"},
   "4"=>{"produto_id"=>"", "preco"=>"", "destaque"=>"0", "_destroy"=>"0"},
   "5"=>{"produto_id"=>"", "preco"=>"", "destaque"=>"0", "_destroy"=>"0"},
   "6"=>{"produto_id"=>"", "preco"=>"", "destaque"=>"0", "_destroy"=>"0"},
   "7"=>{"produto_id"=>"", "preco"=>"", "destaque"=>"0", "_destroy"=>"0"}}}

May anybody help me?

A: I think the problem is in this part has_and_belongs_to_many :produtos in model.  According to this documentation http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
There is on one-to-one and one-to-many.
You should use has_many, or has_one.


text:
Q: Firebase is firing a database leak I added firebase inside my app to get some special events like when users open and close their app.
The problem is that every time I launch the app, it crashes right away. It started to happen when I added firebase and when I comment my Firebase code, it's working again, so now I'm pretty sure it's a problem with firebase.
The problem seems to be happening when the onForeground() is called. I tried to put it on a new Thread or call it in a Handler but it keeps crashing...
Here is the stack:
10-28 16:46:26.106 27724-27732/com.package.custom E/System: Uncaught exception thrown by finalizer
10-28 16:46:26.107 27724-27732/com.package.custom E/System: java.lang.IllegalStateException: The database '/data/user/0/com.package.custom/databases/google_app_measurement_local.db' is not open.
                                                                  at android.database.sqlite.SQLiteDatabase.throwIfNotOpenLocked(SQLiteDatabase.java:2169)
                                                                  at android.database.sqlite.SQLiteDatabase.createSession(SQLiteDatabase.java:365)
                                                                  at android.database.sqlite.SQLiteDatabase$1.initialValue(SQLiteDatabase.java:84)
                                                                  at android.database.sqlite.SQLiteDatabase$1.initialValue(SQLiteDatabase.java:83)
                                                                  at java.lang.ThreadLocal$Values.getAfterMiss(ThreadLocal.java:430)
                                                                  at java.lang.ThreadLocal.get(ThreadLocal.java:65)
                                                                  at android.database.sqlite.SQLiteDatabase.getThreadSession(SQLiteDatabase.java:359)
                                                                  at android.database.sqlite.SQLiteProgram.getSession(SQLiteProgram.java:101)
                                                                  at android.database.sqlite.SQLiteQuery.setLastStmt(SQLiteQuery.java:96)
                                                                  at android.database.sqlite.SQLiteQuery.close(SQLiteQuery.java:111)
                                                                  at android.database.sqlite.SQLiteCursor.close(SQLiteCursor.java:300)
                                                                  at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:366)
                                                                  at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:202)
                                                                  at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:185)
                                                                  at java.lang.Thread.run(Thread.java:818)

Here is a part of my AnalyticsHelper class:
public class AnalyticsHelper
{
    //...

    /**
     * Hook called when the app switch to foreground mode
     */
    public static void onForeground()
    {
        Log.d(TAG, "FOREGROUND");

        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, AnalyticsCategories.CATEGORY_LIFECYCLE_ACTION_FOREGROUND);
        CustomApplication.getAnalytics().logEvent(AnalyticsCategories.CATEGORY_LIFECYCLE, bundle);
    }

 //...
}

Here is the call of the AnalyticsHelper in the activity:
public class MainActivity extends AppCompatActivity
{
 @Override
    protected void onResume()
    {
        super.onResume();

        //...

        AnalyticsHelper.onForeground();
    }

}

And here is the part of the custom Application class:
public class CustomApplication extends Application
{
    private static final String TAG = "CustomApplication";

    private static CustomApplication sApplication;

    public static CustomApplication get()
    {
        return sApplication;
    }

    public static FirebaseAnalytics getAnalytics()
    {
        return get().getFirebaseAnalytics();
    }

    @Override
    public void onCreate()
    {
        super.onCreate();

        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

        sApplication = this;
    }

    /**
     * Gets the default {@link Tracker} for this {@link Application}.
     *
     * @return tracker
     */
    public FirebaseAnalytics getFirebaseAnalytics()
    {
        if (mFirebaseAnalytics == null)
        {
            mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        }

        return mFirebaseAnalytics;
    }
}

I searched all the afternoon and nothing came out, please help..
Edit #1 (build.gradle):
apply plugin: 'com.android.application'
android {
    signingConfigs {
        release {
            keyAlias '##########'
            keyPassword '##########'
            storeFile file('##########')
            storePassword '##########'
        }
    }
    compileSdkVersion 25
    buildToolsVersion '24.0.2'
    defaultConfig {
        applicationId "com.custom.app"
        minSdkVersion 18
        targetSdkVersion 25
        android.applicationVariants.all { variant ->
            def versionPropsFile = file('src/main/res/raw/version.properties')
            if (versionPropsFile.canRead())
            {
                def Properties versionProps = new Properties()
                versionProps.load(new FileInputStream(versionPropsFile))
                def code = versionProps['code'].toInteger() + 1
                versionProps['code'] = code.toString()
                def version = versionProps['version']
                versionProps.store(versionPropsFile.newWriter(), null)
                versionCode code
                versionName version
            }
            else
            {
                throw new GradleScriptException('Cant access version.properties');
            }
        }
        signingConfig signingConfigs.release
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            debuggable true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "boolean", "EXPORT_EXTERNAL_STORAGE", "true"
        }
        debug {
            debuggable true
            buildConfigField "boolean", "EXPORT_EXTERNAL_STORAGE", "true"
        }
    }
    productFlavors {
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/commons-net-3.3.jar')
    //Debug
    compile files('libs/commons-lang3-3.5.jar')
    compile files('libs/joda-time-2.9.5.jar')
    compile project(':android-ble-module')
    debugCompile project(path: ':android-log-module', configuration: 'debug')
    releaseCompile project(path: ':android-log-module', configuration: 'release')
    compile project(':android-location-module')
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.9.5'
    compile 'com.android.support:design:25.0.0'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.android.support:preference-v14:25.0.0'
    compile 'com.google.android.gms:play-services-gcm:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-identity:9.8.0'
    compile 'com.google.firebase:firebase-analytics:9.8.0'
}
apply plugin: 'com.google.gms.google-services'

A: Please move to latest version of firebase SDK. Firebase solved this memory leak issue in their updated sdk. In this case replace this line
compile 'com.google.firebase:firebase-analytics:9.8.0'

with below line.
compile 'com.google.firebase:firebase-analytics:11.0.1'


text:
Q: How to import model with associations using rails_admin_import gem? I'm trying to import my database, which have Project and Technology models (project has many technologies). Each project should have at least 1 technology. I use rails_admin_import gem for this task. As far as I understand, during project import gem is supposed to find associations of the model (technologies in my case) and connect them to model if they exist.
Everything is fine when I import technologies, but as soon as I'm importing projects, I receive this error for each of the projects:
Failed to create Project_1: Technologies minimum allowed: 1

I tried to import projects before importing technologies and after that, added to both of them mapping key, but nothing changed:
config.model 'Project' do
  import do
    mapping_key :name
    include_all_fields
  end
end
config.model 'Technology' do
  import do
    mapping_key :name
    include_all_fields
  end
end

Maybe anyone can help me and say what am I doing wrong?
UPD: The problem is that I exported data using default rails_admin export, which saves data in csv like that:

But rails_admin_import expects data in this format:

So I need to change my question. How should I configure rails_admin so that it would export data in a format accepted by rails_admin_import?

A: I found a way to do this, but probably not the best one.
I used before_import_associations method of rails_admin_import to create needed technologies key manually.
def before_import_associations(record)
  record[:technologies] = record[:name_technologies].split(',')
end


text:
Q: XQuery multivalued fields (IDREFS) In my XML file I have this element
 <subtopics>tr1 tr2</subtopics>

which I retrieve in XQuery using the following query
doc("data.xml")/expert_schema/topic/data(subtopics)

How can I retrive tr1and tr2separately?

A: If performance is not a problem, then you can simply tokenize the values as you query them:
doc("data.xml")/expert_schema/topic/tokenize(subtopics, '\s')


text:
Q: Using AtomicReference to access Object from another thread I have a couple of ideas how to solve this problem, but I really would like to know the underlying reason for such a behavior. I have a class called ConferenceManager which is responsible for receiving callbacks from another thread(not main thread):
ConferenceManager(simplified):
public class ConferenceManager implements IConferenceManager {

private final AtomicReference<CallState> mCallStateHolder = new AtomicReference<CallState>(
            CallState.IDLE);

// excecuted on main thread
public boolean call(Context context, String peerId, String peerName, boolean isAudioCall) {
   // call the user, set the AtomicReference and start CallActivity
   // ...

   mCallStateHolder.compareAndSet(CallState.IDLE,
                CallState.PLACE_CALL);
   startCallActivity();
 }

// called from backgroundthread when call ends
public void onCallFinished() {
   // show toast that call has ended and set the AtomicReference
   // ...

   mCallStateHolder.compareAndSet(CallState.PLACE_CALL,
                CallState.IDLE);
}

}
CallState enum:
public enum CallState {
    PLACE_CALL, RECEIVE_CALL, CONFERENCE, IDLE, RECEIVE_CALL_FAKE, PLACE_CALL_FAKE
}

What CallActivity does in onResume() is checks whether mCallStateHolder is IDLE or not and if it is IDLE CallActivity will call finish(). The reason for this is that sometimes onCallFinished() might be executed very fast before onResume() is called, for instance if user is offline background thread will emmidietly call onCallFinished(). Since I use atomic reference I expect that if this happens the CallActivity will terminate in onResume().
So the problem is: despite using AtomicReference and excecuting onCallFinished() before onResume() the mCallStateHolder is still PLACE_CALL inside onResume(). So the main thread didn't see the changes? I used android studio debugger to check on it. The flow of the code using debugger is as follows:

*

*MainThread - call() is called, call is started in background, and activity intent is sent

*BackgroundThread - onCallFinished() is called and variable is set back to IDLE

*MainThread - Activity onResume() is called and variable is PLACE_CALL


text:
Q: HERE-API Symantec-Certificates no longer work in Chrome I am using Google Chrome (Dev/unstable Edition), specifically
    v65.0.3325.31 (Official Build) dev (64-bit)
to access a freshly created  HERE app.
(It is actually just a layer in a map, displaying a few points on a map / infographics).
A link to a single tile looks like this (I've removed my  credentials from the link, sorry about that):
https://1.aerial.maps.cit.api.here.com/maptile/2.1/maptile/newest/hybrid.day/12/2357/2359/256/png8?app_id=...o&app_code=...&lg=eng
In Chrome I can view the tile/image after defining a security exception.
According to this Sept. 2017 post on the Google Security Blog ("Chrome's Plan to Distrust Symantec Certificates"), Google will no longer (voluntarily) load any data from https- Website that come with a certificate Issued by Symantec (or Digicert, the company Symantec sold the business unit to)
For each tile, now I get warnings like these

Your connection is not private Attackers might be trying to steal your
  information from 1.aerial.maps.cit.api.here.com (for example,
  passwords, messages, or credit cards). Learn more
  NET::ERR_CERT_AUTHORITY_INVALID

What should I do now?
More Background: German Blog post from early Feb 2018
As a workaround I am loading the map tiles via http instead of https, but now I get "Mixed content warnings"
Is there a better workaround?

A: The issue should have been resolved after the SSL certificates were updated in the HERE APIs to move away from Symantec Certificates.


text:
Q: Namenode not coming out of safemode I am trying to put some dummy file in HDFS, but it is showing foll. error:

$ hadoop fs -put dummy.txt /user/hadoop
  put: org.apache.hadoop.hdfs.server.namenode.SafeModeException: Cannot create file/user/hadoop/dummy.txt. Name node is in safe mode.

For this I have tried the command:
$ hadoop dfsadmin -safemode leave
and tried to execute the previous hadoop put command . But it is again giving me the same error .
Name node is not coming out of safemode.
Any help on this please.

A: Try formatting your namenode .
 hadoop namenode -format

And then
hadoop dfsadmin -safemode leave

A: Inside docker Hadoop container bash shell, to create a file
/usr/local/hadoop/bin/hdfs namenode -format
/usr/local/hadoop/bin/hdfs dfsadmin -safemode leave
/usr/local/hadoop/bin/hdfs dfs -mkdir /user/test/


text:
Q: bitbucket on my own server I want to have something like bitbucket.org or github (but for mercurial!) on my VDS. I don't need full functionality, but I need it being able to serve repositories, accept changes (with auth!) and creating new repos in one-two clicks in web interface. What can I use? Thanks

A: Hgwebdir running in a web server (comes with mercurial) does everything except let you create the new repos with a click, which you can very easily do with a simple script you can put right in the hgwebdir footer.

A: I have used bitbucket.org but I also wanted an in house DVCM server for my web development team, so we went with Redmine. This is tested and installed easy using BitNami images, http://bitnami.org/stack/redmine

A: I've not tried it yet, but RhodeCode seems to have all the features you'd ever want from a web based repository manager.
You can create new repositories, fork current repositories and it allows you to set up user authentication and access rights.

A: If you have money, bitbucket has an hosted version (just ask Jesper for a quote).

A: As described in the article  Publishing Repositories in the mercurial wiki, mercurial has different way for publishing repositories (hg serve, ssh, hgwebdir, hgweb, ...).
Since you need multiple repositories with push/pull authentication then you should go for hgwebdir (also described here).
After setting up hgwebdir, apart from pushing/pulling from the repositories, you will also have a web interface that will look like, for example, the suckless.org code repository.
As mentioned by Ry4an you can't create a new repository via the web interface.

A: For your needs you might want to take a look at gitblit
It is fairly basic and simple. It provides web-UI so you can manage as many repos as you need. However I found out that they don't have per branch permissions out of the box (requires some ground work with groovy scripts). On a flip side if it doesn't bother you, then it might be it!
Cheers mate!


text:
Q: ios Swift Chart issue I use Charts iOS library(https://github.com/danielgindi/Charts) and I have this code :
import UIKit
import Charts

    class ChartsViewController: UIViewController , ChartViewDelegate{

        var lineChartView: LineChartView?
        let months = ["Jan" , "Feb", "Mar", "Apr", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec"]
        let dollars1 = [1453.0,2352,5431,1442,5451,6486,1173,5678,9234,1345,9411,2212]

        override func viewDidLoad() {
            super.viewDidLoad()

            self.lineChartView = LineChartView(frame: CGRectMake(50, 70, 300, 300))
            self.lineChartView!.delegate = self
            self.lineChartView!.descriptionText = "Tap node for details"
            self.lineChartView!.drawGridBackgroundEnabled = false
            self.lineChartView!.descriptionTextColor = UIColor.whiteColor()
            self.lineChartView!.noDataText = "No data provided"
            setChartData(months)
            self.view.addSubview(self.lineChartView!)

        }
        func setChartData(months : [String]) {

            var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
            for var i = 0; i < months.count; i++ {
                yVals1.append(ChartDataEntry(value: dollars1[i], xIndex: i))
            }

            let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "First Set")
            set1.lineWidth = 10.0
            set1.circleRadius = 0.0 // the radius of the node circle
            set1.fillColor = UIColor.redColor()
            set1.highlightColor = UIColor.yellowColor()
            set1.drawCircleHoleEnabled = false
            set1.drawVerticalHighlightIndicatorEnabled = false
            var dataSets : [LineChartDataSet] = [LineChartDataSet]()
            dataSets.append(set1)
            let data: LineChartData = LineChartData(xVals: months, dataSets: dataSets)
            data.setValueTextColor(UIColor.whiteColor())
            self.lineChartView!.data = data
        }

and I get this :
https://postimg.org/image/6z6nk5nkn/
My problem is this :
I want to delete the grid on background(vertical and horizontal lines) but I dont be able because I dont find anything in the official library documentation.
Can you help me?

A: You can use this code to disable the grid :
lineChartView.xAxis.drawGridLinesEnabled = false
lineChartView.leftAxis.drawGridLinesEnabled = false

A: self.lineChartView.leftAxis.drawGridLinesEnabled = false
self.lineChartView.xAxis.drawGridLinesEnabled = false

will do the job.


text:
Q: Custom Input HTML with CakePHP's FormHelper I'm trying to use CakePHP's form helper to generate some input elements.
The HTML I am trying to generate is:

    LabelText:

        <input name="data[User][email_address]" type="text" value="">

Ive had a look through the Cake documentation (Using 2.1) and I can't find enough information on how to do this.
It looks like I need to use the format option on the input method, but can't figure out how to get it right. Especially concerned about the div surrounding the input field with a class name on it..
E.g. Ive tried something like this:
echo $this->Form->input('email_address', array(
                                                "input" => array('attributes' => array('wrap' => 'div','class' => 'formRight'))));

But this doesnt change any of the markup and just throws this error:
   Notice (8): Array to string conversion [CORE\Cake\View\Helper.php, line 459]
So my question is how can I get this form helper to create that markup?
Any help much appreciated

A: You're over-thinking it. (No worries, we all do).  Just remember, CakePHP is all about making things easier for you (among other things) - if you're struggling with trying to force Cake to do something for you, just remember, you can fall back to the basics - it's just PHP/HTML after-all.

    LabelText:

        <?php echo $this->Form->input('email_address', array(
            'div'=>false, 'label'=>false)); ?>

You should use the Form helper for your forms when possible, but you don't have to use all of it's presets like surrounding divs & labels.  In the case above, just tell it you don't want the div, and wrap it with a div yourself.
If you don't want
s or s around any inputs, you can also set the form's inputDefaults:
$this->Form->create('Whatever', array(
    'inputDefaults' => array('label'=>false, 'div'=>false)
));

A: If you have a lot of fields, you can use Jquery.
php:
echo $this->Form->input('email_address', array('class' => 'formRow'));

Jquery:
$(".formRow").each(function() {
    $(this).wrapInner( "

");
    $(this).find("label").prependTo(this);
    $(this).append('

');
});


text:
Q: Dealing With Java Default Level Access Specifiers I've seen some code in a project recently where some fields in a couple classes have been using the default access modifier without good reason to.  It almost looks like a case of "oops, forgot to make these private".  Since the classes are used almost exclusively outside of the package they are defined in, the fields are not visible from the calling code, and are treated as private.  So the mistake/oversight would not be very noticeable.
However, encapsulation is broken.  If I wanted to add a new class to the existing package, I could then mess with internal data in objects using fields with default access.
So, my questions:

*

*Are there any best practices concerning default access specifiers that I should be aware of?  Anything that would help prevent this type of accident from re-occurring?

*Are are any annotations which might say something to the effect of "I really meant for these to be default access"?

*Using CheckStyle, or any other Eclipse plugins, is there any way to flag instances of default fields, or disallow any not accompanied by, say, a "//default access" comment trailing them?

A: In terms of style, I have seen some style guides which recommend putting "package" in a comment to denote that it was intentional.  Like this:
/*package*/ int myInt;

It's unfortunate that the Java language spec doesn't allow use of "package" explicitly; after all, it's already a reserved keyword!

A: I would suggest running the UCDetector on the code base. From the main page:

UCDetector creates markers for the following problems, which appear in the eclipse problem view:

*
*Unnecessary (dead) code

* Code where the visibility could be changed to protected, default or private

* Methods of fields, which can be final

A: By convention, you should not define your class in his package. The author is reasonable to make that assumption, and he should be the only one who accesses these package variables.
If you choose to break that convention, you are allowed to, and you should know what you are doing. You know what else you can do to mess around with the design, since you have the source? Everything!
The access level is an honor system after all. It is there to help you, but it's not your dictator.
JDK classes use package level variables extensively. And it's my favorite too. public and protected have important roles for public APIs, private when you are really paranoid and you don't even trust yourself. For everything else - default/package level, which allows an author to freely access, but difficult for users to access.
"How can an author be so arrogant and think that he doesn't have to mark his private variables as private? He is doing his job wrong!" - well, who are you and how is that your business?
Obviously Java creators thought that is should be the most frequently used leve, therefore we should save some key taps, and don't impose a keyword on it.


text:
Q: md-toolbar not rendering as material toolbar using angular material I'm using angular material v1.1.0 and trying to create a simple toolbar. I've taken the code from angular material demo, but the toolbar being rendered, instead getting individual elements. Not sure what I'm missing.

var app = angular.module('app', ['ngMaterial', 'ngRoute']);

        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>My App</title>

     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
     <link href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">

        <md-content>
         <md-toolbar>

           <md-button class="md-icon-button" aria-label="menu">
            <md-icon md-font-set="material-icons">menu</md-icon>
           </md-button>

            My App

           <md-button class="md-icon-button" aria-label="menu">
            <md-icon md-font-set="material-icons">whatshot</md-icon>
           </md-button>
           <md-button class="md-icon-button" aria-label="menu">
            <md-icon md-font-set="material-icons">share</md-icon>
           </md-button>
           <md-button class="md-icon-button" aria-label="menu">
            <md-icon md-font-set="material-icons">file_download</md-icon>
           </md-button>
           <md-button class="md-icon-button" aria-label="menu">
            <md-icon md-font-set="material-icons">thumb_up</md-icon>
           </md-button>

         </md-toolbar>
        </md-content>

A: You forgot to add rel="stylesheet" while loading the angular-material css. Working pen here:
http://codepen.io/anon/pen/jVYEdM


text:
Q: Как задать межбуквенный интервал в TextView? У меня есть дизайн, в нем используются шрифты. У меня есть эти шрифты, но проблема в том, что шрифты имеют межбуквенный интервал. Я нашел некоторые статьи в которых советуют переопределить TextView, сделал это, теперь я могу задавать этот интервал в  dpi. Но он работает безумно криво, например, платный скрипт фотошопа мне показал:
FONT
Block Berthold Regular (bold)
19.2 px
#FFFFFF / rgb(255,255,255)
Letter spacing: +2.69 px
Line height: 36.48 px

картинка в расширении 1440 на 2560 пикселей. это xxxhdpi. чтобы все выглядело идентично мне пришлось задать интервал -0.73dp  я не понимаю как решить эту задачу.
вот мой TextView:
public class MyTextView extends TextView {
    private float letterSpacing = 0.0f;
    private CharSequence originalText = "";
    private Typeface typeface;

    public MyTextView(Context context) {
        this(context, null);
        isInEditMode();
    }

    public MyTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        isInEditMode();
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray attributesArray = getResources().obtainAttributes(attrs, R.styleable.MyTextView);
        letterSpacing = attributesArray.getDimension(R.styleable.MyTextView_letterSpacing, 0.0f);
        String fontName = attributesArray.getString(R.styleable.MyTextView_fontName);
        if(!this.isInEditMode()) {
            if (null == fontName) {
                typeface = Fonts.getBlockBertholdRegular(context);
            } else {
                typeface = Fonts.get(context, fontName);
            }
            super.setTypeface(typeface);
        }
        originalText = super.getText();
        applyLetterSpacing();
        this.invalidate();
    }

    public float getLetterSpacing() {
        return letterSpacing;
    }

    public void setLetterSpacing(float letterSpacing) {
        this.letterSpacing = letterSpacing;
        applyLetterSpacing();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        applyLetterSpacing();
    }

    @Override
    public CharSequence getText() {
        return originalText;
    }

    private void applyLetterSpacing() {
        if (this == null || this.originalText == null) return;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < originalText.length(); i++) {
            String c = "" + originalText.charAt(i);
            builder.append(c.toUpperCase());
            if (i + 1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if (builder.toString().length() > 1) {
            for (int i = 1; i < builder.toString().length(); i += 2) {
                finalText.setSpan(new ScaleXSpan((letterSpacing + 1) / 10), i, i + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        super.setText(finalText, BufferType.SPANNABLE);
        if(!this.isInEditMode()) {
            super.setTypeface(typeface);
        }
    }
}

A: Может пока не стоит ничего переопределять.
Как насчет этого android:textScaleX свойства и метода setTextScaleX(float) для обычного TextView?