text:
Q: Exact symbolic area of an intersection of two regular pentagons with parameters The question of finding the area of intwrsection of two regions with parameters has been answered here using and RegionIntersection with delimeter GenerateConditions -> All. More sophisticated example, for which Mathematica does not return any answer, is as follows.
Consider a vertices of a regular pentagon
regulPen[i_] := {Cos[-((2 \[Pi])/5) + (2 \[Pi])/5 i], Sin[-((2 \[Pi])/5) + (2 \[Pi])/5 i]};

We now rotate this pentagon by $\pi/5$, forming a new pentagon with vertices
regulPenShif[i_] := {Cos[-(\[Pi]/5) + (2 \[Pi])/5 i], Sin[-(\[Pi]/5) + (2 \[Pi])/5 i]};

The area of intersection of these pentagons is $\frac12 \sqrt{\frac52(5+\sqrt{5})}$, which is confirmed by Mathematica. Now we shift the center of the second pentagon into the point $\{p,q\}$, the area of intersection should now depend on $\{p,q\}$, however
Area[RegionIntersection[
  Polygon[{regulPen[1],
           regulPen[2],
           regulPen[3],
           regulPen[4],
           regulPen[5]}],
  Polygon[{regulPenShif[1] + {p, q},
           regulPenShif[2] + {p, q},
           regulPenShif[3] + {p, q},
           regulPenShif[4] + {p, q},
           regulPenShif[5] + {p, q}}]],
  GenerateConditions -> All]

returns itself. How to refine the code such that Mathematica will solve that indeed?

A: You can't get an exact symbolic area of the intersection of two regular pentagons with parameters when the parameters are symbolic because Area is a computational function like NIntegrate and not symbolic expression manipulator like Integrate. Even the result you show isn't symbolic; it is just exact.
The best we can do is define a numeric evaluator for the area of the  intersection. Like so:
regulPen[i_] := {Cos[-((2 π)/5) + (2 π)/5 i], Sin[-((2 π)/5) + (2 π)/5 i]}
regulPenShif[i_] := {Cos[-(π/5) + (2 π)/5 i], Sin[-(π/5) + (2 π)/5 i]}
area[{p_?NumericQ, q_?NumericQ}] :=
With[
  {poly =
     Polygon[{regulPen[1], regulPen[2], regulPen[3], regulPen[4], regulPen[5]}]},
  area[{p_?NumericQ, q_?NumericQ}] :=
    N @
      Area[
        RegionIntersection[
          poly,
          Polygon[
           {regulPenShif[1] + {p, q}, regulPenShif[2] + {p, q},
            regulPenShif[3] + {p, q}, regulPenShif[4] + {p, q},
            regulPenShif[5] + {p, q}}]]]]

Then we can make a demonstration allowing us to see one the pentagons shifting around while the area of intersection is computed. Like so:
With[
  {poly =
     Polygon[{regulPen[1], regulPen[2], regulPen[3], regulPen[4], regulPen[5]}],
   spacer = Invisible["mmmmmmmmmmmm"]},
  Manipulate[
    Column[
      {Graphics[
         {EdgeForm[Black], FaceForm[],
          poly,
          Polygon[
            {regulPenShif[1] + pq, regulPenShif[2] + pq, regulPenShif[3] + pq,
             regulPenShif[4] + pq, regulPenShif[5] + pq}]},
         ImageSize -> Medium],
       Style[Row[{"Shift: ", pq, "    Area: ", area[pq]}], "SR"]},
       Center],
    {{pq, {0, 0}, Style[Row[{spacer, "Shift "}], 16]}, {-1, -1}, {1, 1}, {.05, .05},
      ImageSize -> {175, 175}},
    ControlPlacement -> Bottom]]

A: Your code works for concrete p,q in 12.2, e.g.
p = -1/4; q = 1/2; Area[RegionIntersection[Polygon[{regulPen[1], regulPen[2],
regulPen[3], regulPen[4],regulPen[5]}],Polygon[{regulPenShif[1] + {p, q}, regulPenShif[2] +{p, q},
regulPenShif[3] + {p, q}, regulPenShif[4] +{p, q}, regulPenShif[5] + {p, q}}]]]

1/2 (1/4 (1 - Sqrt[5]) ((Sqrt[5 + Sqrt[5]] (-4 Sqrt[2] + Sqrt[10]))/( 4 (-5 + Sqrt[5])) + 1/4 (2 - Sqrt[2 (5 + Sqrt[5])]) +..

, but a long output is not very useful.


text:
Q: Where do I write a JSON file I have spent a few hours reading about JSON online and have read a JSON for beginners text book. However, I still can not find out how to start using JSON to store data. Is there a JSON download or interface that is used or do you store JSON files in other languages like python?
I understand JSON is a file format, but where do I write and store JSON files?
My question is different than the suggested duplicate because it is more narrow. My question specifically asks "where do I write a JSON file?", as opposed to "how do I use JSON?"
DISCLAIMER I'm brand new to coding and don't have a teacher to consult to ask questions. I am asking this question because I am genuinely trying to learn and this information is not available online, nor in the textbook that I purchased.
Thank you in advance for your help!

A: JSON is a file format for storing and passing data between, you can create a JSON file in any text editor, it should follow the JSON format that's it , you can validate the format of your JSON using online validators, I usually use https://jsonlint.com/, JSON is a standard which is supported by almost every programming language, you have API in every language to support it.
you can find examples of JSON data here http://json.org/example.html
just copy them and store them in a file with extension ".json", you can read them from your program by specifying the path where the file is present on the file system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do I need to run ldconfig everytime I put .so library into directories like /usr/local/lib if set by config files in /etc/ld.so.conf.d/? I am running centos 6.10 in docker. As is described in the title, I set /usr/local/lib and /usr/local/lib64 in a conf file in /etc/ld.so.conf.d/. I need to run ldconfig everytime when I put .so library into /usr/local/lib or it will not be found (when compiling Python 3). However, setting LD_LIBRARY_PATH to /usr/local/lib:/usr/local/lib64 (without writing them to conf files in /etc/ld.so.conf.d/) does not need any additional steps after putting the libs. What causes this?
By the way, why directories like /lib and /usr/lib are not set in /etc/ld.so.conf or /etc/ld.so.conf.d/?

A: When an app is run via LD_LIBRARY_PATH=PATH app glibc will scan all the files in the the specified directories.
When you're not using this flag only cached libraries (/etc/ld.so.cache) are opened to speed up the process. Imagine you need to run a certain application 100K times in a row and each time all the directories have to be rescanned. It might slow everything to a crawl.


text:
Q: Вывести поля каждой структуры на экран? В бинарном файле записано N структур. Как работать с данными структурами - например вывести поля каждой структуры на экран?
Структура:
struct Session
{
    char userName[24];
    int points;
};

Заполняем структуру:
void CreateSession()
{
    Session temp;
    printf_S("\nEnter your name: ");
    gets_s(temp.userName);
    temp.points = 0;
    SaveSessionToFile(temp);
}

Сохраняем в файл:
void SaveSessionToFile(Session temp)
{
    ofstream fout("AppData/Sessions", ios_base::binary | ios_base::app);
    fout.write((char*)&temp, sizeof(Session));
    fout.close();
}

Работает отлично - новые данные добавляются в конец бинарного файла. Но вот никак не могу понять как мне теперь работать с файлом - напимер сделать вывод данных каждой структуры? Например:
userName1 + points1 // Данные 1 структуры записать в string, вывести string;
userName2 + points2 // Данные 2 структуры записать в string, вывести string;
userName3 + points3 // Данные 3 структуры записать в string, вывести string;

Буду признателен за помощь!

A: Собственно так же, как и записывали. Создаете входной файловый поток в бинарном режиме и записываете в экземпляр структуры.
Session s;

std::ifstream fin("Sessions", std::ios_base::binary | std::ios_base::in);

while (fin.peek() != EOF)
{
    fin.read((char*)&s, sizeof(Session));
    std::cout << s.userName << " " << s.points << std::endl;
}


text:
Q: How to grant confluent iam acl for all consumer groups Can you plese share the command to allow READ for a userid for all consumer group?
Below works fine. But I want to grant access for all consumergroup for that username
./confluent iam acl create --allow --principal User:userName --operation READ --consumer-group groupName --kafka-cluster-id UjOnbv9hAsdAk7Tuk4RX4w

A: There are 2 options to work with ACLs for multiple resources:

*

*Use asterisk '*' instead of group or topic names. In Confluent docs examples it is used with --topics flag, it should work with groups as well.
confluent iam acl create --allow --principal User:User1 --operation WRITE
                         --consumer-group '*' --kafka-cluster-id <kafka-cluster-id>

*To select subset of groups or topics, use --prefix flag.
confluent iam acl create --allow --principal User:User1 --operation WRITE
                         --consumer-group 'prefixString' --prefix --kafka-cluster-id <kafka-cluster-id>

Review all the ACLs for the specified cluster that include allow permissions for the user:
confluent iam acl list --kafka-cluster-id <kafka-cluster-id> --allow --principal User:Jane

Example of how prefixed and asterisk are displayed in the liast of ACLs:


text:
Q: Using Cauchy-Schwarz inequality to prove another inequality So I know how to prove the inequality:
$$\left(\sum_{i=1}^n x_{i}y_{i} \right)^2 \le \left(\sum_{i=1}^n x_{i}^2 \right)\left(\sum_{i=1}^n y_{i}^2 \right)$$
But now I need to prove that:

If $x_{i}$ and $y_{i}$ are positives, for i = 1:n, and $\sum_{i=1}^n x_{i} = \sum_{i=1}^n y_{i}$ then:
  $$\sum_{i=1}^n \frac{x_{i}^2}{x_{i} + y_{i}} \ge \frac{1}{2} \sum_{i=1}^n x_{i}$$

I have to find something to substitute on the first inequality, but I don't know what.
Can anybody help?

A: By Cauchy-Schwarz Inequality
$$\left(\sum_{i=1}^nx_i+y_i\right) \left(\sum_{i=1}^n  \frac{x_{i}^2}{x_{i} + y_{i}}\right) \ge \left(\sum_{i=1}^n x_{i}\right)^2$$
Using $$\sum_{i=1}^n x_{i} = \sum_{i=1}^n y_{i}$$ we get the desired result.


text:
Q: Python image processing for 16-bit grayscale png image I'm writing a script to check if an image is normalized or not. I'm using Python PNG module to analyze the image. To test it I created a 16-bit image consisting of a 2 pixels line with a black and white pixel in Photoshop.
My script correctly identifies the black pixel (0), but it gives a different value (65533) than I was expecting (65535) for the white pixel.
I can't understand why this happens. Is there something wrong with my script or it is related with the way Photoshop saves the image?
Minimalistic test png image: http://i.imgur.com/70D0F.png
Script:
#!/usr/bin/python

import sys
import png # https://pypi.python.org/pypi/pypng

if len(sys.argv) != 2:
    print "Invalid number of arguments (",len(sys.argv),").\nUsage: python getMinMaxColor.py png_file"
    sys.exit(-1)
pngFilePath = sys.argv[1]

f = open(pngFilePath, 'rb')
r = png.Reader(file=f)
k = r.read()

bitDepth = 16
if k[3]['bitdepth'] != None:
    bitDepth = k[3]['bitdepth']

absMaxColor = 2**bitDepth-1

maxColor = -1
minColor = absMaxColor+1
print "Content:"
for line in k[2]:
    for color in line:
        print color
        if (color > maxColor):
            maxColor = color
        if (color < minColor):
            minColor = color

f.close()

print "\n"

print "Min Color:", minColor
print "Max Color:", maxColor, "( max:", absMaxColor, ")"
if minColor == 0 and maxColor == absMaxColor:
    print "Image is normalized"
else:
    print "Image is not normalized"

A: It seems the PNG file really has the 65533 value stored for the white pixel instead of 65535. I assume this has something to do with the fact that Photoshop in reality works with 15 bits in the "16 bit mode", so there is a small inaccuracy when saving 16 bit greyscale images.


text:
Q: One sentence of dummy text I need to create just a specified number of sentences of dummy text (rather than a long paragraph). Can I use lipsum to do this? If not, then what can I use? The idea is to be able to create a MWE that doesn't contain a lot of distracting text in the source code, but allows me to use smaller numbers of sentences than I can get with \lipsum[n].

A: You can use a macro for the dummy text and a loop to repeat it, taking as an argument the number of repetitions. These commands work in any variety of TeX, but I illustrate their use in a LaTeX document.
\documentclass{article}

% Define the dummy sentence, an ancient palindrome.
\def\sator{Sator Arepo tenet opera rotas.}

% Create a command to print the sentence repeatedly.
% Argument #1 is the number of times to repeat it.
\newcount\loopcounter
\def\dummysentences#1{%
    \loopcounter = #1
    \loop
        \sator\ %
        \advance\loopcounter by -1
        \ifnum\loopcounter > 0
    \repeat%
}

\begin{document}

\sator

\dummysentences{5}

\begin{itemize}
\item \sator
\item \dummysentences{3}
\item \dummysentences{2}
\end{itemize}

\end{document}

See also my answer here: Is there a dummy package like Lipsum or Blindtext for Tables and Figures?

A: Starting from version 2.0 on, the lipsum package provides a second optional parameter to the \lipsum command which selects a range of single sentences from the paragraphs selected by the first optional parameter. The syntax is
\lipsum[<paragraph range>][<sentence range>]

where each <range> can be a single number n or a range n-m.
Example:
\documentclass{article}
\usepackage{lipsum}

\begin{document}
\lipsum[1][1]\par
\lipsum[1][2]\par
\lipsum[1][3]\par
\lipsum[1][4-6]\par
\lipsum[2-4][12-18]
\end{document}

A: One can defines  command \mylipsum
\newcommand{\mylipsum}{just dummy text}

MWE
\documentclass{article}

\newcommand{\mylipsum}{just dummy text}
\newcommand{\Mylipsum}{\mylipsum{} \mylipsum}

\begin{document}
\mylipsum

\Mylipsum
\end{document}

A: With some help from xparse we can extract a rich supply of sentences from lipsum; precisely 1498, I guess they're sufficient.
\documentclass{article}
\usepackage{lipsum}
\usepackage{xparse}

% store a big set of sentences
\unpacklipsum[1-100] % it was \UnpackLipsum before version 2.0

\ExplSyntaxOn
% unpack \lipsumexp
\seq_new:N \g_lipsum_sentences_seq
\cs_generate_variant:Nn \seq_set_split:Nnn { NnV }
\seq_gset_split:NnV \g_lipsum_sentences_seq {.~} \lipsumexp

\NewDocumentCommand{\lipsumsentence}{>{\SplitArgument{1}{-}}O{1-7}}
 {
  \lipsumsentenceaux #1
 }
\NewDocumentCommand{\lipsumsentenceaux}{mm}
 {
  \IfNoValueTF { #2 }
   {
    \seq_item:Nn \g_lipsum_sentences_seq { #1 }.~
   }
   {
    \int_step_inline:nnnn { #1 } { 1 } { #2 }
     {
      \seq_item:Nn \g_lipsum_sentences_seq { ##1 }.~
     }
   }
 }
\ExplSyntaxOff

\begin{document}

\section{Seven sentences}

\lipsumsentence

\section{Three sentences}

\lipsumsentence[2-4]

\section{Some single sentences}

\lipsumsentence[1]

\lipsumsentence[2]

\lipsumsentence[3]

\lipsumsentence[4]

\lipsumsentence[5]

\end{document}

A: \newcount\zz
\loop
Hello world.
\advance\zz1
\ifnum\zz<10
\repeat

writes Hello world 10 times.


text:
Q: using boost::geometry::buffer function It's my first time in using boost libraries, so I'm quite uncomfortable with it and I might be doing something wrong. I'm experiencing some problems while using boost::geometry::buffer() function.
Here's my code:
#include <vector>
#include <boost\geometry.hpp>
#include <boost\geometry\geometries\register\point.hpp>

struct PNT_2D
{
    double x, y;
};
BOOST_GEOMETRY_REGISTER_POINT_2D(PNT_2D, double, boost::geometry::cs::cartesian, x, y);
typedef boost::geometry::model::polygon<PNT_2D, false>  BoostPolygon;
typedef std::vector<PNT_2D>                             StlPolygon;

int main(int argc, char * argv[])
{
    int             nStaph;
    BoostPolygon    polygon;
    BoostPolygon    off_polygon;
    PNT_2D          p2dPunto;
    StlPolygon      stlPolygon;

    stlPolygon.resize(5);
    stlPolygon[0].x = stlPolygon[0].y = stlPolygon[4].x = stlPolygon[4].y =  0.0;
    stlPolygon[1].x = 25.0; stlPolygon[1].y = 0.0;
    stlPolygon[2].x = 25.0; stlPolygon[2].y = 25.0;
    stlPolygon[3].x = 0.0; stlPolygon[3].y = 25.0;
    boost::geometry::append(polygon, stlPolygon);
    boost::geometry::buffer(polygon, off_polygon, 1);
    stlPolygon = off_polygon.outer();
    for (auto punto = stlPolygon.begin(); punto != stlPolygon.end(); punto++)
        std::cout << "(" << punto->x << ", " << punto->y << ")" << std::endl;
}

which gives the following error in compiling:
'int boost::mpl::assertion_failed<false>(boost::mpl::assert<false>::type)': impossibile convertire l'argomento 1 da 'boost::mpl::failed ************(__thiscall boost::geometry::nyi::not_implemented_error<boost::geometry::info::POLYGON,boost::geometry::info::POLYGON,void>::THIS_OPERATION_IS_NOT_OR_NOT_YET_IMPLEMENTED::* ***********)(boost::mpl::assert_::types<Term1,Term2,Term3,boost::mpl::na>)' a 'boost::mpl::assert<false>::type'

What am I missing?
EDIT
I've updated my code in the following way:
//////////////////////// DEFINITIONS
typedef BG::model::polygon<PNT_2D, false> BoostPolygon;
typedef BG::model::multi_polygon<BoostPolygon> BoostMultiPolygon;
typedef SB::distance_symmetric<double> DistanceStrategy;
typedef SB::end_round EndStrategy;
typedef SB::join_round JoinStrategy;
typedef SB::point_circle PointStrategy;
typedef SB::side_straight SideStrategy;
typedef std::vector<PNT_2D> StlPolygon;
/////////////////////////////////////////////////////////////

///////////////////////// CODE
BoostMultiPolygon   off_polygon;
BoostPolygon        polygon;
DistanceStrategy    distance_strategy(1.0);
EndStrategy     end_strategy;
JoinStrategy        join_strategy;
PointStrategy       point_strategy;
PNT_2D          p2dPunto;
SideStrategy        side_strategy;
StlPolygon      stlPolygon;

p2dPunto.x = p2dPunto.y = 0.0;
boost::geometry::append(polygon, p2dPunto);
p2dPunto.x = 25.0; p2dPunto.y = 0.0;
boost::geometry::append(polygon, p2dPunto);
p2dPunto.x = 25.0; p2dPunto.y = 25.0;
boost::geometry::append(polygon, p2dPunto);
p2dPunto.x = 0.0; p2dPunto.y = 25.0;
boost::geometry::append(polygon, p2dPunto);
p2dPunto.x = 0.0; p2dPunto.y = 0.0;
boost::geometry::append(polygon, p2dPunto);
boost::geometry::buffer(polygon, off_polygon, distance_strategy, side_strategy, join_strategy, end_strategy, point_strategy);
for (auto poligono = off_polygon.begin(); poligono != off_polygon.end(); poligono++)
{
    for (auto punto = poligono->outer().begin(); punto != poligono->outer().end(); punto++)
        std::cout << "(" << punto->x << ", " << punto->y << ")" << std::endl;
}
std::cin >> nStaph;

return EXIT_SUCCESS;

And now I've got this error:
'std::copy::_Unchecked_iterators::_Deprecate': Call to 'std::copy' with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'

Not in the main project, but in xutility.

A: *

*The code you present is to buffer a box. For a buffer with a polygon,
you (currently) need to use the buffer-with-strategies (see doc
with an example there)

*If you do that, and provide strategies, the result should be a multi-polygon

*Your sample is effectively using a box, so that might be an option
too. But then your input geometry should fulfil the box concept


text:
Q: MatCheckbox has not been processed correctly by ngcc, or is not compatible with Angular Ivy I'm trying to use the latest Angular Material with Angular 9 but I encountered below problem
and here is my app.modul.ts
import { NgModule } from '@angular/core';
import { CommonModule, CurrencyPipe } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientJsonpModule } from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { ModalModule } from 'ngx-bootstrap/modal';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { CollapseModule } from 'ngx-bootstrap/collapse';
import { TabsModule } from 'ngx-bootstrap/tabs';
import { NgxPaginationModule } from 'ngx-pagination';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServiceProxyModule } from '@shared/service-proxies/service-proxy.module';
import { SharedModule } from '@shared/shared.module';
import { HomeComponent } from '@app/home/home.component';
import { AboutComponent } from '@app/about/about.component';
// tenants
import { TenantsComponent } from '@app/tenants/tenants.component';
import { CreateTenantDialogComponent } from './tenants/create-tenant/create-tenant-dialog.component';
import { EditTenantDialogComponent } from './tenants/edit-tenant/edit-tenant-dialog.component';
// roles
import { RolesComponent } from '@app/roles/roles.component';
import { CreateRoleDialogComponent } from './roles/create-role/create-role-dialog.component';
import { EditRoleDialogComponent } from './roles/edit-role/edit-role-dialog.component';
// users
import { UsersComponent } from '@app/users/users.component';
import { CreateUserDialogComponent } from '@app/users/create-user/create-user-dialog.component';
import { EditUserDialogComponent } from '@app/users/edit-user/edit-user-dialog.component';
import { ChangePasswordComponent } from './users/change-password/change-password.component';
import { ResetPasswordDialogComponent } from './users/reset-password/reset-password.component';
// layout
import { HeaderComponent } from './layout/header.component';
import { HeaderLeftNavbarComponent } from './layout/header-left-navbar.component';
import { HeaderLanguageMenuComponent } from './layout/header-language-menu.component';
import { HeaderUserMenuComponent } from './layout/header-user-menu.component';
import { FooterComponent } from './layout/footer.component';
import { SidebarComponent } from './layout/sidebar.component';
import { SidebarLogoComponent } from './layout/sidebar-logo.component';
import { SidebarUserPanelComponent } from './layout/sidebar-user-panel.component';
import { SidebarMenuComponent } from './layout/sidebar-menu.component';
import { ChatComponent } from './chat/chat.component';
import { Chat2Component } from './chat2/chat2.component';
import { CitizenInterestsComponent } from './citizen-interests/citizen-interests.component';

import {MAT_CHECKBOX_CLICK_ACTION, MatCheckbox} from '@angular/material/checkbox';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent,
    // tenants
    TenantsComponent,
    CreateTenantDialogComponent,
    EditTenantDialogComponent,
    // roles
    RolesComponent,
    CreateRoleDialogComponent,
    EditRoleDialogComponent,
    // users
    UsersComponent,
    CreateUserDialogComponent,
    EditUserDialogComponent,
    ChangePasswordComponent,
    ResetPasswordDialogComponent,
    // layout
    HeaderComponent,
    HeaderLeftNavbarComponent,
    HeaderLanguageMenuComponent,
    HeaderUserMenuComponent,
    FooterComponent,
    SidebarComponent,
    SidebarLogoComponent,
    SidebarUserPanelComponent,
    SidebarMenuComponent,
    ChatComponent,
    Chat2Component,
    CitizenInterestsComponent
  ],
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    HttpClientJsonpModule,
    ModalModule.forChild(),
    BsDropdownModule,
    CollapseModule,
    TabsModule,
    AppRoutingModule,
    ServiceProxyModule,
    SharedModule,
    NgxPaginationModule,
    MatCheckbox

  ],
  providers: [],
  entryComponents: [
    // tenants
    CreateTenantDialogComponent,
    EditTenantDialogComponent,
    // roles
    CreateRoleDialogComponent,
    EditRoleDialogComponent,
    // users
    CreateUserDialogComponent,
    EditUserDialogComponent,
    ResetPasswordDialogComponent
  ],
})
export class AppModule {}

ERROR in node_modules/@angular/material/checkbox/checkbox.d.ts:56:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.
This likely means that the library (@angular/material/checkbox) which declares MatCheckbox has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

A: Add the file package.json in the scripts section as follows:
"postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"

And run npm install or yarn install

A: I found the solution here
I was imported Matcheckbox instead of MatCheckboxModule
before that, I ran this command  npm ci I don't know if this affects but that what I did.

A: Make sure your import class should be ended up with **Module. In my case I was just importing MatFormField & stucking up with same error as stack's sub. Since I did MatFormFieldModule it works.

A: To Fix this problem you need to clean your local node module cache.
Run this command to fix this:
npm cache clean --force

Then reinstall your npm modules:
npm install


text:
Q: With Nest.js, how to make Mongoose accept mixed scheme or multiple types in one scheme? Say I have this simple Mongoose schema of which you can find something similar in the docs of Nest.js.
class One {
  name: string;
  type: string;
}

class Two {
  hight: number;
  depth: number;
}

class Three {
  count: number;
  properties: object;
}

@Schema({})
export class SomeThing { }

export const SomeThingSchema = SchemaFactory.createForClass(SomeThing)

How can I make SomeThingSchema implement one of the above 3 classes at a time?
I expect I can't. If so, how to implement a mixed schema (as Mongoose says) but in a way that works with above code syntaxes? Unfortunately Nest.js docs don't say how.

A: You can create more models for the same collection.
You have to use different models but the data will be in the same place and you can validate and have all the features of the mongoose models/documents.
Something like this
import mongoose, { Schema } from 'mongoose';

const oneSchema = new Schema({
  name: String,
  type: String
})

export const oneModel = mongoose.model('OneThing', oneSchema , 'things')

const twoSchema = new Schema({
  hight: Number,
  depth: Number
})

export const oneModel = mongoose.model('TwoThing', twoSchema , 'things')

const threeSchema = new Schema({
  count: Number,
  properties: Object
})

export const oneModel = mongoose.model('ThreeThing', threeSchema , 'things')

To add the model to your syntax you can use JSDoc
import mongoose, { Schema } from "mongoose";

/**
 * @class MySchema
 * @extends mongoose.Document
 */
const MySchema = new Schema({ one: String })

// You can also add the methods or anything in this way
/** @alias MySchema.prototype.customMethod */
MySchema.method('customMethod', function() {})

export default mongoose.model('Mymodel', MySchema );

In your code you have to declare the
/**
 * @type {MySchema & mongoose.Document}
 */
const newItem = new MyModel({one: 1})


text:
Q: How to get information from two tables? I have a database named superstore and 4 tables.
-- Q5: Pull all the order details of Product
-- (ID: 657768) got sold at a discount rate of 0.06
SELECT * FROM superstore.orders JOIN
superstore.product  ON
superstore.orders.ProductID=superstore.product.ProductID
WHERE
superstore.product.ProductID='657768' AND Discount='0.06';

This returns me an empty record. How can I fix it?

A: SELECT *
FROM Product p
JOIN Orders o ON o.ProductID = p.ProductID
WHERE
   p.ProductID = '657768' AND
   Discount = 0.06;

A: It is important to use column names in SELECT query instead of "*" as it becomes slow if you have tables with thousands of records.
SELECT
    p.ProductID,p.ProductName,p.ProductCategory,p.ProductSubCategory,
    p.ProductContainer,p.ProductBaseMargin
    FROM Product p
    JOIN Orders o ON o.ProductID = p.ProductID
    WHERE p.ProductID = '657768' AND o.Discount=0.06


text:
Q: The speed of JIT compiling method call compared to reflection in .NET Reflection is usually said to be slow. However, when .NET JIT compiler needs to compile a call to a method it needs to refer to the same module metadata tables (if I understand it correctly). Does method (and field) lookup incur the same perf. hit in JIT compilation and in reflection?

A: I think the two might be comparable, but don't forget that JITting is a one-time cost, while using reflection isn't.


text:
Q: How to connect to MySQL and SQL Server databases at once in Laravel 8 and PHP 8 for Linux I have a Laravel web application running on a Nginx application server. The application has 2 database connections: one to a local MySQL database named picking_demo and another to a remote Microsoft SQL Server named db_picking_main.
The MySQL connection works fine and doesn't need to be changed.
At first, the application worked under Laravel 5 and PHP 7. For the SQL Server connection, the application used the library techscope/laravel-sqlserver and it worked well.
However, due to client's requirements, we had to migrate the application to the latest Laravel and PHP Versions (version 8 for each) and we must use Ubuntu as the operative system. Thus, techscope/laravel-sqlserver is not compatible anymore and it had to be deleted from composer.json.
We are currently using the 20.04 version of Ubuntu.
At first, when we tested the connection from one of the application's commands that must work with the SQL Server connection, we got a "Driver not found" error.
After some research, I installed the following packages from the repositories: freetds-common, freetds-bin, php8.0-pdo-sybase. The package unixodbc was already installed when we started to work.
Also, I installed the ODBC Driver 17 for SQL Server following Microsoft's official instructions (see https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15)
Afterwards, I tried executing the applicacion's command again and it gave me the following message:
In Connection.php line 685:

  SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (10.0.50.8:1433) (severity 9) (SQL: sel
  ect count(*) as aggregate from [deli_eti_correl] where [correl] > 1234891)

In Connector.php line 70:

  SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (10.0.50.8:1433) (severity 9)

This is the content in config/database.php:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'geostore'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
            'options' => [
                \PDO::ATTR_PERSISTENT => true
            ]
        ],
        'todosport_dummy' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'port' => '3306',
            'database' => 'todosport_dummy',
            'username' => 'root',
            'password' => '',
            'unix_socket' => '',
            'charset' => 'utf8',
            'collation' => 'utf8_spanish2_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
            'options' => [
                \PDO::ATTR_PERSISTENT => true
            ]
        ],
        'delisur_picking' => [
            'driver'        => 'sqlsrv',
            'odbc_driver'   => '{ODBC Driver 17 for SQL Server}',
            'host' => '10.0.50.8',
            'database' => 'bd_delisur_main',
            'username' => 'sa',
            'password' => 'Latorredebabel6427....D',
            'port' => '1433',
            'prefix'   => '',
            'charset' => 'utf8',
            'collation' => 'utf8_spanish2_ci',
            'TrustServerCertificate' => 'no',
            'options' => [
                \PDO::ATTR_PERSISTENT => true,
                "MultipleActiveResultSets"=>'0',
                "ConnectionPooling" => "1",
                "TraceOn" => "0",
                \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
            ]
        ]
    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than a typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];

Questions:

*

*Must I still configure TDS in order to connect to the desired database? If not, what steps are missing?

*Is it possible that the cause is a permissions issue from the SQL Server Database server?

Thanks in advance

A: SOLVED
It wasn't a Laravel nor SQL Server nor tsql problem. It was a VPN problem. Recently my partner told me the application needs a VPN connection to the SQL Server database using openvpn. No additional configuracion is needed in tsql.
Thanks anyway.


text:
Q: Доступ к папке documents основного приложения из share-расширения Моё приложения представляет из себя что-то вроде текстового редактора. Его файлы хранятся в стандартной папке documents, путь к которой внутри приложения я получаю при помощи NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0].
Собственно, как получить доступ к этой папке из share-расширения? Мне хотелось бы, что бы был интерфейс выбора директории, в которую пользователь хотел бы поместить тот или иной файл.
Заранее всем спасибо за ответы.


text:
Q: Thin Film Interference - longest wavelength of the light in water that is transmitted most easily The problem:

A scientist notices that an oil slick floating on water when viewed
from above has many different colors reflecting off the surface,
making it  look rainbow-like. She aims a spectrometer at a particular
spot and measures the wavelength to be 750 nm (in air). The index of
refraction of water is 1.33. Now assume that the oil had a thickness
of 200 nm and an index of refraction of 1.5. A diver swimming
underneath the oil slick is looking at the same spot as the scientist
with the spectrometer. What is the longest wavelength of the light in
water that is transmitted most easily to the diver?

My attempt:
I tried to find the wavelength at which the scientist would see constructive interference. I know that is not what the problem asks but I figured I could find the wavelength from that. The top reflected ray experiences phase shift while the bottom reflected ray does not, hence the equation to satisfy constructive interference is:

So I did that, setting m = 0 and then m = 1, and then used the relationship $\lambda_{oil}n_{oil}=\lambda_{water}n_{water}$ to calculate wavelength in water. However, in both my cases of m = 1 and m = 0, I calculated the wavelength of water to be outside of the range of the visible spectrum (900 and 266 nm).

The correct answer for the wavelength of light in water 450 nm and I discovered that the only way to get this is if I set m = 0.5, but m can only be an integer. The other alternative is that the scientist actually sees a dark spot while the diver looking up sees a bright spot. Then I can use the destructive interference equation ($2t=m\lambda_{oil}$). This is the only case where $\lambda_{oil}$ will have a coefficient of 1, giving 400 nm for the wavelength in the oil, and thus 450 for wavelength in water. So what is the case here?

A: The light is reflected best when constructive interference occurs.
Conversely, the light is transmitted best when destructive interference occurs.
That's why you're getting $m=0.5$: you should actually be solving for when destructive interference occurs.


text:
Q: Will this short range AM transmitter constructed using crystal work? I have designed a circuit as follows:

simulate this circuit – Schematic created using CircuitLab
There are a few corrections in the circuit. I couldn't do it in the editor because I don't know. The corrections are:
1. The input is audio input.
2. The capacitor is electrolytic.
Now my question is whether this circuit will be able to generate the carrier frequency to transmit the audio input. If not, then what are all the required additions and corrections?
Also can anyone explain how to design the receiver to receive the signals.

A:
Now my question is whether this circuit will be able to generate the
  carrier frequency to transmit the audio input. If not, then what are
  all the required additions and corrections?

My advice is do some research and forget your circuit. Google is your friend. Type "crystal AM modulator" and look at the images that it finds: -

Next choose one that appears to give good information about how it works and try it out. Also be very aware of your country's laws on illegal transmitters.

Also can anyone explain how to design the receiver to receive the
  signals.

Get your transmitter working on a band that a regular transistor radio works on then think about designing a receiver (much trickier).

A: This is not much of an answer, but a blind suggestion since I know nothing about transistor parameters and other conditions. First, if you want to modulate the signal you should multiply them instead of summing them. Secondly, there must be an adjusted resistor on the place where the crystal is. Because the crystal does not let dc current to flow so there will be no amplified signal. Third, you should place the antenna on collector output with a coupling capacitor with a large value  say 1.5 uF. Then you should reduce the value of the source resistor. And final, put the crystal to source with proper capacitor values. That means you should also bypass the source resistor.


text:
Q: Go Appengine Debug ability I searched on this forum and I can't seem to find much information about Go AppEngine debug method.
I come from Java world. I usually put a Java web app on Tomcat and turn on the debug port. Then I use Eclipse to have remote debugging. I am wondering if there is similar features or ability in Go AppEngine?


text:
Q: MySql, find in paragraphs with regex sorry for my English.
I'm trying to find text by this query with regexp:
SELECT * FROM p_posts  where Text REGEXP '[[:<:]]Liberty[[:>:]]'and Text REGEXP '[[:<:]]Rig.*[[:>:]]'and Text REGEXP '[[:<:]]7[[:>:]]'and Text REGEXP '[[:<:]]22[[:>:]]'

All works fine. But now I need to find records, where these words are in one paragraph. For example, if word Liberty and number 22 aren't in one paragraph, then this record not valid.
Please help.
Thanks.

A: This will be tricky to do with MySQL regex because you have neither lookarounds nor non-greedy  matches.
I would suggest that you split the string according to the paragraph delimeters and then search for the matches in the paragraph strings. An example split function that was taken from here:
CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');


text:
Q: Disable Network Location Wizard in Windows on Azure I have a problem with WPF automation - when I'm running automation on a virtual machine, I see on the video recorder this window. The window changes focus and automation cant work.
Maybe I can disable that window by power-shell script or is there some other solution?

A: You want to create a new registry key. In Powershell:
New-Item -Path "HKLM:\System\CurrentControlSet\Control\Network\NewNetworkWindowOff\"


text:
Q: How to install haskell Parallel on mac? How to install haskell Parallel on mac?
I'm trying:  '$sudo cabal install parallel' but its not working. I'm getting the following message:
Resolving dependencies...
Configuring parallel-3.2.0.0...
Preprocessing library parallel-3.2.0.0...
Building parallel-3.2.0.0...
<command line>: cannot satisfy -package-id deepseq-1.1.0.2-09b3aed0c4982bbc6569c668100876fa
    (use -v for more information)
cabal: Error: some packages failed to install:
parallel-3.2.0.0 failed during the building phase. The exception was:
ExitFailure 1

Thanks.


text:
Q: Issue deploying Flask Rest Api on Nginx I'm trying to deploy my flask api rest on nginx (on a subdomain) without success. I've followed this example from Digital Ocean and everything was working properly but then I changed the tutorial example code to my mine and POST requests aren't working at all. I'm using Postman Chrome App and each time I do a POST request to "api.domain.com/CreateUser" I get a 404 error:
"The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again."
This is my VH config:
server {
    listen 80;
    server_name api.domain.com;

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/ubuntu/apirest/apirest.sock;
    }
}

And this is the python file (flask api sample):
from flask import Flask, jsonify, url_for, redirect, request
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)
api = Api(app)

class CreateUser(Resource):
    def post(self):
        return jsonify({
            'status': 'ok',
            'message': 'user successfuly created'
        })

api.add_resource(CreateUser, '/CreateUser')

if __name__ == '__main__':
    app.run(host='0.0.0.0')

Anyone has a clue about what's happening? Thanks so much!


text:
Q: How to circumvent Rails 5 Devise user login authentication and instead redirect to page My application has Devise deeply integrated and I wish to instead allow Apache to authenticate the user via SAML (to an IdP identity provider). Upon successful SAML login, Apache can then pass an environment variable that indicates the user_identifier.
Yet, I do not know how to tell Devise (or Warden) that the user is now logged in, and to not present the login page.
The routes.rb is similar to:
Authentication::Engine.routes.draw do
  devise_for :user, {
    class_name: 'Authentication::Account',
    module: :devise,
    path_names: {
      sign_up: 'register',
      cancel: '',
    },
    controllers: {
      # ...
      sessions: 'authentication/sessions',
    }
  }

  devise_scope :user do
    root to: 'sessions#new'
    # ...
  end

I have made several attempts by adding a new() method to the SessionsController:
module Authentication
  class SessionsController < Devise::SessionsController
    before_action :authenticate_user!, :except => [:new, :create], raise: false
    prepend_before_action(only: [:new, :create, :destroy]) { request.env["devise.skip_timeout"] = true}

    def destroy
      # ...
    end

    # add new() method to override default Devise method
    def new
      user_identifier = ENV['uid']
      @user = Account.find_by_user_identifier(user_identifier)

      # super do
        store_location_for(:user, session[:origin_url])

        # dependent upon prepend_before_action, see rubydoc.info
        # sign_in(@user)  # didn't seem to sign user in, redirectors controller then calls destroy (above)

        bypass_sign_in(@user)

        # redirect_to session[:origin_url] and return
        # sign_in_and_redirect session[:origin_url] and return  # wrong?
        # sign_in_and_redirect @user  # wrong, loops through sign_in

        # resource = warden.authenticate!(:scope => :user, :recall session[:origin_url])
        # resource = warden.authenticate!(:scope => :user)  # maybe?

        # sign_in_and_redirect(:user, resource)
        # redirect_to session[:origin_url] and return
      # end
    end

Most attempts result in sending the user to the login page, while others create an infinite loop.

A: The correct way to add other auth methods to Devise is via OmniAuth (Standardized Multi-Provider Authentication)
From the docs: "OmniAuth is a library that standardizes multi-provider authentication for web applications. It was created to be powerful, flexible, and do as little as possible. Any developer can create strategies for OmniAuth that can authenticate users via disparate systems."


text:
Q: Probability of selecting consecutive floors in an elevator Three people get into an empty elevator at the first floor of a building that has 10 floors. Each presses the button for their desired floor (unless one of the others has already pressed the button). Assume that they are equally likely to want to go to floors 2 through 10 (independently of each other). What is the probability that the buttons for 3 consecutive floors are pressed? (question from 'introduction to probability' by Bliztstein)
I thought the answer might be $$\frac{7 \cdot3!}{9^3}$$... but then I thought maybe the total number of ways is the bose-einstein value $n+k-1 \choose k$ (how many ways there are to choose k times from a set of n objects with replacement, if order doesn't matter).. so then the answer could also be $$\frac{7}{165}$$ Which is the correct answer, and why is the logic for the other answer wrong?

A: I think there is only one reasonable interpretation of the problem.  It leads to a probability model that produces your first answer.
Let our three passengers be A, B, and C. If A, B, C wish respectively to go to floors $p$, $q$, and $r$, record that fact as an ordered triple $(p,q,r)$. By the equally likely and independent part of the problem statement, all ordered triples $(p,q,r)$, where $p$, $q$, and $r$ range from $2$ to $10$, are equally likely. There are $9^3$ such triples. Whether a passenger, say C, happens not to press the elevator button to Floor $6$ because it has already been pressed is irrelevant.
We now count the favourables. There are $7$ ways to choose a collection of $3$ consecutive numbers in the interval from $2$ to $10$. For each of these collections, there are $3!$ ways in which A, B, and C might wish to get off at the floors in this collection, for a total of $7\cdot 3!$. For the probability, divide.

A: Call the passengers A,B,C.
Consider A presses 2, then for there to be three consecutive ( i.e. 2,3,4 ) buttons pressed B and C must press 3 and 4, this can occur in only two ways, with B pressing 3 and C pressing 4 or visa versa.
Repeating this method on floors 3,4,5,6,7 and 8 we have a total of 14 different ways of getting 3 consecutive buttons pressed where A gets out on a lower floor than the other two.
 Therefore there is a total of 3 times 14 = 42 ways of getting 3 consecutive buttons pressed, the probability of which is $\Large\frac{42}{9^3}$
Much the same as  André Nicolas' answer.
BTW if one of the passengers was an unaccompanied 4 year old, chances are almost certain that every damn button would be pressed, at least the ones he/she could reach.

A: The first one $$  \dfrac{7*3!}{9^3} $$ is the correct answer.
We can not use Bose-Einstein here because it can not be used in naive probability expression according to 'introduction to probability' by Bliztstein, page 18. "The Bose-Einstein result should not be used in the naive definition of probability except in very special circumstances. For example, consider a survey where a sample of sizekis collected by choosing people from a population of size n one at a time, with replacement and with equal probabilities. Then then k ordered samples are equally likely, making the naive definition applicable, but the
unordered samples (where all that matters is how many times each person was
sampled) are not equally likely."
Here, since each person presses which floor is an equal likely event, we cannot use Bose-Einstein.

A: let's say we have A, B, and C people in the lift.
A - is the event that passengers will press three consecutive numbers.
P(A)= # of favourable outcomes/# of total outcomes
Since there is replacement and order matters the # of total outcomes is 9^3
Now we should find the # of fav outcomes:
there are 7 ways to get three consecutive numbers out of 2-10  => (234), (345), (456), (567), (678), (789), (8910) and 3! ways to shoose from three numbers
Therefore, the number of fav outcomes is 7*3!
P(A)=7*3!/9^3

A: The number of possible outcomes for who is going to which floor is $9^3$. There are $7$ possibilities for which $3$ buttons are pressed such that there are consecutive floors: $(2,3,4),(3,4,5)...(8,9,10)$. For each of these $7$ possibilities, there are $3!$ ways to choose who is going to which floor. So by the naive definition, the probability is
$${3!\times7\over9^3}= {42\over729}= {14\over243} = 0.05761316872 $$

A: As the problem says: "unless one of the others has already pressed the button", so for sure sample space is not $9^3$. Should be $$\frac{7}{\binom{9}{3}}$$  or in other way $$\frac{7\times3!}{9\times8\times7}$$

A: In the sequence $2,3,4,\cdots,10$ there are $7$ sequences of three consecutives numbers:
$$(2,3,4), (3,4,5), (4,5,6), (5,6,7), (6,7,8), (7,8,9), (8,9,10)$$
and by outher side there are ${9 \choose 3}=84$ distinc modes od choose $3$ numbers in set ${2,3,\cdots,10}$, Then, in my opinion, the probability is $P=\frac{7}{84}$.


text:
Q: Change ggplot2 colourbar tick marks to black In some of my plots I find it hard to see the tick marks in the colour bar. I haven't been able to find a documented way to change the colour of the ticks. All the examples seem to focus on changing the labels or not drawing ticks at all. Is it possible?
#  Data
require(ggplot2)
require(grid)
n <- 100
x <- y <- seq(-4*pi, 4*pi, len=n)
r <- cos( sqrt( outer(x^2, y^2, "+") ) ^ 2 )
df <- data.frame( x = rep( x , each = n) , y = rep( y , times = n ) , val = c(r) )

#  Plot
ggplot( df , aes( x , y , fill = val ) )+
  geom_raster()+
  scale_fill_gradient( low = "#FFFFFF" , high = "#de2d26" )+
  guides( fill = guide_colourbar( barheight = unit( 3 , "in" ) ) )+
  theme_bw()+
  theme( line = element_line( colour = "#0000FF" ) )

How can I make the ticks in the colourbar be plotted in black rather than white, without changing other elements of the plot?

p.s. kudos to this question for the function to create the example data

A: The pull request mentioned in another answer never made it into the ggplot2 code base, but this is now possible in a slightly different way in the development version (slated to be released as ggplot2 2.3):
ggplot(df, aes(x, y, fill = val)) +
  geom_raster() +
  scale_fill_gradient(low = "#FFFFFF", high = "#de2d26") +
  guides(fill = guide_colourbar(barheight = unit( 3 , "in" ),
                                ticks.colour = "black",
                                ticks.linewidth = 1)) +
  theme_bw() +
  theme(line = element_line(colour = "#0000FF"))

You can also add a frame, which may be useful when some of the colors in the colorbar are very light.
ggplot(df, aes(x, y, fill = val)) +
  geom_raster() +
  scale_fill_gradient(low = "#FFFFFF", high = "#de2d26") +
  guides(fill = guide_colourbar(barheight = unit( 3 , "in" ),
                                ticks.colour = "black",
                                ticks.linewidth = 1,
                                frame.colour = "black",
                                frame.linewidth = 1)) +
  theme_bw() +
  theme(line = element_line(colour = "#0000FF"))

A: I usually find what I need to change by extensive use of str. I'm sure others can do it more elegantly.
g <- ggplotGrob(p)
g$grobs[[8]][[1]][[1]]$grobs[[5]]$gp$col <- "black"

library(grid)
grid.draw(g)

A: EDIT: Please refer to the answer below by Claus Wilke.

I have included the original answer below, but please note that it is now outdated and I do not recommend using it.
I included the functionality to customize tick marks and legend borders in my fork of ggplot2. I have submitted a pull request, but thought I would let people know here in case they stumble on this question.
Install my fork using the following code,
if (!require(devtools))
  install.packages('devtools')
install_github('paleo13/ggplot2')

We can specify black marks using the following code,
ggplot(df, aes( x, y, fill = val)) +
  geom_raster() +
  scale_fill_gradient(low = "#FFFFFF", high = "#de2d26") +
  theme_bw() +
  theme(line = element_line(colour = "#0000FF")) +
  guides(fill = guide_colourbar(barheight = unit(3, "in"),
   ticks=element_line(color='black'), border=element_line(color='black')))

(I would have included this as a comment but I lack the reputation to do so, if anyone with sufficient privileges wants to delete this answer and move the contents to the comments then feel free)


text:
Q: Understanding MASE Value I've looked through many of the other posts concerning the Mean Absolute Scaled Error (MASE) forecast metric and haven't been able to sort out my problem just yet.
I'm working with some weather model forecast data (hourly forecasts from 0 to the 18th hour out) for surface temperatures and comparing the weather model data to a weather station that records surface temperature. I calculated MASE and ended up with values in the ballpark of 2 to 3. If I understand correctly, this indicates that my mean absolute error in the forecast is 2 to 3 times greater than that of a naive forecast.
If that's the case, why don't we just use naive forecasts for forecasting surface temperatures instead of a complex weather model?
I've included my code snippet below and the values. It won't be terribly useful without the data which I think may be difficult for me to provide but perhaps someone will see an egregious error in my method for calculating MASE. I've also included the MAE (numerator) and MAE naive forecast (denominator) output from running my code.
def mase_calc(df, obs):
    # Naive forecast calculation
    df = df.dropna() ##
    naive = df[obs].shift(1, freq='1H')
    naive_res = abs(df[obs] - naive)
    n = len(naive_res.dropna())
    print('naive_res n: ' +str(n))
    mae_naive = naive_res.sum()/n

    # RWIS - Observation MAE
    #hrrr_rwis_res = abs(df['sfc_tmp'] - df[obs])
    hrrr_rwis_res = abs(df['hrrr_sfc_tmp'] - df[obs])
    n = len(hrrr_rwis_res.dropna())
    print('hrrr_rwis_res n: ' +str(n))

    mae = hrrr_rwis_res.sum()/n
    print('MAE: ' + str(mae) + '     MAE_naive: ' + str(mae_naive))
    mase = mae/mae_naive

    return(mase)

Here is the output I got back from each forecast hour.

Rob J. Hyndman's paper discussing MASE can be found here.
My MASE results can be summarized in the following graph.

A: If a better answer is posted, I'll accept it.
After tinkering around with the data some more and thinking through all of this I realized that the MAE of the naive forecast was set at a 1 hour naive forecast where as my forecast data from the weather model provides up to 18 hours out. So the 18th hour forecast was being scaled by a 1 hour naive prediction. This means that the 18th hour forecast from my weather model has errors that are about 2.8 times greater than the naive forecast from the hour before that (17th hour in model terms).
So in summary, the naive forecast is better than the first hour of the model but the naive falls apart miserably if I attempt to push it farther than an hour (which I expected). A potential fix to the naive forecast problem is to use historical data (the seasonal version of MASE) but that's something I don't have currently.

A: I would think the mistake you made might be more serious than you expected.
The way you calculated "Naive", could only be the control of your one-hour prediction.
Then since you only had/showed one sample of forecast data (Fix me if I misunderstanding), there is no "MEAN" here, but only the "Absolute Scaled Error".

On the other hand, there is nothing here for your 18-hours forecast to defeat yet.
If you consider the original "Naive", it should be calculated by shifting 18 hours.
Well, in my opinion, if you want to compare your forecast with "Naive", except for the "MEAN" problem, I wouldn't consider the last observation of 18 hours ago would be "Naive" enough. I didn't know much about the weather forecast, but a Daily "Naive" might be better. Anyway, the competitor you chose for your defeat shows how confident you are.


text:
Q: Uploading application content to Firebase I am attempting to make my first Android application using the Firebase free trial for the server side of things. My app is fairly limited in scope and it is basically just a way of viewing some pre-created content that I have made.
I have manually created some JSON for the app to parse, and along with the JSON I have some images which I want the app to be able to download. However, I have no idea of how to store these images in Firebase so that they can be retrieved by the app.
My issue is... I have searched every variation of "Upload images to firebase" which I can think of and they are all about the user uploading their own content to Firebase via the app and not for me to upload the content of the app so it is available to be downloaded by the user.
Would anyone be able to point me in the direction of how to set this up? I can upload my JSON to Firebase to create the "database", it is just I do not know how to go about uploading my application data to Firebase so that users can then view it.
Thanks

A: You can upload your images manually from Firebase Storage.
from the left menu choose Storage and then upload file.

If you need the image URL. Press on the image and it will show details section at the bottom of this section you will find Download URL


text:
Q: Is there a way to pause/resume a serenity-js test run to check the browser? In a test context, we have been setting up a mock to behave a certain way including accessing the service under test, and we want to inspect the browser mid test because it isn't working in the way we expected.
Accessing the mock url direct doesnt give us the insight we need - we want to set headless:false and inspect the browser in the test execution.
Ca we set a pause/resume so we can check what we want? Then I guess cancelling the run is the simplest next step, or maybe continuing?

A: Not sure if I understood you right, but maybe you can use a Wait.for(Duration.ofMinutes(60)) (see Wait (Serenity/JS 2.x) or Wait (Serenity/JS 3.x).
Then you should have enough time to inspect your systems.


text:
Q: Rotating an object around it's centre in OpenGL I'm writing small 3d viewer of models from .obj file.
I have a car and I want to rotate car's wheels. I found a lot of good examples but I still have a problem: wheel rotates around point at the it's border, not around center. You can see it on the gif.
Below part of code without code for material and lighting. I find coordinates of wheel's center.
GL.PushMatrix();

// Rotate the car
GL.Translate(x, y, z); //x=0, y=0, z=0
GL.Rotate(ori, 0, 1, 0); // ori=90

// ...
// Material and lighting code
// ...

foreach (var group in file.G)
{
    GL.PushMatrix();
    if (group.name == "wheel_rf")
    {
        float xTmp, yTmp, zTmp;
        xTmp = yTmp = zTmp = 0;
        int count = 0;
        // read group's faces
        foreach (var f in group.F)
        {
            // read face's vertices
            foreach (var v in f.V)
            {
                yTmp += v.Y;
                zTmp += v.Z;
                xTmp += v.X;
                count++;
            }
        }
        yTmp /= count;
        zTmp /= count;
        xTmp /= count;
        GL.Translate(xTmp, yTmp, zTmp);
        GL.Rotate(this.wheelAngle, 1, 0, 0);
        GL.Translate(-xTmp, -yTmp, -zTmp);
    }

    // draw faces for each group
    GL.Begin(file.PrimitiveType);
    foreach (var face in group.F)
    {
        GL.TexCoord2(face.VT[0]);
        GL.Normal3(face.VN[0]);
        GL.Vertex3(face.V[0]);

        GL.TexCoord2(face.VT[1]);
        GL.Normal3(face.VN[1]);
        GL.Vertex3(face.V[1]);

        GL.TexCoord2(face.VT[2]);
        GL.Normal3(face.VN[2]);
        GL.Vertex3(face.V[2]);
    }
    GL.End();
    GL.PopMatrix();
}
GL.PopMatrix();

Note! In first time I rotate all car on 90 degrees otherwise I would have seen the car back. I can't find reason of problem. Maybe trouble in the car model, but whole car is drawn fine.


text:
Q: Confidence Intervals for a proportion My question is this:
I'm trying to get confidence intervals around the means of the proportion of survey respondents that chose a particular ordinal or nominal answer choice.
What is the reason for the requirement that a sample not make up more than 5% of the population?  Is there another statistical test that would be more appropriate for my use?  My two surveys have samples that make up about 6% and 10% of their populations, respectively.
Thanks for any help you can provide.


text:
Q: Angular $http get with :id I am trying to get the following to url path using angular $http service.
let's say I have a string

'/api/users/:id/fullinfo'

, and an id of 5, how do I get this string have following format:

'/api/users/5/fullinfo'

, via $http.get() method or $resource api.

A: I think what you are saying is that you have a GET API endpoint in your application that responds to the dynamic route '/api/users/:id/fullinfo', and you are trying to figure out how to make the GET request using the $http provider right? If that is the case, then you can do something like the following:
// create a service to manage the users resource
app.factory('UsersService', ['$http', function($http) {
    function getById(id) {
        var requestUrl = '/api/users/' + id + '/fullinfo';
        return $http.get(requestUrl).then(function(resp) {
            return resp.data;
        }, function(err) {
            // handle request error generically
        });
    }

    return {
        getById: getById
    };
}]);

// consume the service in a controller like so:
app.controller('YourController', ['$scope', 'UsersService', function($scope, UsersService) {
    var userId = 5; // you might also get this value from state params or some other dynamic way

    UsersService.getById(userId).then(function(userInfo) {
        $scope.userInfo = userInfo;
    });
}]);

A: You should be able to use $interpolate
var getPath = '/api/users/{{id}}/fullinfo';
$scope.id= '5';
$interpolate(getPath)($scope);

Alternatively you can also do:
var path = '/api/users/' + id + '/fullinfo';

But the interpolate is better.
https://docs.angularjs.org/api/ng/service/$interpolate

A: Code
Include this service in your app:
    app.service(
        "httpi",
        function( $http ) {
            return( httpProxy );
            // I proxy the $http service and merge the params and data values into
            // the URL before creating the underlying request.
            function httpProxy( config ) {
                config.url = interpolateUrl( config.url, config.params, config.data );
                return( $http( config ) );
            }
            // I move values from the params and data arguments into the URL where
            // there is a match for labels. When the match occurs, the key-value
            // pairs are removed from the parent object and merged into the string
            // value of the URL.
            function interpolateUrl( url, params, data ) {
                // Make sure we have an object to work with - makes the rest of the
                // logic easier.
                params = ( params || {} );
                data = ( data || {} );
                // Strip out the delimiter fluff that is only there for readability
                // of the optional label paths.
                url = url.replace( /(\(\s*|\s*\)|\s*\|\s*)/g, "" );
                // Replace each label in the URL (ex, :userID).
                url = url.replace(
                    /:([a-z]\w*)/gi,
                    function( $0, label ) {
                        // NOTE: Giving "data" precedence over "params".
                        return( popFirstKey( data, params, label ) || "" );
                    }
                );
                // Strip out any repeating slashes (but NOT the http:// version).
                url = url.replace( /(^|[^:])[\/]{2,}/g, "$1/" );
                // Strip out any trailing slash.
                url = url.replace( /\/+$/i, "" );
                return( url );
            }
            // I take 1..N objects and a key and perform a popKey() action on the
            // first object that contains the given key. If other objects in the list
            // also have the key, they are ignored.
            function popFirstKey( object1, object2, objectN, key ) {
                // Convert the arguments list into a true array so we can easily
                // pluck values from either end.
                var objects = Array.prototype.slice.call( arguments );
                // The key will always be the last item in the argument collection.
                var key = objects.pop();
                var object = null;
                // Iterate over the arguments, looking for the first object that
                // contains a reference to the given key.
                while ( object = objects.shift() ) {
                    if ( object.hasOwnProperty( key ) ) {
                        return( popKey( object, key ) );
                    }
                }
            }
            // I delete the key from the given object and return the value.
            function popKey( object, key ) {
                var value = object[ key ];
                delete( object[ key ] );
                return( value );
            }
        }
    );

Usage
After including, and injecting it you should be able to perform the following
httpi({
    method: "post",
    url: "/sample/:id",
    data: {
        id: "1"
    }
});

And it will call to "/sample/1" with POST and no more data.
Source: http://www.bennadel.com/blog/2613-using-url-interpolation-with-http-in-angularjs.htm
Running sample: http://plnkr.co/edit/xnPpzweXZFQvSccA5xFK?p=preview


text:
Q: How to animate Custom Marker on Polyline instead of icon in Google Maps API V3? I'm making a Map where my custom created marker will animate on Polyline from initial point to last point. Currently its working fine with "google.maps.SymbolPath.CIRCLE" icon. But i want to use my custom marker instead of this "google.maps.SymbolPath.CIRCLE" icon. Can someone help to do this.
it will be great if someone help me in short time. Thanks in Advance.

A: For adding custom icon you have to set icon value in your marker object.
Following is sample how to add custom icon
var marker = new google.maps.Marker({
    position: map.getCenter(),
    icon:'https://cdn4.iconfinder.com/data/icons/pictype-free-vector-icons/16/location-alt-512.png',
    draggable: true,
    map: map
});

In icon youe have to give path of your custom icon.
Demo for this available here
If you want to add animation on icon on click event than first add click listener
google.maps.event.addListener(marker, 'click', toggleBounce);

and in that function do something like that
if (this.getAnimation() != null) {
    this.setAnimation(null);
} else {
    this.setAnimation(google.maps.Animation.BOUNCE);
}

New demo here


text:
Q: Better to have multiple adapters or multiple activities? I have a hierarchical data structure. As an example, lets consider my data television shows. Each show has multiple seasons and each season has several episodes. I want to have a list that displays all shows. When a show is clicked the list will then display all seasons for that show and when a season is clicked the list will show all episodes for that season.
OK so with that out of the way, currently I have ONE Activity that implements a Loader through LoaderCallbacks. This loader returns a full hierarchy of data (AKA all shows with all seasons with all episodes). I then use a different ArrayAdapter depending on the level of data I'm on.
Is this the 'right' way to handle this kind of data? Should I instead have a loader and activity and adapter for each level of the data?
Sorry if this is confusing, thank you in advance for your insight.

A: There really is no right or wrong here. I would go for one activity and adapter per set of data. This will make your activities less complex and make them decoupled from each other. In your case I would have:

*

*ShowActivity+ShowAdapter

*SeasonActivity+SeasonAdapter

*EpisodeActivity+EpisodeAdapter

Your data model (with Shows, Seasons and Episodes) should be made accessible to the activities and used to initialize each activity and adapter with the correct data.
Once a show has been selected I'd pass on the id of the show to the next activity through the intent bundle, pick up the show id in the SeasonActivity, fetch the relevant seasons from the data model and display them. The same goes for the transition from season to episode.
Using the approach of one activity per list you'll also get nice transitions between activities and don't have to worry about dealing with the back button to navigate up through your hierarchy.


text:
Q: getContentLength() failing for urlConnection, cannot calculate percent download I'm doing a download in an android app and I need to get the content_length in order to display the percent downloaded.
The files reside on a server that my client has set up. On this server, the call to getContentLength() returns -1. Here are the headers:
THIS SERVERS HEADER DOESN'T WORK WITH urlConnection.getContentLength()

    $ curl --head "http://www.server0.com/ango/thefile.m4v"
    HTTP/1.1 200 OK
    Set-Cookie: JSESSIONID=A17762C6B65FD8D35840110F8628DE4B.V5; Path=/; HttpOnly
    X-ServedBy: web114
    Set-Cookie: SS_MID=7315b0cb-054c-4dd8-a013-c7163793becehfjcndg8; Domain=.tangoberretin.com; Expires=Thu, 13-Apr-2023 07:57:07 GMT; Path=/
    Pragma: cache
    Cache-Control: private,max-age=86400
    Last-Modified: Thu, 21 Feb 2013 06:28:24 GMT
    Content-Disposition: attachment; filename="thefile.m4v";
    Accept-Ranges: bytes
    Content-Range: bytes 0-6716578/6716579
    Content-Type: application/octet-stream;charset=UTF-8
    Content-Length: 6716579
    Date: Mon, 15 Apr 2013 07:57:07 GMT
    Server: SSWS
    Set-Cookie: WebPersCookie=Gn5lN9r2EIK+3eKz0tv/bEs4IJpcBzYg22jKvv/JD1eAA1N3D0pevaz3zuXOD3uTT950AQdstGRJgdE=; path=/

So I did a test and put the file on my own server (apache) and everything works fine. Here are those headers:
THIS SERVERS HEADER WORKS WITH urlConnection.getContentLength()

    $ curl --head "http://server1.net/wp-content/video/thefile.m4v"
    HTTP/1.1 200 OK
    Date: Mon, 15 Apr 2013 07:57:42 GMT
    Server: Apache
    Last-Modified: Sun, 14 Apr 2013 23:49:00 GMT
    Accept-Ranges: bytes
    Content-Length: 502365
    Content-Type: text/plain

So my question is what about the first case is causing the failure, and what can I do about it. Ideally I'd leave the files where they are.
*UPDATE**
I've printed out the headers from the android app, and apparently the server doesn't send the Content-Length for the android agent. I don't understand... :(
HTTP/1.1 200 OK
Accept-Ranges :
bytes
Cache-Control :
private,max-age=86400
Content-Disposition :
attachment; filename="04Left_Turning_Check_Step.m4v";
Content-Range :
bytes 0-7019776/7019777
Content-Type :
application/octet-stream;charset=UTF-8
Date :
Mon, 15 Apr 2013 08:39:06 GMT
Last-Modified :
Wed, 02 Jan 2013 18:40:09 GMT
Pragma :
cache
Server :
SSWS
Set-Cookie :
JSESSIONID=0B1D0CFFD975ED2736BFF7BBC23ACD96.V5; Path=/; HttpOnly
SS_MID=5a7bd305-4ac1-4d4d-98a3-67fa26c0db56hfje5d3d; Domain=.tangoberretin.com; Expires=Thu, 13-Apr-2023 08:39:06 GMT; Path=/
WebPersCookie=WIo8mRMTANAAke3GEsDOsONkGZoRcVvqpC4Am/pl/3WFB9hSEGH5DfGiDSKJDLc2nbZBpWFy3/Yfb3s=; path=/
Transfer-Encoding :
chunked
Vary :
Accept-Encoding
X-Android-Received-Millis :
1366015147201
X-Android-Sent-Millis :
1366015146842
X-ServedBy :
web115

A: The key thing here is the following:
Transfer-Encoding :
chunked

Chunked transfer encoding is described here.
In a nutshell chunked transfer encoding allows the server to send large content in a sequence of chunks without first having to determine the size of the content before sending. This allows the server to be much more efficient about how it loads the content from storage in order to send it the client.
I think that you need to speak with your client and tell him that if the server provides a valid, accurate Content-Length in the response headers then you can provide a progress report, but otherwise you cannot. Alternatively are you able to make an initial request to get information about the content (including the content size) and then make a second request for the content itself? If so, then you are able to provide a progress report.

A: Old post, but the explanation by Mark helped point me to my solution.

Make a call to the url using the following call. This allows the content length to be returned without the server going into "Chunked" mode.
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse execute = client.execute(httpGet);
int contentLength = (int)execute.getEntity().getContentLength();

You can then  remake the the request using URLConnection and use the already returned content length for calculations


text:
Q: Improving tesseract digit recognition I am using Tesseract v5.1.0 to identify the digits from the image below using the command:
tesseract 146_164.jpg stdout -c tessedit_char_whitelist=0123456789

The result is 168 14. What can I do to improve the accuracy?


text:
Q: how to use different shape of UIButton I am having below image for UIButton background image.
But UIbutton shape  by default is round rect.So touch up inside event will work only in round rect area.
So how can i support touchup inside event for below shape (entire area).

A: You can use UIButtonTypeCustom and give the correct frame.

A: Hope this link helps.
To create an irregular shaped button, you need to create custom button and perform hitTest to check if button was pressed or empty space was pressed.


text:
Q: Pretending to be another user with Flask When I need to get information about the current logged in user in a flask web app, I import current_user like this:
from flask_login import current_user

And then I use some attributes, for example current_user.role to determine the type of user, or current_user.username, and based e.g. on the username I can also access the DB data and user settings associated with that particular user.
In order to provide a better support to specific users having specific issues, I am realising that it could be useful to "impersonate" them, that is logging in with my admin account but then pretending to be them instead.
I have seen this being done successfully on some legacy systems I do not own (but maintained by me), and I think it's very useful when inspecting issues.
An attempt I would have in mind is "overriding" current_user if an admin (like me) chooses a new impersonation function that I could implement. Or replacing current_user with some adapter class or with something that implements a common interface.
Or perhaps Flask, and in particular Flask-Login, already provides a mechanism to do this? I tried to look online in the Flask documentation with no success. Do you have any advice?


text:
Q: Avoinding duplicate ranks with PROC RANK I would like to use PROC RANK to rank multiple variables.  For simplicity the code below only demonstrates using a single variable.
In the case of a tie, I would like proc rank to just iterate across the next rank values.  The example code I give below gives the duplicate values (333) ranks of 3.5 and 3.5.  I would like it to just assign 3 and 4 instead.
Is there a way to do this using PROC RANK?  I can fix it in a data step but if I can do it within the proc then that will keep things neater.
data have;
  input x;
  datalines;
100
200
333
333
;
run;

proc rank data=have out=dont_want;
  var x;
  ranks x_rank;
run;

A: You're better off with a data step if you need to consistently increase the rank.
proc sort data=have;
    by x;
run;

data want;
    set have;
    rank+1;
run;

If you have many variables to rank, you can use this macro below:
%macro sequential_rank(lib=, dsn=, out=);

    data want;
        set have;
    run;

    proc sql noprint;
        select name
        into :vars separated by '|'
        from dictionary.columns
        where     memname = %upcase("&dsn.")
              AND libname = %upcase("&lib.")
              AND type    = 'num'
        ;
    quit;

    %do i = 1 %to %sysfunc(countw(&vars., |));
        %let var = %scan(&vars., &i., |);

        proc sort data=&out.;
            by &var.;
        run;

        data &out.;
            set &out.;
            by &var.;

            rank_&var.+1;
        run;
    %end;
%mend;
%sequential_rank(lib=work, dsn=have, out=want);


text:
Q: Where to put resource files on Linux? I'm using makefiles. I have /src, /include, /res and a makefile. The build directory is passed to make. Some of the binaries need resource files stored in /res. One way to access the resources is to tell the makefile to copy /res into the build directory. Is there a more conventional way to do this?
I prefer to have only executables in the build directory and some other directory for the resources. If one chooses, for example, /usr/bin/ for the executables, what's the convention for resource files? /usr/share/?

A: One way to access the resources is to tell the makefile to copy /res
into the build directory. Is there a more conventional way to do this?

No. Copying the resource files to the build directory isn't a wise option. Let the resource files be there in /res makeuse of the VPATH variable in makefile. You can assign the directory path to VPATH so that make will search for the file in that folder after searching the current folder.


text:
Q: Like excel Mround function in Javascript I am trying to round a decimal number to nearest fraction number which end with 0 or 5 in Javascript.example if value is 543.55 should return 545 and if value is 541.99 should return 540.
i tried with Math.round()
but not able to achieve.
kindly suggest me how to achieve that.
Thanks in advance,
Bijay

A: Math.round does the job with a little more extra work. Divide by 5, round it, multiply it back by 5. It is a method I used quite a bit in the past. Here is a simple snippet to show it is working.

function RoundTo(number, roundto){
  return roundto * Math.round(number/roundto);
}

alert(RoundTo(543.55, 5));
alert(RoundTo(541.99, 5));


text:
Q: ImageSlider + animation views I have ViewPager + PageAdapter for slide images. I'm trying add Alpha animation button which appears when user tap on screen and disappears when tap again.
When I add clickListner for ImageView or for some invisible layout over ImageView animation button works fine, but slider doesn`t work now. What I should do for combine these 2 functions.
imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Animation aAnim1 = new AlphaAnimation(1.0f, 0.0f);
                final Animation aAnim2 = new AlphaAnimation(0.0f, 1.0f);

                if (VISIBLE_FLAG == true) {
                    aAnim1.setDuration(250);

                    aAnim1.setFillAfter(true);
                    save_btn.startAnimation(aAnim1);
                    exit_btn.startAnimation(aAnim1);
                    VISIBLE_FLAG = false;
                }
                else {
                    aAnim1.setDuration(250);

                    aAnim1.setFillAfter(true);
                    save_btn.startAnimation(aAnim2);
                    exit_btn.startAnimation(aAnim2);
                    VISIBLE_FLAG = true;
                }
            }
        });


text:
Q: Python 3.7.3 Path and VS Code conflict Last week I installed Anaconda but I continue to have problems using that environment in VS Code on Mac OS Mojave. For 2 weekends now I've struggled and struggled to try and figure out this path conflict myself but have not been able to get the interactive terminal in VS Code to match a terminal launched from the Anaconda Navigator. There seems to be ample materials online about how to run an Anaconda ENV in VS Code but after working through the possible solutions I can't figure out the root conflict and so it persists.
VS Code seems to indicate (bottom left status bar) that the correct 3.7.3 Conda environment is active in VS Code but $python --version returns 3.7.2 when tried. VS Code setting "python.pythonPath" for the workspace is pointing at the correct 3.7.3 python.exe location so I can only assume the conflict is with my PATH setting? Do I have to move the /Anaconda/bin to the front?
I really enjoy scripting with VS Code and would really like to get it up and working again with some of the tools from Anaconda.

A: Looks like you have both Mac python (from python.org) + anaconda, and the version from python.org is first in the PATH (the /Library/Frameworks/Python.framework stuff).  You can move the python.org version later in the PATH, or even remove it altogether if you'd like.
If you decide to remove the other python, be sure you don't accidentally remove the MacOS system python (in /System/Library/Frameworks) or you will have to reinstall MacOS.


text:
Q: MongoDB Aggregate subfields with individual date ranges I have a schema which is:
{
"_id" : "12345678",
"action1" : [
    {
        "date" : "2021-01-15",
        "value" : 20
    },
    {
        "date" : "2021-01-14",
        "value" : 16
    }
],
"action2" : [
    {
        "date" : "2021-01-15",
        "value" : 30
    },
    {
        "date" : "2021-01-14",
        "value" : 10
    }
],
"action3" : [
    {
        "date" : "2021-01-15",
        "value" : 40
    },
    {
        "date" : "2021-01-14",
        "value" : 20
    }
],
"action4" : [
    {
        "date" : "2021-01-15",
        "value" : 60
    },
    {
        "date" : "2021-01-14",
        "value" : 40
    }
]

}
Now I want to write an aggregate query to filter out counts within a date range (for last 7 days, or 30 days or 90 days)
so the final sum should look something like the following:
{
    _id: "12345678"
    action1 : {
        alltime: number,
        last7Days : number,
        last30Days: number,
        last90Days: number
    },
    action2: {
        alltime: number,
        last7Days : number,
        last30Days: number,
        last90Days: number
    },
    action3: {
        alltime: number,
        last7Days : number,
        last30Days: number,
        last90Days: number
    },
    action4: {
        alltime: number,
        last7Days : number,
        last30Days: number,
        last90Days: number
    },
}

I am trying to get the total number of actions using $project and $match for a particular _id
But how can I filter the past7days/30days/90days data
My query looks like the following
db.collection.aggregate([
    {
            $project: {
                alltimeAction1: {$sum: "$action1.value"},
                alltimeAction2: {$sum: "$action2.value"},
                alltimeAction3: {$sum: "$action3.value"},
                alltimeAction4: {$sum: "$action4.value"}
            }
    },
    {
        $match: {
            _id: "12345678"
        }
    }
])

is mapReduce the only option available?

A: db.test1.aggregate([
  {
    "$project": {//Reshape actions, you need this as you have dynamic keys
      data: {
        "$objectToArray": "$$ROOT"
      }
    }
  },
  {//Denormalize
    "$unwind": "$data"
  },
  {//Denormalize
    "$unwind": "$data.v"
  },
  {
    "$project": {//Formatting date
      "_id": 1,
      "key": "$data.k",
      "date": {
        "$dateFromString": {
          "dateString": "$data.v.date",
            "format":"%Y-%m-%d"

        }
      },
      "value": "$data.v.value"
    }
  },
  {
    "$addFields": {//Getting the conditions ready
      "7Days": {
        $gte:["$date", new Date(new Date().getTime() - (7*24*3600*1000))]
      },
      "30Days": {
        $gte:["$date", new Date(new Date().getTime() - (30*24*3600*1000))]
      }
    }
  },
  {
      $group:{//Grouping them, you can add few more cases
          "_id": "$key",
                  "7days":{
                      $sum:"$value"
                  },
                  "30days":{
                      $sum:"$value"
                  }

              }
  }

])

You don't need to do this much complex query if you have flattened schema where actionName can be identified by a constant field name.


text:
Q: Getting "__NSArrayI stringByReplacingOccurrencesOfString:withString:" I am trying to get content of "items.snippet.title" from JSON file on server.(Getting JSON Data)
but content that I will get is with Japanese and its unicode escaped
so I converted text using Converting Text.

        ``Getting JSON Data``
        NSString *origin = [NSString stringWithFormat: @"URLIncluding%@",videoID];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:origin]];
        NSData *json = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments error:nil];`enter code here`
        NSString *titleConvert=[array valueForKeyPath:@"items.snippet.title"];

        ``Converting Text``
        NSString* esc1 = [titleConvert stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
        NSString* esc2 = [esc1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        NSString* quoted = [[@"\"" stringByAppendingString:esc2] stringByAppendingString:@"\""];
        NSData* data = [quoted dataUsingEncoding:NSUTF8StringEncoding];
        NSString* unesc = [NSPropertyListSerialization propertyListFromData:data
                                                       mutabilityOption:NSPropertyListImmutable format:NULL
                                                       errorDescription:NULL];
        assert([unesc isKindOfClass:[NSString class]]);
        NSLog(@"Output = %@", unesc);

but I've got error says
 -[__NSArrayI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x7f99a8dc5e70

any one knows solution for this?

A: Looks like the path "items.snippet.title" returns an array. The items key is probably an array in your JSON data.

A: Calling valueForKeyPath on an array returns an array. It can't be any other way because you aren't specifying how / where to index into the array. You need to deal with the array using a specific index or a loop and then navigate the key path to get your string data.

A: When JSON returns an array: Iterate through the array using fast iteration, for example
for (NSDictionary* dict in array)

When you have a dictionary: Access the elements with subscription syntax, for example
NSString* aString = dict [@"title"];

Don't use methods starting with "value". You don't understand what they do. No, you don't, because if you did, you wouldn't be asking questions here. They may sometimes do what you want, which then may lead to horrible bugs later on. Apart from that they are slow :-(
The error message should be obvious: There is something that you think is an NSString, but in reality it is an NSArray. That's your fault. Sending an NSString message to the NSArray crashes.
BTW. You have an array. What makes you think it has exactly one element? Having an array would be quite pointless then. Write code that can handle multiple array elements.


text:
Q: Animate Canvas using for loop and setInterval I'm trying to animate canvas using for loop and setInterval, but no luck so far... Here's what I have in my code:
//loop function
function loop(){
    var dynamic = 0;
    var v = 10;
    var x, y;

    for (dynamic = 0; dynamic < v; dynamic++) {
        x = dynamic * 1;
        y = dynamic * 1;
        c.clearRect(0, 0, 350, 350);
        c.fillStyle = '#87CEEB';
        c.beginPath();
        c.arc(x, y, 10, 0, Math.PI*2, false);
        c.fill();
    }
}

setInterval(loop, 20);

Thanks so much in advance!

A: Maybe you should move the dynamic variable to the outside? You seem to draw the circle at the same point every loop.
var dynamic = 0;
//loop function
function loop(){
  var v = 10;
  var x, y;
  x = dynamic * 1;
  y = dynamic * 1;
  c.clearRect(0,0, 350,350);
  c.fillStyle = '#87CEEB';
  c.beginPath();
  c.arc(x,y, 10, 0, Math.PI*2, false);
  c.fill();

  ++dynamic;
}

setInterval(loop,20);

A: As said before: move your dynamic out of the animation loop and change dynamic inside the loop.
A summary of animation is this:

*

*Set your starting variables (like dynamic) outside your  for loop

*Inside the animation loop() you want to animate the canvas by 1 move (not many moves), like this:
  + Increment your dynamic variable to induce motion.

  + Set your x & y to reflect the changes to dynamic.

  + Clear the canvas to prepare for this animation frame

  + Draw stuff!

*After the loop, start the animation with setInterval()

*If you animation runs off the screen, you might as well turn it off!
Here is some code and a Fiddle:   http://jsfiddle.net/m1erickson/fFfRS/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

        var canvas=document.getElementById("canvas");
        var c=canvas.getContext("2d");

        // set the dynamic outside the loop
        var dynamic = 10;
        var x;
        var y;

         //loop function
        function loop(){

            // change dynamic
           dynamic=dynamic*1.1;
           x = dynamic;
           y = dynamic*1.2;

            // stop the the animation if it runs out-of-canvas
            if (x>canvas.width || y>canvas.height){
                c.clearRect(0,0,canvas.width,canvas.height);
                clearInterval(myTimer);
                alert("animation done!");
            }

           // clear the canvas for this loop's animation
           c.clearRect(0,0,canvas.width,canvas.height);
           c.fillStyle = '#87CEEB';

           // draw
           c.beginPath();
           c.arc(x,y, 10, 0, Math.PI*2, false);
           c.fill();
        }
        var myTimer=setInterval(loop,20);

    }); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=400 height=400></canvas>
</body>
</html>


text:
Q: How can I check if a Express.js session is active? I was trying to check if a session is active in an Express.js session but couldn't find anything relatable. I am storing my sessions in a MongoDB store with connect-mongo. I basically need to check if a user's session is active to display an active icon on their avatar (front-end not included in this question). I only want to create the back-end API to do that.
Thank you for help.

A: Right now you probably have a bunch of sessions in your database. In order to find them in your express-app, you need to create a schema so mongoose knows what to look for:
// models/session.js
const sessionSchema = new mongoose.schema ({
  expires: Date,
  session: String,
});

module.exports = mongoose.model('Session', sessionSchema);

Then, somewhere in your code you need to use mongoose to look into this collection, eg:
const sessions = await Session.find({}).lean();
console.log(sessions) // sessions stored in the database

and then you should have your results. You probably have many sessions so you need to look into the session key and filter out what you're looking for.

A: I have managed to accomplish this using Redis. I have set a TTL(time-to-live) for each object so that if the user doesn't send a GET request to a certain route in some amount of time the object will be removed from Redis thus making the user "incative" when others fetch their status.


text:
Q: Why is my dictionary not being changed outside of my function Any changes that I make in products inside the function changeproducts is not being set outside of the function.
products = {
    "apple": {"price": 3.5, "stock": 134},
    "banana": {"price": 6.82, "stock": 52},
    "cake": {"price": 23, "stock": 5}
    }

def changeproducts():
    #operator enter new products
    items = input("Items: ").split()
    prices = map(float, input("Prices: ").split())
    stocks = map(int, input("Stocks: ").split())
    products = {
        item: {"price": price, "stock": stock}
        for item, price, stock in zip(items, prices, stocks)
    }
    print (products)

changeproducts()
print(products)

A: Python functions can't assign to variables in global scope by default, so it would be creating a new dictionary instead. Add global products to the top of the function:
def changeproducts():
  global products
  ...

A: As Toggle said, edits within a function only exist to that function or it's sub-functions. You can either use a global variable as suggested,
def changeproducts():
    global products
    ...

But you can also use parameters + return values instead
def changeproducts(func_products):
    #use `func_products` instead of `products`
    ...
    return func_products

products = changeproducts(products)
print(products)

When changeproducts is called, you give it the value of products, which it saves as func_products. Then once the function code has finished, it gives func_products as it's return value. The return value is then saved into the products variable again
For more info, check the docs

A: Instead of reassigning the value, you can simply modify the list by using its update method, so in changeproducts do:
products.update(
    {
        item: {"price": price, "stock": stock}
        for item, price, stock in zip(items, prices, stocks)
    }
)


text:
Q: Using non-printable characters as a delimiter in PHP? When storing an array in a file, I implode it with a delimiter, but if any of the values had the delimiter in it, then this would destroy that value (and give me 2 smaller ones).
Is it good practice to use non-printable characters as a delimiter? And if so, how to do that?

A: It used to be a practice in the 80s. Specifically the ASCII charset had some non-printable symbols just for that very purpose.
   034   28    1C    FS  (file separator)        134   92    5C    \  '\\'
   035   29    1D    GS  (group separator)       135   93    5D    ]
   036   30    1E    RS  (record separator)      136   94    5E    ^
   037   31    1F    US  (unit separator)        137   95    5F    _

You could use them like "\036" in PHP, and later split up by them. But JSON or phps serialize() format or even XML are more advisable for webapps than a binary format.

A: To store any data structure inside a file you should use serialize to store and unserialize to restore the data structure again.

A: For this purpose there are many serialization formats that have specifications for how to deal with characters with special meaning in the serialized format. Use one of them, for example JSON, serialized PHP or CSV.

A: I don't think its the best practice, but if you had to do this for some reason then the example below shows a way of doing it using the tab character as a delimiter. This table may be useful for you http://www.asciitable.com/.
$testArray = array('item1', 'item2', 'item3');
$delimiter = chr(9);
$imploded = implode($delimiter, $testArray);
var_dump($imploded);
var_dump(explode($delimiter, $imploded));

Maybe better to use $delimiter = chr(30) as in @mario's answer.