text:
Q: How to make document custom page dimensions? I have seen the options such as a4paper, a5paper, letterpaper, etc... to go in the square brackets after \documentclass, but what I want is 8.25 inches width by 10.75 inches height for one document and 6 inches width by 9 inches height for another one. How is this done?

A: Hope the code is self explanatory.
For first,
\documentclass{article}
\usepackage{blindtext}
\usepackage[paperheight=10.75in,paperwidth=8.25in,margin=1in,heightrounded,showframe]{geometry}
\begin{document}

\Blinddocument

\end{document}

and the second:
\documentclass{article}
\usepackage{blindtext}
\usepackage[paperheight=9in,paperwidth=6in,top=1in,bottom=1in,right=1in,left=1in,heightrounded,showframe]{geometry}
\begin{document}

\Blinddocument

\end{document}

A: Here is method without using a package:
\pdfpagewidth 8.25in
\pdfpageheight 10.75in

A: The geometry package, version 2020/01/02 v5.9, now has the command ''heightrounded'', which calculates for you an integer number of lines of text in ''\textheight''. So, it is suggested that that if you change ''\baselineskip'', that this be done before calling geometry:
\documentclass[11pt,openany]{book}  % XeLatex. pdf output.
  \author{Page Paperton}
  \date{2021 Sep}
  \title{A Custom Paper Size Template}
  \usepackage{comment,kantlipsum,verbatim}
  \usepackage{calc}
  \usepackage{fontspec}
  \setmainfont[Mapping=tex-text]{Minion Pro}
  \newlength{\OriginalBaselineSkip}
  \setlength{\OriginalBaselineSkip}{\baselineskip}
  \usepackage{setspace}
    \setstretch{1.05}    % Set font and line spacing before `heightrounded' below.
  \setlength{\paperwidth}{8.25in}
  \setlength{\paperheight}{10.75in}
  \usepackage[% showframe,
   % left=0.8in,   % 'left' means 'insidemargin'
    right=1.446in,  % 'right' means 'outsidemargin'
    hmarginratio={2:3},
    top=1.446in,
    vmarginratio={1:1},
    marginparwidth=0.6in,
    marginparsep=0.125in,
    heightrounded,  % To make the text block height an integer number of lines.
    driver=pdftex   % Final output is pdf.
             ]{geometry}

%  \usepackage{pdflscape}
% ------- \layout --------------------------------------------------- %
 \usepackage{layout}  % Use \layout to show page geometry             %
   % You can change \layout output metric here..                      % (Heiko Oberdiek)
   % in    = 1/72.27    = 0.013837000                                 %
   % picas = 12/72.27   = 0.166044002                                 %
   % bp    = 72/72.27   = 0.996264010                                 %
   % mm    = 25.4/72.27 = 0.351459804                                 %
   \makeatletter                                                      %
     \renewcommand*{\lay@value}[2]                                    %
     {                                                                %
       \strip@pt\dimexpr0.013837\dimexpr\csname#2\endcsname\relax\,in %
     }                                                                %
   \makeatother                                                       %
% ------------------------------------------------------------------- %
  \usepackage{booktabs}  % For nice looking tables \begin{tabular}{lcr...} ... \end{tabular}
  \usepackage{siunitx}   % Adds 'S' option for aligning table values at decimal point.
  %%%%%%%%%% A macro to display parameters in other units: %%%%%%%%%%%%%%%%%%%
       %%% Example useage: \convertto{in}{\pdfpagewidth}in %%% \the\pdfpagewidth also works.
  \makeatletter
    \def\convertto#1#2{\strip@pt\dimexpr #2*65536/\number\dimexpr 1#1 }
  \makeatother
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  \usepackage[hyphens]{url}
  \usepackage[hidelinks]{hyperref}

  \raggedbottom  % \flushbottom
\begin{document}
%  \pagenumbering{Alph}
  \maketitle
%  \pagenumbering{alph}
  \pagestyle{empty}
  \tableofcontents
  \thispagestyle{empty}
  \pagenumbering{arabic}
  \pagestyle{plain}
 \chapter{Benevolent Misanthropy}
  \section{Mishaps, Adventures, and Battling the Paper Sprites}
     \kant[1-7]
     \newlength{\insidemargin}
       \setlength{\insidemargin}{1.0in}
       \addtolength{\insidemargin}{\oddsidemargin}
     \newlength{\outsidemargin}
       \setlength{\outsidemargin}{\paperwidth}
       \addtolength{\outsidemargin}{-\insidemargin}
       \addtolength{\outsidemargin}{-\textwidth}
     \newlength{\topmrgn}
       \setlength{\topmrgn}{\topmargin}
       \addtolength{\topmrgn}{\headheight}
       \addtolength{\topmrgn}{1.0in}
       \addtolength{\topmrgn}{\headsep}
     \newlength{\bottommrgn}
       \setlength{\bottommrgn}{\paperheight}
       \addtolength{\bottommrgn}{-\topmrgn}
       \addtolength{\bottommrgn}{-\textheight}
     \newlength{\TextWidth}
       \setlength{\TextWidth}{\textwidth}
     \newlength{\TextHeight}
       \setlength{\TextHeight}{\textheight}
     \newlength{\LinesOfText}
     \newlength{\buffer}
       \setlength{\buffer}{\textheight}
       \addtolength{\buffer}{-\topskip}
       \setlength\LinesOfText{1pt*\ratio{\buffer}{\baselineskip}+1pt}

     \newpage
% \begin{landscape}
     \centering
     \begin{tabular}{clSSS} \toprule
       \multicolumn{1}{c}{Number} & Name & pt & in & mm \\ \midrule
        1 & \verb|\paperwidth|     & \convertto{pt}{\paperwidth}     & \convertto{in}{\paperwidth}     & {\convertto{mm}{\paperwidth}}      \\
        2 & \verb|\paperheight|    & \convertto{pt}{\paperheight}    & \convertto{in}{\paperheight}    & {\convertto{mm}{\paperheight}} \\
        3 & \verb|\textwidth|      & \convertto{pt}{\TextWidth}      & \convertto{in}{\TextWidth}      & {\convertto{mm}{\TextWidth}}   \\
        4 & \verb|\textheight|     & \convertto{pt}{\TextHeight}     & \convertto{in}{\TextHeight}     & {\convertto{mm}{\TextHeight}}  \\
        5 & \verb|\left|           & \convertto{pt}{\insidemargin}   & \convertto{in}{\insidemargin}   & {\convertto{mm}{\insidemargin}}    \\
        6 & \verb|\right|          & \convertto{pt}{\outsidemargin}  & \convertto{in}{\outsidemargin}  & {\convertto{mm}{\outsidemargin}}   \\
        7 & \verb|\top|            & \convertto{pt}{\topmrgn}        & \convertto{in}{\topmrgn}        & {\convertto{mm}{\topmrgn}}       \\
        8 & \verb|\bottom|         & \convertto{pt}{\bottommrgn}     & \convertto{in}{\bottommrgn}     & {\convertto{mm}{\bottommrgn}}    \\
        9 & \verb|\marginparwidth| & \convertto{pt}{\marginparwidth} & \convertto{in}{\marginparwidth} & {\convertto{mm}{\marginparwidth}}  \\
       10 & \verb|\marginparsep|   & \convertto{pt}{\marginparsep}   & \convertto{in}{\marginparsep}   & {\convertto{mm}{\marginparsep}}    \\
       11 & \verb|\headheight|     & \convertto{pt}{\headheight}     & \convertto{in}{\headheight}     & {\convertto{mm}{\headheight}}      \\
       12 & \verb|\headsep|        & \convertto{pt}{\headsep}        & \convertto{in}{\headsep}        & {\convertto{mm}{\headsep}}         \\
       13 & \verb|\footskip|       & \convertto{pt}{\footskip}       & \convertto{in}{\footskip}       & {\convertto{mm}{\footskip}}        \\
       \bottomrule
     \end{tabular}

     \flushleft
     \verb|\baslineskip =| \the\OriginalBaselineSkip\ (Original)\par
     \verb|\baslineskip =| \the\baselineskip\ (Current, after \verb|\setstretch|)\par
     \verb|\topskip =| \the\topskip\par
     The number of lines of text = \par
     \verb|(\textheight-\topskip)/\baselineskip + 1 = | \convertto{pt}{\LinesOfText}
% \end{landscape}

     \layout

\end{document}


text:
Q: Cropping map extent in QGIS2Web? I am new to using QGIS and I have been trying to build a Map which will eventually be put on my firm's website with overlaying layers for different indicators in the local area.
I have made a draft map with OS open background and 16 interchangeable layers using QGIS2Web. However, it is taking around 6-8 minutes to load and is very slow.
I think this is due to the size of the underlaying OS map? Does anyone know how to crop the extent of the map in QGIS2Web?

A: I think you might be right that the OS background map could be causing the problem. I don't know the dataset. Is it raster or vector? You would be better off trying to add an XYZ tileserver map for your background. What that means is that, rather than export the whole background map, a link to the remote online source of the XYZ tiles is used.
The first step is to confirm that the OS layer is the one causing the issue. Remove it temporarily from your project, and then export using qgis2web. If it all speeds up, this is the cause.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to iterate over Flux and use result from another Mono to filter the Flux Mono<MyObj1> mono1 = repository.get(id); // data from reactive mongo
Flux<MyObj2> availabilityInfo = getAvailabilityInfo(); // blocking I/O call

What I am trying to achieve is iterate availabilityInfo and need to apply some conditions using mono data and return MyObj2 (which contains delieveryDate and price related information on that date).
I will try to explain in naive coding as below
 foreach(MyObj2 obj : availabilityInfo){
      if(MyObj1.getX() && obj.getY()){
         return or break;
      }
  }

I want to emit the first element from the flux which satisfies the criteria - MyObj1.getX() && obj.getY(), even if there are other elements further in the flux matching the criteria. The criteria is based on the respone from mono which is a reactive mongo db call and few facts from emitted flux element.

A: Way 1:
 Mono<MyObj2> filteredInfo = mono1.flatMapMany(myObj1 ->
                                        availabilityInfo.filter(myObj1 -> myObj1.getX() && myObj2.getY()).take(1)).single();

Way 2:
Mono<MyObj2> filteredInfo  = availabilityInfo.collectList().zipWith(mono1).flatMap(tuple -> {
            List<MyObj2> list = tuple.getT1();
            MyObj1 myObj1 = tuple.getT2();
            for(MyObj2 myObj2:list){
                if(myObj1.getX() && myObj2.getY()){
                    return Mono.just(myObj2);
                }
            }
            return Mono.empty();
        });

flatMapMany is used to create a flux by processing a mono. filter takes a predicate, which forms the basis of filtering the flux.
Example:
 Mono<Integer> mono = Mono.just(3);
        Flux<Integer> flux = Flux.just(1, 2, 3, 4, 5, 6);
        //Way 1
        Mono<Integer> res = mono.flatMapMany(i -> flux.filter(j -> j % i == 0).take(1)).single();

        res.subscribe(System.out::println);

        //Way 2
       flux.collectList().zipWith(mono).flatMap(tuple -> {
        List<Integer> list = tuple.getT1();
        int x = tuple.getT2();
        for(int y:list){
            if(y%x==0){
                return Mono.just(x);
            }
        }
        return Mono.empty();
    }).subscribe(System.out::println);

Both ways will give me the output:
3


text:
Q: Showing results for Index or size is negative or greater than the allowed amount Firefox is showing this error:

Index or size is negative or greater than the allowed amountv

when I execute this code:
   function myDraw(x1,y1){
        var img1 = document.createElement('img');
        img1.src='i12.png';
        img1.onload = function (){
        var c=document.getElementById('myCanvas');
        var ctx=c.getContext('2d');
        ctx.drawImage(img1,0,0,y1,x1,5,5,y1,x1);
        }
        var sizeArrey =[1,13,25,37,49,61,73,85,97,109, 125,140];
        for (var i = 0; i < sizeArrey.length; i++ ){
        y1 = sizeArrey[i];}
        x1 += 2;
        var loopTimer = setTimeout('myDraw('+x1+','+y1+')', 7);
}
function myDraw1(x11, y11){
    var img=document.createElement('img');
    img.src='logo11.png';
        img.onload = function (){
            var c=document.getElementById('myCanvas');
            var ctx=c.getContext('2d');
            ctx.drawImage(img,0,0,x11,50,125,55,x11,50);
            }
     x11 += 1;
     var loopTimer = setTimeout('myDraw1('+x11+','+y11+')', 3 );
}
myDraw(0,0)
setTimeout("myDraw1(0,0)",1400);

Help me please, what is wrong here?


text:
Q: Xcode Transformation static library(.a) to Framework(.Framework) I have a Cocoa Touch Static Library project(compile as a .a file), i got a mission,create a Cocoa Touch Framework project, which has the same function as Static Library(same file, same  resource)
How can i achieve the goal quickly,there is some document explains how to transformation static library(.a) to Framework(.Framework) ?


text:
Q: Visualforce page for email and pdf print I am trying to create the ability to print or email a salesforce page layout without the SF headers and side panel.  When I create the visualforce component it looks fine for the email but the pdf does not space the output fields properly.  Admittedly I am not very familiar with custom visualforce and I am following a model from a previous implementation. Below is the main vf page, the pdf page, and the component.  Is it possible to do this with one component or do I need to have two?  It would be great to have it look just like the page layout in SF.  I have a feeling it is some of the code in the pdf vf page, but to be honest I don't totally understand all the options used by the previous developer.
Main vf:
<apex:page sidebar="false" showHeader="false" tabStyle="Account"
       standardController="Affiliate_Consulting_Engagement__c"
       extensions="pdfExtension"
       applyHtmlTag="false" applyBodyTag="false" >

<!-- generic markup for pdfExtension is in a form by itself... -->
<apex:form >
<apex:pageBlock >
<apex:pageMessages ></apex:pageMessages>
  <apex:pageBlockSection columns="3">
    <apex:pageBlockSectionItem dataStyle="text-align:left;">
      <apex:commandLink action="{!transferTopage }" value="Save PDF" styleClass="btn" id="btnPdf">
          <apex:param name="TransferPage"
                      assignTo="{!TransferPage}"
                      value="Affiliate_Engagement_Pdf" />
      </apex:commandLink>
    </apex:pageBlockSectionItem>
    </apex:pageBlockSection>
  <apex:pageBlockSection columns="1" >
    <apex:pageBlockSectionItem dataStyle="text-align:left;">
      <apex:outputLabel for="recipientEmail" value="Send To"/>
      <apex:inputText value="{!recipientEmail }" size="40"/>
    </apex:pageBlockSectionItem>
    <apex:pageBlockSectionItem dataStyle="text-align:left;">
      <apex:outputLabel for="subjectEmail" value="Email Subject (Optional)"/>
      <apex:inputText value="{!subjectEmail }" size="40" />
    </apex:pageBlockSectionItem>
    <apex:pageBlockSectionItem dataStyle="text-align:left;">
      <apex:outputLabel for="bodyEmail" value="Email Text (Optional)" />
      <apex:inputTextarea value="{!bodyEmail}" rows="6" cols="20" richText="true" />
    </apex:pageBlockSectionItem>
    <apex:pageBlockSectionItem dataStyle="text-align:left;">
      <apex:commandLink action="{!emailPdf }" value="Email PDF" styleClass="btn" id="btnEmail">
          <apex:param name="TransferPage"
                      assignTo="{!TransferPage}"
                      value="Affiliate_Engagement_Pdf" />
      </apex:commandLink>
    </apex:pageBlockSectionItem>
  </apex:pageBlockSection>
</apex:pageBlock>
</apex:form>

<c:AffEngComponent Engage="{!Affiliate_Consulting_Engagement__c }" RenderPDF="false" />
</apex:page>

PDF page:
<apex:page sidebar="false" showHeader="false" tabStyle="Account"
       standardController="Affiliate_Consulting_Engagement__c"
       contentType="application/pdf" renderAs="PDF"
       applyHtmlTag="false" applyBodyTag="false" >

<head>
    <style type="text/css">
            @page { size:landscape; margin:4px }
            body { font-family: 'Arial Unicode MS'}
            label { font-weight: bold; font-size: 14px; padding-left:4px; padding-top:2px}
            .newpage { page-break-after:always}
            .header { font-weight: bold; font-size: 14px; padding-left:6px; padding-top:2px}
            .header2 { font-weight: bold; font-size: 14px; padding-left:6px; padding-bottom:4px; padding-top:16px}
            .rosterheader { font-weight: bold; font-size: 14px; padding-left:6px; padding-top:8px}
            .field { font-weight: bold; font-size: 11px; padding-left:6px; padding-top:6px}
            .hiddenfield { visibility: hidden}
            .blankline { visibility: hidden; font-weight: bold; font-size: 11px; padding-top:12px}
    </style>
</head>

<c:AffEngComponent Engage="{!Affiliate_Consulting_Engagement__c }" RenderPDF="true" />

</apex:page>

Snippet from component - still in development. Need to confirm before adding all the fields.
<apex:component controller="AffEngController">

<apex:attribute name="Engage"
                type="Affiliate_Consulting_Engagement__c"
                description="Affiliate Consulting Engagement"
                required="true"
                assignTo="{!AffEngage}"/>

<apex:attribute name="RenderPDF"
                type="Boolean"
                description="Render as PDF"
                required="true"
                assignTo="{!onlyIfPDF}"/>

<apex:form >

<apex:pageBlock mode="maindetail" >
    <apex:pageBlockSection title="Oriel STAT A MATRIX" columns="1" >
        <apex:outputText styleClass="header1" label="" value="Consulting Engagement Details for {!Engage.Account_Name__c} - Details as of {!TODAY()}" />
    </apex:pageBlockSection>
    <apex:pageBlockSection title="Affiliate Consulting Engagement Detail" columns="2" >
        <apex:outputField value="{!Engage.Name}"/>
        <apex:outputField value="{!Engage.User__c}"/>
        <apex:outputField value="{!Engage.Engagement_Code__c}"/>

    </apex:pageBlockSection>

</apex:pageBlock>

</apex:form>

</apex:component>

A: You could try monkeying with the CSS for print using display:none for elements you want to hide.
@page print{
.header{display:none;}
.header2{display:none;}
//etc for footer, side panel or whatever else you've got
}

Worked for me but then again I'm lazy.


text:
Q: JQuery $.post is not working This is my Index.cshtml file (I'm learning MVC .NET), and when I click on the Add button to add a new user, this user is not added when I go and check my Api.
I know that both the route (api/users) and the Json object are correct, and the script is being rendered.
I'am using Visual Studio 2017 for Mac and my Api service is Service Stack.
@model dynamic

    @{
        ViewBag.Title = "Protein Tracker";
        Layout = "../Shared/_Layout.cshtml";
    }
@section scripts
{

}

Protein Tracker

    Select a user
    <select id="select-uder"></select>

Add new user

    Name
    <input id="name" type="text" />

    Goal
    <input id="goal" type="text" />

    <input id="add-new-user-button" type="button" value="Add" onclick="AddNewUser()" />

A: Thank you for the help guys, I tried everything everyone suggested, but when I used the Chrome WebInspector (like @mythz suggested) I discovered that "$" was not defined, so I understood that my code was not being recognized as JQuery or something like that. And when I added the following line of code it worked as expected:


text:
Q: Partial harmonic sums with denominators from a fixed set of primes It is well known that the harmonic sum $\sum_1^\infty \frac{1}{n}$ diverges to infinity, and more over that we can approximate using the integral of $\frac{1}{x}$ to get that $\sum_1^N \frac{1}{n} \sim \ln(n)$.
In my problem I have a fixed finite set of primes $S$, and I want to approximate $\sum_{n\in <S>, n\leq N} \frac{1}{n}$ where $<S>$ is the set of natural numbers which are product of primes from $S$. Unlike the harmonic sum, when $N$ goes to infinity this sum converges to $\prod_{p\in S}\frac{p}{p-1}$, so the question is what is the rate of convergence of this summation.


text:
Q: Improve profvis performance for profiling shiny app I have a very large and complex R Shiny app and I am trying to find bottlenecks or parts of the code to improve via the profvis package.
The problem is that profvis itself is performing very slowly (because of the processes and functions in my shiny app) so that it's lagging and almost not possible to properly view & navigate through the profile or the flame graph.
Starting the profvis profile via R or via browser (firefox & chrome tested) doesn't really make a big difference here.
I am only testing one (the main) feature/calculation in my shiny app which is initiated by one action button, thus I can't really test less features or make the profile "shorter".
Any help or tips are appreciated. Especially ways to run profvis faster. Another option I tried was to only wrap parts of my code inside the shiny app with profvis, but I didn't find a way to get this work.
Thank you!


text:
Q: Normalization of custom PDF I needed to implement a couple of probability density functions li:
import numpy as np

def bekkers(x, a, m, d):
    P = a*np.exp((-1*(x**(1/3) - m)**2)/(2*d**2))*np.power(x, -2/3)
    return(P)

The problem is, it has no intrinsic normalization, so it has to be normalized by hand. I tried using scipy.integrate.quad for computing the integral of the function from 0 to infinity, and using it as a denominator for P, but it is extremely slow and it interferes with the optimization when I try to use the function for the nonlinear fitting. What is the most elegant and fast way to do this?


text:
Q: React conditional onClick with ampersand I want to edit a card if allowed=true. I came up with this solution:
const editCard = (onEdit, id, allowed) => {
    if (allowed) {
        onEdit(id);
    }
};

<Card onClick={() => editCard(onEdit, id, allowed)}>Card</Card>

I thought of making a simpler onClick like so:
<Card onClick={() => allowed && onEdit(id)}>Card</Card>

Can I make on onClick like so with the ampersand? If allowed=true then edit, otherwise onClick should not do anything.
It seems to work but I don't know if it will always work. Can this cause bugs and is there a better way to implement this click event?

A: Yes, it will work as expected :)
true && something() calls something function
false && something() returns just false while not calling something

A: Yes, that will work. But you may also use like:
<Card allowed onClick={() => onEdit(id)}>Card</Card>

Then check the allowed props.
Just using allowed is equivalent to allowed={true}. If the allowed option is false you want to send, you don't need to pass the props.
But in your case, it's dynamic. So, you can use like:
<Card allowed={allowed} onClick={() => onEdit(id)}>Card</Card>

So, depending on the case it will be either allowed={true} or allowed={false}.

And oh, you want to use it in editCard, so you may just use like:
 <Card onClick={() => onEdit(id, allowed)}>Card</Card>

A good use case with conditional statement would be to use like: (only show card if allowed is true)
 {
   allowed &&
   <Card onClick={() => onEdit(id)}>Card</Card>
 }

This way, you're ensuring clear instruction with your code. So, you found sorts of ways. Happy coding!


text:
Q: Smart way to aggregate API data async I am looping through a list of objects that each have a single key-value pair, address which is type string
I want to built an object with the results of API requests for each address that tell me how often a token symbol appears. However, I think that because I'm running all of these requests in parallel, I may be over-writing the tokenKeyValue count. Is there a smarter way of doing this, that preserves the parallelization to keep things fast?
const tokenKeyValue: any = {};
let addressesCompleted = 0;
await Promise.all(segmentData.users.map(async (user: {address: string}, i) => {
  try {
    const tokenBalances = await getBalancesForUser(
      user.address,
    );

    if (tokenBalances && tokenBalances.length > 0) {
      for (const token of tokenBalances) {
        if (tokenKeyValue[token.symbol]) {
          tokenKeyValue[token.symbol]++;
        } else {
          tokenKeyValue[token.symbol] = 1;
        }
      }
    }
  }
  catch(e) {
    console.error(e);
  }
  finally {
    addressesCompleted++;
    // Check we are done looping
    if (addressesCompleted === segment.users.length) {
      // Calculate final tokenCount
      const tokenCount = [];
      for (const token in tokenKeyValue) {
        tokenCount.push({
          symbol: token,
          value: tokenKeyValue[token],
        });
      }
    }
  }
}));

A: Instead of using

addressesCompleted++;
// Check we are done looping
if (addressesCompleted === segment.users.length)

just move that code after the await Promise.all(…):
const tokenKeyValue: Record<string, number> = {};
await Promise.all(segmentData.users.map(async (user: {address: string}) => {
  try {
    const tokenBalances = await getBalancesForUser(user.address);

    for (const token of tokenBalances || []) {
      tokenKeyValue[token.symbol] ??= 0
      tokenKeyValue[token.symbol] += 1;
    }
  } catch(e) {
    console.error(e);
  }
}));

// Calculate final tokenCount
const tokenCount = Object.entries(tokenKeyValue).map(([symbol, value]) => ({symbol, value}));

A: You could make all the requests in parallel and then use Promise.all() to wait until all the requests resolve and then count the symbols.
const users = [{
  address: '12 main st'
}, {
  address: '32 main st'
}];

const promises = users.map(user => {
  return getBalancesForUser(user);
});

Promise.all(promises).then((tokenBalancesList) => {
  const countByTokenSymbol: any = {};
  for (let tokenBalances of tokenBalancesList) {
    for (let key in tokenBalances) {
      const tokenBalance = tokenBalances[key];
      countByTokenSymbol[tokenBalance.symbol] = countByTokenSymbol[tokenBalance.symbol] || 0;
      countByTokenSymbol[tokenBalance.symbol]++;
    }
  }

  const tokenCount = [];
  for (let tokenSymbol in countByTokenSymbol) {
    tokenCount.push({
      symbol: tokenSymbol,
      value: countByTokenSymbol[tokenSymbol]
    });
  }

  console.log(tokenCount);
});

//placeholder getBalancesForUser function
async function getBalancesForUser(user: {address: string}) {
  return [{
    symbol: user.address[0]
  }, {
    symbol: user.address[1]
  }];
}


text:
Q: Is there any self complementary graph of order 5 other than C5 The concept of a self-complementary graph as I learned is, a graph that is isomorphic to its complement is called self-complement. I have some examples in mind of the self-complementary graph of order five but I am confused about, how can we find a self-complementary graph of order five other than copies of C5. Kindly give me the answer with an example.

A: For this kind of questions, I like to simply use sage with geng. Try this code
for g in graphs.nauty_geng("{0} -c".format(5)):
    if g.is_isomorphic(g.complement()):
        g.show()

Yielding to

and

A: You can analyze this question as follows: Suppose $G=(V,E)$ is a self-complementary graph of order $5$ and let $\overline{G}=(V,E')$ denote its complement.
First, since $G\cong\overline{G}$, we have $|E|=|E'|$. Besides, it is clear that $G\cup\overline{G}=K_5$ and $E\cap E'=\emptyset$, so $$|E|+|E'|=\binom{5}{2}=10.$$ Thus, $|E|=|E'|=5$.
Now you consider the degree sequence $d_1\leq d_2\leq d_3\leq d_4\leq d_5$ in $G$. The degree sequence in $\overline{G}$ is $$4-d_5\leq4-d_4\leq 4-d_3\leq 4-d_2\leq 4-d_1.$$ Again, since $G\cong\overline{G}$, we must have $4-d_5=d_1$, $4-d_4=d_2$ and $4-d_3=d_3$. That is, it yields $$d_1+d_5=d_2+d_4=4$$ and $d_3=2$. Besides, $d_1>0$, for $d_1=0$ implies $d_5=4$. It is impossible for a graph of order $5$ containing both an isolated vertex (degree $0$) and a vertex adjacent to all others (degree $4$). Note that $d_2\leq d_3=2$ and consider the following cases:

*

*Suppose $d_2=1$. Then $d_4=4-d_2=4-1=3$. Since $1\leq d_1\leq d_2=1$, we must have $d_1=1$. Thus, the degree sequence of $G$ is $1,1,2,3,3$. This is precisely the first graph shown in David's answer.

*Suppose $d_2=2$. Then $d_2=d_3=d_4=2$. Of course, if $d_1=2$, then $G$ is $C_5$. What if $d_1=1$? As we can see, the degree sequence now becomes $1,2,2,2,3$. There are two graphs of order $5$ possessing such sequence, but they are neither self-complementary nor isomorphic to each other.
In general, all the examples are displayed in David's answer.


text:
Q: How to create a dataframe from extracted hashtags? I have used below code to extract hashtags from tweets.
def find_tags(row_string):
    tags = [x for x in row_string if x.startswith('#')]

    return tags

df['split'] = df['text'].str.split(' ')

df['hashtags'] = df['split'].apply(lambda row : find_tags(row))
df['hashtags'] = df['hashtags'].apply(lambda x : str(x).replace('\\n', ',').replace('\\', '').replace("'", ""))
df.drop('split', axis=1, inplace=True)
df

However, when I am counting them using the below code I am getting output that is counting each character.
from collections import Counter
d = Counter(df.hashtags.sum())
data = pd.DataFrame([d]).T
data

Output I am getting is:

I think the problem lies with the code that I am using to extract hashtags. But I don't know how to solve this issue.

A: Change find_tags by replace in list comprehension with split and for count values use Series.explode with Series.value_counts:
def find_tags(row_string):
    return [x.replace('\\n', ',').replace('\\', '').replace("'", "")
            for x in row_string.split() if x.startswith('#')]

df['hashtags'] = df['text'].apply(find_tags)

and then:
data = df.hashtags.explode().value_counts().rename_axis('val').reset_index(name='count')


text:
Q: Autofill form depending on one field in Rails 4 I want to autofill some fields with data from database depending on the value in the first field.
This is what i have:
$(function(){
   $('#request_name').on('focusout', function () {
     var clientName = $(this).val();
     $.ajax({
    url: "/requests/autofill/"+clientName,
    type: "GET",
    dataType: ...some dataType
    })
   });
});

When user types some text into the first field with id "request_name" and focuses out i want to take that value search for it in db and fill some other fields with returned values.
Here is my controller:
def autofill
    @client = Client.where("name=?",params[:name]).take
    respond_to do |format|
     ... some code
    end
   end

And route for that:
get "requests/autofill/:name" => "requests#autofill", as: :requests_autofill

Also i have created autofill.js.erb file in my requests view. I think i should handle filling form fields inside that file.
But, here i do not know how to send proper ajax request to the server and also how to handle it.
If i don't specify dataType server returns the whole page which is autofill.html.erb. I think i should use some other dataType, but i don't know which one.
Also i want to insert returned values to the form fields.
For example one of the fields to be autofilled looks like that
<%= f.text_field :mobile, class: 'form-control' %>

A: Assuming Client has mobile and your input field id is mobile_input, add following script in
autofill.js.erb
$('#mobile_input").val('<%=@client.mobile%>');

A:  $("#request_name").on('focusout', function(){
    $.ajax({
             type: "GET",
             url: "/requests/autofill/"+clientName,
             data: formData,
             success: function(data){

//Use the data returned by the API to fill the from fields, like below
                      $('#field_id').html(data.<json_key>)
                    }
    });
    return false;
 });


text:
Q: Need to perform authentication without giving the credentials from Salesforce Login screen from Mule Use case Scenario: Mule to Salesforce redirection of user to home page without username and password
User details will come from source and based on details i will validate and create the user in Salesforce using Mule.
after creating the user in Salesforce without logging in. i want to redirect the user to enter Salesforce community home page.
Here I am able to redirect to the Salesforce page but how can i enter to community page without logging in
Any suggestion or solutions also welcome but here i require for multiple users

A: If the page requires authentication to be accessed you have to provide that authentication, there is no way around it. You can use any authentication method supported by the HTTP Requester, including OAuth 2 Authorization Code and OAuth 2 Client Credentials. I don't have an example like you want but it is theoretically possible at least.


text:
Q: Multiple databases in an app. How to specify per-model I have several models, one of which uses a database on an external user. The database is defined in the settings file. How would I do the following for this model?
class ItemMaster(models.Model):
    id = models.AutoField(primary_key=True) # auto-added anyways
    guid = models.CharField(max_length=36, unique=True)

    db = using('avails') # <== use this database

Note: the only thing I care about here is being able to do a get_queryset query. I don't need a full database router.

A: As Shang Wang has pointed out in the comments, using a database router is the best solution.

Whenever a query needs to know which database to use, it calls the
  master router, providing a model and a hint (if available). Django
  then tries each router in turn until a database suggestion can be
  found. If no suggestion can be found, it tries the current _state.db
  of the hint instance. If a hint instance wasn't provided, or the
  instance doesn't currently have database state, the master router will
  allocate the default database.

If you are not keen on using routers, one alternative is to call the using on each and every queryset API call to define which database to use.
ItemMaster.objects.using('avails').all()
itemmaster.save(using='avails')
itemmaster.delete(using='avails')

But this will not be very DRY. A second alternative is to create a custom manager and override each of the methods to add the using('avails') fragments. But this involves writing a lot more code that you would write when using a router.


text:
Q: How can I create wrapper for the types in the simple_form gem? I want to create a wrapper for my app, but html for different types should be different. So, I can write just
= simple_for_for @task, wrapper: :mine_special do |f|
  = f.input :first_attr, type: :sring
  = f.input :second_attr, type: :boolean

so, my initializer will contain definitions for both string & boolean types:
config.wrappers :mine_special, types: [:boolean] do |b|
  # configs here for check box
end

config.wrappers :mine_special, types: [:string] do |b|
  # configs here for text field
end

How can I do that?

A: In short
The best solution I can think of is just naming your wrappers differently:
config.wrappers :mine_special_boolean
config.wrappers :mine_special_string

It follows simple_form semantics nicely and also eliminates the need to remember to pass type option.
Explanation
By the time you are passing wrapper: :mine_special option in the template, simple form initializers code has already been run, so you cannot simply insert an if statement in wrappers block. When you call the wrapper from template, it merges your options with the ones you defined in initializers.
I can imagine a way to override some methods in SimpleForm::FormBuilder to route your wrapper calls based on type option you pass in, but at that time I'll probably be wondering if it's worth the complexity.


text:
Q: The PDF result from SelectPDF HtmlToPdf is different when i run it from released Website in IIS (dotnet core) I'm working in a website with PDF generation, but the result changes between the local execution and the final deployed site (the site effectively generates the PDF and the same binaries were checked with dotnet run -c Release and the result is the same in localhost Release and localhost Debug).
I looked for some information or specific instructions for deployment, these are the official docs from https://selectpdf.com/html-to-pdf/docs/html/Deployment.htm but it doesn't have something special, I already made bigger modifications and I don't know if this is something like a config problem.
This is the function for Pdf Rendering
private Byte[] GetPdf(DocumentViewModel model)
{
    var url = "a simple URL";
    var converter = new HtmlToPdf();
    converter.Options.CssMediaType = HtmlToPdfCssMediaType.Screen;
    converter.Options.JavaScriptEnabled = true;
    converter.Options.MarginBottom = 0;
    converter.Options.MarginRight = 0;
    converter.Options.MarginLeft = 0;
    converter.Options.MarginTop = 0;
    converter.Options.PdfPageSize = PdfPageSize.Letter;
    converter.Options.AutoFitWidth = HtmlToPdfPageFitMode.AutoFit;
    converter.Options.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
    converter.Options.PdfPageOrientation = PdfPageOrientation.Landscape;
    converter.Options.MinPageLoadTime = 2;
    converter.Options.MaxPageLoadTime = 30;
    var doc = converter.ConvertUrl(url);
    using (var stream = new MemoryStream())
    {
         doc.Save(stream);
         return stream.ToArray();
    }
}

My web.config doesn't have anything particularly special, but here it is
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\WebSite.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
   <staticContent>
    <remove fileExtension=".pdf" />
     <mimeMap fileExtension=".pdf" mimeType="application/pdf" />
   </staticContent>
    </system.webServer>
  </location>
    <system.web>
        <sessionState timeout="60" />
    </system.web>
    <system.webServer>
        <caching>
            <profiles>
                <add extension=".pdf" policy="DisableCache" kernelCachePolicy="DisableCache" />
            </profiles>
        </caching>
    </system.webServer>
</configuration>

With the current method, my results are different from local to server. I need to set the placement of elements in the website but I can't if I don't know which viewport is selected.

A: Content is resized during the conversion to pdf:
https://selectpdf.com/docs/ResizingContentDuringConversion.htm
Try to change the viewport width to see what happens:
converter.Options.WebPageWidth = 1024;

Try to set some other values (depending on your web page width): 800, 1920 (these are in pixels).


text:
Q: How to manually trigger BootStrap Validation on blur of a text input event I am using Bootstrap validation for my Application .
Incase if user enters "abc" under text input how to show a validation message , Entered value is not allowed
This is my code
$('#taginsertform').bootstrapValidator(
{
        feedbackIcons:
        {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
        },
        fields:
        {
                recipientname:
                {
                        feedbackIcons: 'false',
                        validators:
                        {
                                notEmpty:
                                {
                                        message: 'Reciepnt Name cannot be empty'
                                }
                        }
                }
        }
}).on('success.form.bv', function(e)
{
        e.preventDefault();
        addTagSbmt();
});

function addTagSbmt()
{
   $('#taginsertform').bootstrapValidator('resetForm', true);
        $('.closemodal').trigger('click');

        return false;
}
$('#myModal').on('shown.bs.modal', function()
{
        $('#taginsertform').bootstrapValidator('resetForm', true);
});

$( "#recipientname" ).blur(function() {

  var recipientnameval = $("#recipientname").val();

  recipientnameval = recipientnameval.toLowerCase();

  if(recipientnameval==='abc')
  {
  alert(recipientnameval);
  // fire bootstrap valdation as invalid data
  }

});

In the below jsfiddle , upon entering abc under text input how can i show a message ?
http://jsfiddle.net/xmrxbL9f/97/

A: In short, no there is no built in bootstrap functionality to do the validation.
Bootstrap simply provides styles to the default HTML input types, HTML input attributes and JavaScript constraints validation functionality. In order to validate an element we call the checkValidity() JavaScript method.
If you are following the BootStrap Form Validation documentation then we can accomplish an onblur event validation with the following snippet.
$(function () { // jQuery ready
    // On blur validation listener for form elements
    $('.needs-validation').find('input,select,textarea').on('focusout', function () {
        // check element validity and change class
        $(this).removeClass('is-valid is-invalid')
               .addClass(this.checkValidity() ? 'is-valid' : 'is-invalid');
    });
});

This example will set the is-valid or is-invalid class on the current element when it looses focus. Note we are assigning event listeners to all input,select,textarea in all forms with the class needs-validation.
If you wish to trigger a different type of notification the same can be applied.
nJoy!

A: You can append the error div on blur. Try it if it matches your requirement.
 $( "#recipientname" ).blur(function() {

  var recipientnameval = $("#recipientname").val();

 recipientnameval = recipientnameval.toLowerCase();
 var errorDiv = "<div class='form-error alert alert-danger fade in'>Please Insert valid data<div>"
 if(recipientnameval==='abc')
  {
   $('.form-group').append(errorDiv);
  }else{
   $('.form-error').remove();
  }
});

Best of luck :)

A: Add an id to the form as formId
var formEl = $("#formId");

formEl.find('input,select,textarea').on('focusout', function () {

    var thisEl = $(this).parent();
    if(!thisEl.hasClass('was-validated')){
        thisEl.addClass('was-validated');
    }

});


text:
Q: jQuery Plugin does not work in a Modal I am using this in a modal: http://www.web2media.net/laktek/2008/10/27/really-simple-color-picker-in-jquery/ but it does not work. The same code:
//Start of document Ready which contains event handlers
$(document).ready(function() {

    $('#ForeColor').colorPicker();
});

<input type="text" value="#333399" id="ForeColor" class="colourPicker" />

works fine in a normal page but as soon as I load it in a jQuery UI Modal (the contents of which come from an ASP.Net MVC partial view) it breaks! It does some of the work, i.e reformats the text box to show the current colour but clicking it does not cause the selector to appear!
I suspect it's an issue with using jQuery inside modals..
Any ideas?

A: Ok figured it out, rather stupid actually!
Basically when you load a modal it is obviously on the same page and to appear above other elements the jQuery UI modal has a z-index of 1002!
As a result any elements on your page, including a lot of jQuery popup elements, will appear underneath the modal and hence appear not be working. Just add a higher z-index (1003+) to the color picker or other jQuery popup css style.
For the one I linked to the div I needed to add was:
div#color_selector
{
   //other stuff
   z-index: 1120;
}

Hope that helps anyone else.


text:
Q: topological isomorphism between a topological group and the identity component of a topological group Let $\Bbb R$ be the group of real numbers with the usual topology and $\Bbb Z$ the group of integers with the discrete topology. Is $\Bbb R$ topological isomorphism by the identity component of $(\Bbb R\bigoplus \Bbb Z)/H$ where $H$ is the subgroup $\{(n,-2n);n\in \Bbb Z\}$?

A: Hint:
Let $\Bbb Z_2$ denote the cyclic group of order 2, with the discrete topology.
Define a map $\phi: \Bbb R \oplus \Bbb Z \to \Bbb R \oplus \Bbb Z_2$ as $(x,n) \mapsto \big(x+\frac{1}{2}n, \;n \pmod 2\big)$.
Then $\phi$ is a surjective homomorphism with kernel $H$, so what does the first isomorphism theorem tell you?


text:
Q: How to do checkIn major version through REST Sharepoint 2013 Im tryin to do checkin major version through REST API.
This url is working just fine and I can do minor version checked in
/sites/developersite/_api/web/GetFolderByServerRelativeUrl('Document')/Files/GetByUrl('file.docx')/CheckIn('Comment')

but I cant get this one working
/sites/developersite/_api/web/GetFolderByServerRelativeUrl('Document')/Files/GetByUrl('file.docx')/CheckIn('Comment', 1)

Argument 1 suppose to be major version checkin type.
Documentation on MSDN  says that second url should be working.
Error that Im getting when second url is used
{
"error":{
   "code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException",
   "message":{
      "lang":"en-US",
      "value":"The expression \"web/GetFolderByServerRelativeUrl('Documents')/Files/GetByUrl('file.docx')/CheckIn('Comment',1)\" is not valid."
        }
    }
 }

A: I haven't done that with REST before, but in this article he uses this syntax:
http://<site url>/_api/web/GetFileByServerRelativeUrl(
  '/Shared Documents/a.txt')/CheckOut()
http://<site url>/_api/web/GetFileByServerRelativeUrl(
  '/Shared Documents/a.txt')/CheckIn(comment='Comment', checkintype=0)


text:
Q: PowerShell Insert into SQL Server issue This is the code I am using:
$command2 = New-Object System.Data.SqlClient.SqlCommand
#$MySql2="Invoke-sql INSERT INTO acubdb.scans (SessionID, Started, Status, Description, Target, Systime, Mailed) VALUES ($SessionVal, $StartedVal, $StatusVal, $DescVal, $TargetVal, $SysDateVal, $MailVal); "

$command2.CommandText = "INSERT INTO acubdb.scans (SessionID, Started, Status, Description, Target, Systime, Mailed) VALUES ($SessionVal, $StartedVal, $StatusVal, $DescVal, $TargetVal, $SysDateVal, $MailVal); "
$command2.Connection = $connect2
$command2.Parameters.AddWithValue("@server", $_.server) | Out-Null
$command2.Parameters.AddWithValue("@instance", $_.instance) | Out-Null

$rowsUpdated = $command2.ExecuteNonQuery()

Write-Output "Updating SQL Database; Adding record for "$SessionVal
Write-Output " "
$connect2.Close()

When I run it, I get this error:

Exception calling "ExecuteNonQuery" with "0" argument(s): "Incorrect syntax near the keyword 'is'."
  At line:10 char:13
  +             $rowsUpdated=$command2.ExecuteNonQuery()
  +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  + FullyQualifiedErrorId : SqlException

What am I missing this time?
Variables are defined and filled outside of this snippet.
Code
$command2.CommandText = INSERT INTO acubdb.scans (SessionID, Started, Status, Description, Target, Systime, Mailed) VALUES (this is a test, 2017-11-17T07:00:01.418178+00:00, processing, name of site, address of site, 20/11/2017 15:57, 0);

A: Your insert statement should look like this. You are missing single quotes around text:
INSERT INTO acubdb.scans
            (sessionid,
             started,
             status,
             description,
             target,
             systime,
             mailed)
VALUES      ('this is a test',
             '2017-11-17T07:00:01.418178+00:00',
             'processing',
             'name of site',
             'address of site',
             '20/11/2017 15:57',
             0);


text:
Q: How can I get a matrix of strings after subsetting strings in a matrix? I have a "little" problem. I have a matrix with strings and I want to extract some parts of the strings in each cell and I want to obtain another matrix.
library (stringr)
ma <- matrix (c("ab", "wz", "k2", "jk"), ncol = 2, byrow = T)
colnames (ma) <- c("c1", "c2")

I've used:
str_sub (ma, 1, 1)

But it didn't give me what I wanted (a list of the values)
and I want to obtain another matrix like this:
  C1   C2
  "a"  "w"
  "k"  "j"

Thank you very much for any advice or solutions
Richard

A: You can try this:
sub_ma <- matrix(str_sub(ma,1,1), nrow=nrow(ma), ncol=ncol(ma), dimnames=dimnames(ma))


text:
Q: Restoring an RDS Instance to a backup/snapshot I'm trying to RESTORE an RDS instance to one of it's previous backups/snapshots, but when I follow the provided instructions by Amazon it CREATES a new instance from the backup instead of restoring the existing one.
I would like to just restore the db to an existing state because I have an EC2 instance pointing to it (managed through  a Load Balancer) that I'd prefer to not have to go in and point to the new RDS.
How can I restore an RDS instance back to a previous point in time AND NOT create a new instance from the backup/snapshot

A: Restore to new RDS instance. Then rename or original rds server to something else and apply change immediately. Once the change is processed (2-3 min), rename the restore instance to the same name as the original rds and apply immediately.
RDS dns name within single account only varies by initial part, which is taken from the RDS instance name.

A: Short answer is you can't:

You can't restore from a DB snapshot to an existing DB instance; a new
DB instance is created when you restore.

from here:
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RestoreFromSnapshot.html

A: If you have terraform experience, I found this to be the most reproducible way of restoring from snapshots.
resource "aws_db_instance" "prod" {
  allocated_storage    = 10
  engine               = "mysql"
  engine_version       = "5.6.17"
  instance_class       = "db.t2.micro"
  name                 = "mydb"
  username             = "foo"
  password             = "bar"
  db_subnet_group_name = "my_database_subnet_group"
  parameter_group_name = "default.mysql5.6"
}

data "aws_db_snapshot" "latest_prod_snapshot" {
  db_instance_identifier = aws_db_instance.prod.id
  most_recent            = true
}

# Use the latest production snapshot to create a dev instance.
resource "aws_db_instance" "dev" {
  instance_class      = "db.t2.micro"
  name                = "mydbdev"
  snapshot_identifier = data.aws_db_snapshot.latest_prod_snapshot.id

  lifecycle {
    ignore_changes = [snapshot_identifier]
  }
}

From the terraform documentation.


text:
Q: Why fread() giving extra garbage value I am reading content of a file and and trying to print it, but it is giving extra garbage value.
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>

int main() {
    long length;
    char* content;
    FILE *file = fopen("text.txt", "r");
    fseek(file, 0, SEEK_END);
    length = ftell(file);
    fseek(file, 0, SEEK_SET);
    content = (char *)malloc(length);
    fread(content, 1, length, file);
    printf("%s\n", content);
    return 0;
}

Maybe I have to null terminate content[length] = '\0';?
The more \n newline characters the file has at the end, the more garbage I get.
Any solution, except using calloc?

A: If that is MSVC (clued by #define _CRT_SECURE_NO_DEPRECATE) then the file mode is probably text by default, and all the CR-LF pairs will be shrunk to a single LF when you read it. Getting the file size does not take that into account. Use the number of characters actually read to terminate the string.
content = malloc(length + 1);           // room for terminator
size_t bytes = fread(content, 1, length, file);
content[bytes] = '\0';

A: The file content does not end with the null char.
Your should reset the allocated memory buffer with 0, since it's unknown how many bytes will be read.
content = (char *)malloc(length + 1);
memset(content, 0, length + 1);
fread(content, 1, length, file);

Or you should set the data length while printing
length = fread(content, 1, length, file);
printf("%.*s\n", length, content);

See Is there a way to specify how many characters of a string to print out using printf()?


text:
Q: Rails integration test syntax - using get :edit vs get edit_user_path I'm going through Hartl's exercises in chapter 9, and got to the part about writing integration test for Requiring logged-in users .
I notice that Listing 9.17 (i) uses
get :edit, id: @user

whereas Listing 9.14 (ii) uses:
get edit_user_path(@user)

What's the difference?  For the purpose of testing that logged-in users get redirected to home page if not logged in, the latter works, whereas the former throws an error.
Conceptually, the two statements above look like the same, i) calls the controller action, whereas ii) routes to the resource
Is that right?

A: Indeed, the two code are equivalent conceptually.
They are doing the same thing by issuing a GET request for users/edit.html.erb via edit action in Userscontroller.
However the contexts in which you are testing the above behaviour are different.

The code
get :edit, id: @user

is in the context of testing a controller (UsersController). Therefore you only need to specify the action ("edit" in this case) along with necessary parameters("id" in this case).
get edit_user_path(@user)

is in the context of simulating a user browsing your app, which you can do via integration tests. Here you need to be precise about the routing path since there can be different controllers involved. That is, the context in which an action is called is not restricted to one particular controller.
For example, in Listing 8.40, we have an integration test that simulates a user logging out:
  test "login with valid information followed by logout" do
    get login_path
    post login_path, session: { email: @user.email, password: 'password' }
    assert is_logged_in?
    assert_redirected_to @user
    follow_redirect!
    assert_template 'users/show'
    assert_select "a[href=?]", login_path, count: 0
    assert_select "a[href=?]", logout_path
    assert_select "a[href=?]", user_path(@user)
    delete logout_path
    assert_not is_logged_in?
    assert_redirected_to root_url
    # Simulate a user clicking logout in a second window.
    delete logout_path
    follow_redirect!
    assert_select "a[href=?]", login_path
    assert_select "a[href=?]", logout_path,      count: 0
    assert_select "a[href=?]", user_path(@user), count: 0
  end

In this integration test, there are two controllers involved: UsersControllerand SessionsController.
Specifically:

*

*user_path(@user) in assert_select "a[href=?]",
user_path(@user) is about a show action in UsersController.

*login_path in get login_path calls a new action in
SessionsController.

*login_path in post login_path, session: { email: @user.email,
password: 'password' } calls a create action in
SessionsController.

*login_path in assert_select "a[href=?]", login_path is about
a new action in SessionsController.

*logout_path in assert_select "a[href=?]", logout_path is
about a destroy action in SessionsController.

This is possible in integration tests simply because we are not restricted to a particular controller when calling some actions.
This also explains why the first code you provided
get :edit, id: @user

throws an error in integration tests.
It's not specifying in what controller the edit action is called. (It could be the edit action in AccountActivationsController or PasswordResetsController, for example)
Also, the point you raised

i) calls the controller action, whereas ii) routes to the resource

is important.
Controller tests are purely about testing a controller by issuing rather "low-level", or "machine-level", commands. That is, we submit particular HTTP requests (PATCH in your case) directly to controller actions(edit in your case) without being concerned about simulating a user browsing your app (i.e. user actually clicking a link "Edit Profile"), which you can do with more "high-level" integration tests.


text:
Q: scripting language with easy UI development capabilities I have to develop a simple application for Windows that manages a hashmap.  Users will enter a keyword in a text area and get some data back, that's all it has to do.
The backend part of this is dead simple but I'm unsure of how to produce the UI.
I would like to get some recommendations for scripting languages that include UI creation capabilities.  In the past (more than 15 years ago) I used TCL/TK to do this sort of thing but I'm hoping there is something much simpler that matches the simplicity of my task.

A: Download Visual Studio Express and create a WinForms application. Visual Studio has a Design view that allows you to create UIs with a few mouse drags and clicks; it really is dead simple. And there are many tutorials and examples.

A: Tcl/Tk is still one of the simplest ways to do stuff like this (and has progressed quite far in the past 15 years if you find you need more power later).

A: U can use python Tkinter library , it is easy , for windows you can use Qt for interface design, it is also handy.


text:
Q: are event.target.value and value attribute of input element the same in react? import React from 'react';
import { useState } from 'react';

function MyForm() {
  [state, setState]=useState("");

  return (
    <form>
      <label>Enter your name:
        <input type="text"
               value={state}
               onChange={(event)=>setState(event.target.value)}
         />
      </label>
    </form>
  )
}

When I do two-way binding in react I don't really understand how it works.
As I know, event.target is a property of an event object that refers to the element that triggered the event. So in this case, if we type something in input field, it will trigger the "onChange" which in turn sets the state to the value of element that triggered this change action (input element) and whilst its value is empty string(because its value attribute is equal to the state). So actually state setter function would have set the state to the current state that makes state and also value attribute always to be the same. But off course, I miss something here. Thanks in advance for any explanation.

A: If explain it step by step - it gonna be something like this (in the context of your example) :

*

*State is the reactive variable, so then it changes, your component (and nested components) rerenders. On the first render you just set it to default.

*Then, this variable is hardly assigned to the value of an input. So in a normal situation you wouldn't be able to change the input at all, BUT.

*You set your listener to change the state then this input gets some users interaction. Your type something - your state changes (by that time input is still empty).

*As we already know, we changed the state. Component rerenders with new state. For example - we typed letter "T".

*This rerender causes new state to assignee to the value of your input, you get value="T".

*And boom - you have your new letter.

It can be said that you don't really changing the input - state does.
Hope that explanation was helpful! ;)


text:
Q: Touchpad doesn't work Please, help me. Even after the OS upgrading my touchpad doesn't work properly. Everything is OK about swiping, but in the case I'd like to tap I have to use buttons (it means I have to use buttons instead of using the touchscreen, because it simply doesn't react).
Maybe it happens because of any bug? Is there anybody who also had such an experience?
synclient -l
    LeftEdge                = 43
    RightEdge               = 1045
    TopEdge                 = 38
    BottomEdge              = 666
    FingerLow               = 1
    FingerHigh              = 1
    MaxTapTime              = 180
    MaxTapMove              = 56
    MaxDoubleTapTime        = 100
    SingleTapTimeout        = 180
    ClickTime               = 100
    EmulateMidButtonTime    = 75
    EmulateTwoFingerMinZ    = 282
    EmulateTwoFingerMinW    = 7
    VertScrollDelta         = 25
    HorizScrollDelta        = 25
    VertEdgeScroll          = 0
    HorizEdgeScroll         = 0
    CornerCoasting          = 0
    VertTwoFingerScroll     = 1
    HorizTwoFingerScroll    = 1
    MinSpeed                = 1
    MaxSpeed                = 1.75
    AccelFactor             = 0.15444
    TouchpadOff             = 2
    LockedDrags             = 0
    LockedDragTimeout       = 5000
    RTCornerButton          = 0
    RBCornerButton          = 0
    LTCornerButton          = 0
    LBCornerButton          = 0
    TapButton1              = 0
    TapButton2              = 0
    TapButton3              = 0
    ClickFinger1            = 1
    ClickFinger2            = 1
    ClickFinger3            = 0
    CircularScrolling       = 0
    CircScrollDelta         = 0.1
    CircScrollTrigger       = 0
    CircularPad             = 0
    PalmDetect              = 0
    PalmMinWidth            = 10
    PalmMinZ                = 200
    CoastingSpeed           = 20
    CoastingFriction        = 50
    PressureMotionMinZ      = 30
    PressureMotionMaxZ      = 160
    PressureMotionMinFactor = 1
    PressureMotionMaxFactor = 1
    ResolutionDetect        = 1
    GrabEventDevice         = 0
    TapAndDragGesture       = 1
    AreaLeftEdge            = 0
    AreaRightEdge           = 0
    AreaTopEdge             = 0
    AreaBottomEdge          = 0
    HorizHysteresis         = 6
    VertHysteresis          = 6
    ClickPad                = 0

A: Your problem is here:
TapButton1              = 0
TapButton2              = 0
TapButton3              = 0

For some reason all the tapping options (single-finger, double-finger and triple-finger tapping) are disabled.
Edit /usr/share/X11/xorg.conf.d/50-synaptics.conf:
sudo nano /usr/share/X11/xorg.conf.d/50-synaptics.conf

Find this section:
Section "InputClass"
        Identifier "touchpad catchall"
        Driver "synaptics"
        MatchIsTouchpad "on"
# This option is recommend on all Linux systems using evdev, but cannot be
# enabled by default. See the following link for details:
# http://who-t.blogspot.com/2010/11/how-to-ignore-configuration-errors.html
      MatchDevicePath "/dev/input/event*"
EndSection

And add the following lines before the EndSection line:
Option "TapButton1" "1"
Option "TapButton2" "3"
Option "TapButton3" "2"

This will bound the one-finger tap to the left click, the double-finger tap to the right click and the triple-finger tap to the middle click;
Hit CTRL+O, Y, CTRL+X and reboot.


text:
Q: How to download images from postgres bytea column using R or python? Basically, I have local postgres database with table called "person" and it has column called "image", which is a bytea column holding a .png image. I don't use postgresql and I want to download the images to be names from another column with the suffix ".png"
All the answers I have found are postgres side answers and I really can't go with them. Is there is an authentic package in R or python that can download the images?

A: Here's a solution using R:
# Packages we need
require("RPostgreSQL")
require('jsonlite')

# Create connection to database
pgConn <- dbConnect(PostgreSQL(), dbname="your_db", host='127.0.0.1')

# Query string - edit this to suit your needs
# Important thing here is that we're getting Postgres to base64 encode
#   the image data (converting it from binary to text)
thisQ = "SELECT encode(imageColumn, 'base64') AS image from test_table WHERE name='image';"

# Execute the SELECT query and fetch the results
resultSet = dbSendQuery(pgConn, thisQ)
resultData <- fetch(resultSet, n=-1)
dbClearResult(resultSet)

# Get the image data as text
imageData <- resultData$image

# Decode from base64 back to binary
imageDataDecoded <- jsonlite::base64_dec(imageData)

# Create a file connection and write the binary data to disk using mode "wb".
write.filename = file("/temp/file.png", "wb")
writeBin(imageDataDecoded, write.filename)
close(write.filename)


text:
Q: Не получается добавить еще один класс для button в React Столкнулся с интересной проблемой. В своём приложении react я задал общий стиль для всех button с классом quizBtn. Теперь в одном компоненте нижнего уровня мне надо добавить одной из кнопок ещё один класс, чтобы покрасить её в другой цвет. Но самые очевидные варианты не работают.
<button className='quizBtn quizBtn__red'>В меню</button>

Кнопка теряет оба стиля
const styleMenu = ['quizBtn', style.quizBtn__red];
<button className={styleMenu.join(' ')}>В меню</button>

Основной стиль удаляется, второй стиль применяется.
Вот кстати так выглядит основной стиль, находится он в главном компоненте
button[class^=quizBtn] {
    outline: none;
    background: #ffb700;
    padding: 5px 30px;
    margin-top: 25px;
    border: 2px solid #ff8001;
    border-radius: 20px;
    cursor: pointer;
    color: #fff;
    font-weight: bold;
    box-shadow: 2px 2px 3px 0 rgba(255, 116, 2, 0.3);
    transition: .2s;
  }

  button[class^=quizBtn]:hover {
    background: #ff8001;
  }

A: Решил проблему с помощью hoc-компонента QuizButton.
import React from 'react';
import style from './QuizButton.module.scss';

function QuizButton(props) {
    return (
        <div className={style.QuizButton}>
            {props.children}
        </div>
    )
}

export default QuizButton;

В style задал стиль для кнопки. Обернул компонентом каждую кнопку в приложении:
<QuizButton>
    <button
        className={style.quizBtn__red}
    >В меню
    </button>
</QuizButton>


text:
Q: Pandas df.to_html with CSS styling Can anyone please explain why the below outputs no data? The Results.html is not produced.
df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
df.dropna(how="all", inplace=True)
data = df.sort(ascending=True)
HTML('''''')
HTML(data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df'))

Update
I was able to work out the issue myself, just encase anyone else comes across this below is the working example.
df = pd.read_csv(os.path.join(root,filename), skip_blank_lines=True)
df.dropna(how="all", inplace=True)
data = df.sort(ascending=True)
style = ''''''
style + data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df')

A: The to_html method saves the html file (when passed a buf parameter), that is, it saves the xml to Results.html... and the method returns None.
data.to_html(os.path.join(root, "Results.html"), index=False, na_rep="NA", classes='white_space_df')

If you don't pass a buf argument (the first one) it returns a string:
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])

In [12]: df.to_html()
Out[12]: '
\n
\n
\n      	\n      A	\n      B	\n
\n
\n
\n
\n      0	\n      1	\n      2	\n
\n
\n      1	\n      3	\n      4	\n
\n
\n
'

So you want to pass this string to HTML (rather than None):
HTML(data.to_html(index=False, na_rep="NA", classes='white_space_df'))


text:
Q: No open subset $U \subset \mathbb{C}$ so that $f|_U :U \rightarrow \mathbb{C} \smallsetminus {0}$ where $f=e^z$ is a bijection I nood to show that there is no open subset $U \subset \mathbb{C}$ so that $f|_U :U \rightarrow \mathbb{C} \smallsetminus {0}$ where $f=e^z$ is a bijection.
I started by claiming that for $f$ to be $1-1$, $arg(z)$ must be in the set $[\alpha +2 \pi k,\alpha +4 \pi k)$ for all $z \in U$ for a particular $\alpha \in [0,2 \pi)$ and $k \in \mathbb{Z}$. Hence $U$ is contained by a "vertical strip" on the plane, I get nowhere from here.


text:
Q: Customize AWS arn address? I need to use the arn many times, currently it looks like this:
arn:aws:iam::000000000000:user/FirstName.LastName

Is it possible to customize it for something like this ?
arn:aws:iam::CompanyName:user/FirstName.LastName

So I could use it on others arn as well, such as this:
arn:aws:iam::000000000000:role/my.role

A: You should create account alias.
As your 000000000000 is an account Id.
You can do it using:
aws iam create-account-alias --account-alias examplecorp

Here's the link


text:
Q: Regular expression for a string with a max length that contains a required part? I'm not exactly a regex guru, so I have some difficulty finding a regular expression for the following case.
I'd like to match a string of the form <prefix>$rolename$<suffix> (e.g. abc$rolename$def) that has a maximum length of 20. Both <prefix> and <suffix> can be empty and may contain any character. The $rolename$ part is required.
Shouldn't be difficult but I just can't figure out how to do this. Can anyone help me?

A: Since you have to use a regex, as you've explained, here's an option:
^(?!.{21,})(.*?)\$rolename\$(.*?)$

This is similar to Joachim's answer, but with a negative lookahead at the beginning. That is: before the regex is matched, we check the string does not have 21 or more characters.

A: The regular expression I'd use would be /^([^\$]*)\$rolename\$([^\$]*)$/, validating the total length of the string externally.

A: why regex? think simple. depending on your language, check for length using your language's string length methods eg using Python
if len(mystring) <= 20:
     if "$rolename" in mystring:
         print "ok"

your language may have similar methods like index() to find where a substring is in a string.


text:
Q: UseEffect does not update the component When I delete the recipe from the favorites by clicking on the button, it is removed from the favorites array but the card remains displayed on the screen.
I would like the card to be deleted but it does not disappear.
The favorite recipe card disappears only I reload the page.
I tried using useEffect but it doesn't work.
How can I reload the component in order to update the favorites list shown?
import React, { useContext, useEffect, useState } from 'react';
import Navbar from '../../components/Navbar/Navbar';
import FavoritesContext from '../../FavoritesContext';
import { Link } from 'react-router-dom';
import { BsFillTrashFill } from 'react-icons/bs';
import './Favorites.css';
import { getRecipeInfo } from '../../api';

function Favorites() {

    const { favorite, setFavorite } = useContext(FavoritesContext);
    const [recipes, setRecipes] = useState([]);
    const [newrecipes, setNewrecipes] = useState([]);

    //recipes request
    const getRecipe = () => {
        for (let i = 0; i < favorite.length; i++) {
            const element = favorite[i];
            getRecipeInfo(element)
            .then((response) => {
                let title = response.data.title;
                let image = response.data.image;
                let id = response.data.id;
                setRecipes(prev => [...prev, {id: id, title: title, image: image}])
            })
            .catch((error) => console.log(error))
        }
    }

    useEffect(() => {
        getRecipe()
    },[favorite])

    //remove duplicate ids from previous function
    useEffect(() => {
        let uniqueID = [];
        const getUnique = () => {
            uniqueID = recipes
                .map(e => e['id'])
                .map((e, i, final) => final.indexOf(e) === i && i)
            .filter(e => recipes[e]).map(e => recipes[e])
            return uniqueID;
        }
        console.log(getUnique())
        setNewrecipes(uniqueID);
    },[recipes])

    const saveToLocalStorage = (items) => {
        localStorage.setItem('favorites-recipes', JSON.stringify(items))
    }

    const removeFavorite = (id) => {
        let index = favorite.indexOf(id);
        let newFavoriteList = [...favorite.slice(0, index), ...favorite.slice(index + 1)];
        setFavorite(newFavoriteList);
        saveToLocalStorage(newFavoriteList);
        //window.location.reload(false);
    }

    return (

            <Navbar />

Favorites

                {newrecipes.map((recipe) => {
                return (

                                <Link to={'/recipe/' + recipe.id} style={{ textDecoration: 'none' }}>

{recipe.title}

                                </Link>

 removeFavorite(recipe.id)}><BsFillTrashFill size={"70px"}/>

                )
                })}

    )
}

export default Favorites


text:
Q: SEO - Mutli international domains vs one site? MAIN (US/UK)
http://www.gc.com/
http://www.gc.com/categorys
http://www.gc.com/categorys/products
http://www.gc.com/categorys/products/item-1

PL (Polish)
http://www.gc.pl/
http://www.gc.pl/categorys
http://www.gc.pl/categorys/products
http://www.gc.pl/categorys/products/item-1

DE (Deutsch)
http://www.gc.de/
http://www.gc.de/categorys
http://www.gc.de/categorys/products
http://www.gc.de/categorys/products/item-1

We have domains for over 20 countries so you get the point.
What is the best solution for SEO?

*

*Keep the multi domain option, and just add Canonical meta to the .com for international URL

*Keep the store to .com and all the URLS to .com - when the customer lands on any page with a new session offer them currency and language options and then update the system to reflect - but still use the same URLs

Our Ecommerce platform allows us to have multiple stores. Alternative we can have one store, with multiple languages and multiple currencies. The prime question is about the SEO and flagging of having all these domains listed.

A: You don't want to use canonical across languages.  Rather you should use link tags with hreflang attributes.
Because you have an ecommerce store that will need to deal with prices, currencies, and shipping, you should do geographic targeting.   You should have one site per country and make sure that Google gets the geographic targeting of each correct using Webmaster Tools.
I'm not sure what the difference between multiple stores and a single store with multiple languages is.  For SEO, there are several ways of setting it up, but you need to have separate URLs for each country.  They can either be different domains, different sub-domains, or different folders.  Here is a more in depth answer about setting up international URLs for SEO.


text:
Q: How to create overloaded method that is Implemented recursively I am creating a mortrage calculator in Java using recursion and the first thing I did is to create a method that takes a payment amount and returns the number of months to repay the loan. If the payment amount is too low this method throws a PaymentException with a descriptive message that indicates the minimum acceptable payment. The minimum acceptable payment is the lowest integral dollar amount greater than the interest due the first month.
Now what I need to do is to create a private overloaded method that implements the calculation of the number of months recursively. Each invocation of this method is supposed to have its own value for the remaining principal until everything is paid off. (the interest accrues every month for the remaining principal based on the monthly interest rate). And he method should return the number of months left to pay the remaining principle....I'm confused on how to do that? Please I need help
I don't know where to start from to create the second overladed method that is implemented recursively.
Here is the first method I created that needs to be implemented recursively
public int calculateMonthsToRepay(int paymentAmount, int minimum, int numOfMonthsToRepay) throws PaymentException {
        minimum = (loanAmount * (interestRate / MONTHS_IN_A_YEAR));
        if (paymentAmount < minimum) {
            throw new PaymentException("Payment " + paymentAmount + " is too low");
        }
        return numOfMonthsToRepay = (loanAmount / paymentAmount);
    }


text:
Q: Create Dynamic Web Service Client in Eclipse using "Web Service Client Wizard" Created a Web Service Client in Eclipse using "Web Service Client Wizard" listed in following link which worked great with a single proxy / URI.
http://www.eclipse.org/webtools/community/education/web/t320/Generating_a_client_from_WSDL.pdf
However, how can we adjust the system to create a dynamic proxy (Same application or web service client functions but in different servers). Is there any wizard to do it? If not, how can it be done?
Thanks


text:
Q: How do I automatically scroll a page up if .slideDown goes of the bottom of the browser? I have a table that reveals additional information for each row via a jQuery slideDown when the row is mouseover'd. When the mouse is removed the information is removed with a slideUp.
This works nicely but when I mouseover the last item on the page it slides down below the bottom of the browser window. If the user scrolls down with a mousewheel or similar they can see the information but if they move the mouse pointer to slide the scroll bar the information disappears.
Is there a simple way in jQuery of ensuring that the page is scrolled down to show the information at the same time as the slideDown is executed or am I going to have to handroll a solution to this?

A: You could try to get how deep is the last row going by calculating his vertical position (top) and his height. If that value would pass the current scroll, then you scroll to that value.
//Not tested
var verticalLimit = $("#lastRow").offset().top + $("#lastRow").height() ;
var currentVerticalScroll = $(window).scrollTop();
if (verticalLimit > currentVerticalScroll){
    $("body").animate({ scrollTop: verticalLimit }, 500);
}


text:
Q: Delphi: "WriteProcessMemory" is regarded a virus, how to dodge it? I want to run an exe program from memory. I already found good solutions, but... my virus-chaser wont allow to compile my code. I already tracked down that if I remove the "WriteProcessMemory" callings, the code at least compiles (not running of course...).
It is reported as "modified Win32/Injector.CKX trojan".
But Im surely not writing a virus. The "WriteProcessMemory" function is the problem.
How to run away from the virus-chaser?

A: WriteProcessMemory() is a function often used to inject code into another process - and it also requires enough privileges to work - if you call CreateProcess() you have PROCESS_ALL_PRIVILEGES rights, but if you call OpenProcess() the privileges assigned depends on the process security token, and WriteProcessMemory() may fail.
If you're compiling a program for yourself you may put it into your AV exceptions, but if you're going to deploy it, most AV will probably see the call to WriteProcessMemory() and block it, very few legitimate applications should need to call it.

A: You may actually have a virus, have you checked for: http://nakedsecurity.sophos.com/2009/08/19/w32induca-spread-delphi-software-houses/
Win32/Injector.CKX trojan, Yep it is the famous Delphi virus.
You need to get a virus cleaner for that one: http://www.sophos.com/en-us/threat-center/threat-analyses/viruses-and-spyware/Mal~Induc-A.aspx
Please apply it and clean up your system.


text:
Q: how can i pass query string parameter in payload with jason data using javascript ajax post call Every time a user searches, I have to send a request. So I'm utilizing kendo multi-select and implementing it using an ajax post call.
var payload ={
  "vFilters": [
    {
      "field": "DistLocationIds",
      "values": [
        "2787"
      ]
    },
    {
      "field": "VdistLocationIds",
      "values": []
    },
    {
      "field": "createdByLocationLevelId",
      "values": []
    },
    {
      "field": "taskLevelId",
      "values": [
        "118"
      ]
    }
  ],
  "rangeFilters": [
    {
      "greaterThanOrEqual": "2022-06-11",
      "field": "startDate"
    },
    {
      "lessThanOrEqual": "2022-07-11",
      "field": "endDate"
    }
  ],
  "sorts": [],
  "limit": 50,
  "q": "s"
};

var new1 = new kendo.data.DataSource({
  transport: {
                    read: function(options) {
                        $.ajax({
                             delay: 350, // wait 250 milliseconds before triggering the request
                             url: "https://tasklist",
                             type: "post",
                             data: JSON.stringify(payload),
                             dataType: 'json',
                             contentType: "application/json"
                        });
                    },

                    contentType: "application/json",
                    beforeSend: function(req) {
           req.setRequestHeader('Authorization', "Bearer @Session.AuthToken~");
       },
        processResults: function (data) {
                //console.log("results: "+data.results.length);
                var res = [];
                if(data && data.results){
                    for(var i  = 0 ; i < data.results.length; i++) {
                        res.push({id: data.results[i].objectId, text: data.results[i].title});
                    }
                }
                return {
                    results: res
                }
            },
            complete: function(){
            }
                }
});
$("#islTasks").kendoMultiSelect({
        placeholder: "Select Tasks...",
        filter: "contains",
        autoBind: false,
    dataValueField: "objectId",
    dataTextField : "title",
    dataSource : new1
});

I've tried several techniques, but none of them have worked. Anyone have any ideas on how to pass json data in an array plus a query string parameter in a payload request using a post ajax call?
Now I have to pass the query string parameter in the variable I made which is payload data. Could someone kindly help me with this?


text:
Q: Make a divs top and bottom border have a jagged edge What would be the best approach to make a border such as this on a div? It would only need to work in modern browsers and nothing below IE10. I have been looking into using border image but that seems to be a little off in how it would render the bottom border and in how it stretches across the width of the div. Using a repeated background image I dont think would work either since the height of the container can grow. Thanks for any help!

A: Check this jsfiddle which works in all browsers
EDIT
http://jsfiddle.net/yKPe9/3/
.header:after, .footer:after {
    content: " ";
    display:block;
    position: relative;
    top:0px;
    left:0px;
    width:100%;
    height:36px;
    background: linear-gradient(#2B3A48 0%, transparent 0%), linear-gradient(135deg, #272220 33.33%, transparent 33.33%) 0 0%, #272220 linear-gradient(45deg, #272220 33.33%, #2B3A48 33.33%) 0 0%;
    background: -webkit-linear-gradient(#2B3A48 0%, transparent 0%), -webkit-linear-gradient(135deg, #272220 33.33%, transparent 33.33%) 0 0%, #272220 -webkit-linear-gradient(45deg, #272220 33.33%, #2B3A48 33.33%) 0 0%;
    background: -o-linear-gradient(#2B3A48 0%, transparent 0%), -o-linear-gradient(135deg, #272220 33.33%, transparent 33.33%) 0 0%, #272220 -o-linear-gradient(45deg, #272220 33.33%, #2B3A48 33.33%) 0 0%;
    background: -moz-linear-gradient(#2B3A48 0%, transparent 0%), -moz-linear-gradient(135deg, #272220 33.33%, transparent 33.33%) 0 0%, #272220 -moz-linear-gradient(45deg, #272220 33.33%, #2B3A48 33.33%) 0 0%;
        background: -ms-linear-gradient(#2B3A48 0%, transparent 0%), -ms-linear-gradient(135deg, #272220 33.33%, transparent 33.33%) 0 0%, #272220 -ms-linear-gradient(45deg, #272220 33.33%, #2B3A48 33.33%) 0 0%;
    background-repeat: repeat-x;
    background-size: 0px 100%, 9px 27px, 9px 27px;
}

.main
{
    height:200px;
    padding: 36px 0;
    box-sizing:border-box;
   background-color:#2B3A48;
}
.flip-vertical {
    -moz-transform: scaleY(-1);
    -webkit-transform: scaleY(-1);
    -o-transform: scaleY(-1);
    transform: scaleY(-1);
    -ms-filter: flipv; /*IE*/
    filter: flipv; /*IE*/
}


text:
Q: Replace string with most frequent fuzzy match I have a dataframe of unstructured names, and I want to create a 'master' list of the cleaned name in one column with all the variants in another column. I am using the stringdist package. Below is a small example:
library(dplyr) # for pipes
library(tidyr) # for expand_grid()
library(stringdist)

words <- c("dog","dot","don","con","cry","croak","cat","dogg", "dogy", "dog", "cat", "dog")
# compare everything to everything
words_df <- expand_grid(raw = words, clean = words) %>%
    mutate(dist = stringdist(raw, clean, method = "jw") %>%
    # compute word frequency
    group_by(clean) %>%
    mutate(count = n()) %>%
filter(dist < 0.3)

This results in a df with the distance and word counts for all similar enough combinations:
|raw |clean |      dist| count|
|:---|:-----|---------:|-----:|
|dog |dog   | 0.0000000|    36|
|dog |dot   | 0.2222222|    12|
|dog |don   | 0.2222222|    12|
|dog |dogg  | 0.0833333|    12|
|dog |dogy  | 0.0833333|    12|
|dog |dog   | 0.0000000|    36|
|dog |dog   | 0.0000000|    36|
|dot |dog   | 0.2222222|    36|
|dot |dot   | 0.0000000|    12|
|dot |don   | 0.2222222|    12|

You can see that in the clean column I have two entries for "dog" and "dogg", which I would want to collapse into one entry (dog) because the string "dog" appears more often.
Here is what I've tried so far:
dict <- words_df %>%
    mutate(clean_new = ifelse(dist < 0.085, words_df[which.max(words_df$count)][[1]][1], clean))

Which results in:
|raw |clean |      dist| count|clean_new |
|:---|:-----|---------:|-----:|:---------|
|dog |dog   | 0.0000000|    36|NA        |
|dog |dot   | 0.2222222|    12|dot       |
|dog |don   | 0.2222222|    12|don       |
|dog |con   | 0.4444444|    12|con       |
|dog |cry   | 1.0000000|    12|cry       |
|dog |croak | 0.4888889|    12|croak     |
|dog |cat   | 1.0000000|    24|cat       |
|dog |dogg  | 0.0833333|    12|NA        |
|dog |dogy  | 0.0833333|    12|NA        |
|dog |dog   | 0.0000000|    36|NA        |

Essentially what I want to create is a dictionary of all variants of the word, based on frequency of the closest word match.
Thanks all!

A: This dplyr pipe statement will return a data frame with 9 rows, one for each of the unique elements in your original words vector. First we group_by the raw column which creates a group for each unique word, then filter by your distance threshold, then find the corresponding word in clean with the highest frequency in the original dataset. In your example all words match themselves except for the two variants of "dog."
Code
words_df %>%
  group_by(raw) %>%
  filter(dist < 0.085) %>%
  summarize(clean = clean[which.max(count)])

Output
# A tibble: 9 x 2
  raw   clean
  <chr> <chr>
1 cat   cat
2 con   con
3 croak croak
4 cry   cry
5 dog   dog
6 dogg  dog
7 dogy  dog
8 don   don
9 dot   dot


text:
Q: Woocommerce - wc_cart_totals_shipping_method_label() breaking out option tag I'm trying to change the default cart-shipping.php template to use a dropdown menu rather than radio buttons.
I have successfully managed to do this on the cart page by changing the printf function to an option and replacing checked() with selected().
<select id="shipping_method" class="woocommerce-shipping-methods">
                <?php foreach ( $available_methods as $method ) : ?>
                        <?php
                        printf( '<option name="shipping_method[%1$d]" data-index="%1$d" id="shipping_method_%1$d_%2$s" value="%3$s" class="shipping_method" %4$s />%5$s</option>', $index, esc_attr( sanitize_title( $method->id ) ), esc_attr( $method->id ), selected( $method->id, $chosen_method, false ), wc_cart_totals_shipping_method_label( $method ) ); // WPCS: XSS ok.
                        do_action( 'woocommerce_after_shipping_rate', $method, $index );
                        ?>
                <?php endforeach; ?>
            </select>

However, when viewing it on the checkout page in the 'Order Review' section, it's displaying the dropdown menu but the label is breaking out of the option tag.
 <select id="shipping_method" class="woocommerce-shipping-methods">
    <option name="shipping_method[0]" data-index="0" id="shipping_method_0_local_pickup3" value="local_pickup:3" class="shipping_method" selected="selected">
</option>Collection
</select>

The problem seems to exist in the DOM and not the source so I'm not sure if there's any javascript working behind the scenes which is causing this to happen.
Does anyone know why this is happening?

A: You seem to have an unexpected "/" character here .../>%5$s</option> so the "option" tag is:
<option ... />Collection</option>
instad of
<option ... >Collection</option>
I am not sure if this causes a problem but i think it is worth checking :).


text:
Q: Bash's $_ variable not expanding The $_ variable, which should expand with the arguments of the last executed command in Bash, contains _lp_runtime_before. No matter how many times I run a command, that would be the content it has. Why?

A: Actually, $_ expand to the last argument of the last command line, according to the man page of bash:

[$_] expands to the last argument to the previous command, after expansion.

If you want the whole arguments, use !:*:
$ ls -a -l -h test
[blah blah]
$ last_command="!:*" > /dev/null

$ echo $last_command
-a -l -h test

I added a redirection of stdout to null device to prevent bash to print the expansion.


text:
Q: How to access and retrieve real-time data from Avaya database? I seek to retrieve Agents and Jobs real-time information and send it via web.
My company is using Avaya Proactive Contact 5.1 standalone. The objective is a way to do this without purchasing any extra service or component from Avaya.. i.e. free.
I read something about Clint or RT_Socket but it wasn't very clear or precise. Could you help me a bit with this??
BIG THANKS in advance.
Greetings.

A: I would get a free account on http://www.devconnectprogram.com/ and search through the SDK and API docs to see if you can get what you need.
There are so many API's and SDK's on the POM solution...

good luck!


text:
Q: Disable links in UIWebView? I am loading some content from the web into a UIWebView, but I'd like all links to be disabled in the UIWebView. Is this possible? I could parse the text, but I'm looking for something easier.

A: You can give the UIWebView a delegate and implement the -webView:shouldStartLoadWithRequest:navigationType: delegate method to return NO; (except on the initial load).
That will prevent the user from viewing anything but that single page.
To provide an example requested in the comments...  Start with allowLoad=YES and then:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    return allowLoad;
}

- (void)webViewDidFinishLoad:(UIWebView*)webView {
    allowLoad = NO;
}

A: You can disable data detect from your webview.
[webView setDataDetectorTypes:UIDataDetectorTypeNone];

A: Tested in Swift 4.0: This approach doesn't involve having an extra variable to test if this is the initial load or not. Simply check the type of request (in this case, LinkClicked) and return false in that case. Otherwise simply return true!
(Of course make sure you set the webView.delegate)
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == .linkClicked {
        return false
    }
    return true
}

A: For swift 3:
Try removing the types you don't want to show as link from webView.dataDetectorTypes
webView.dataDetectorTypes.remove(UIDataDetectorTypes.all)

A: Another answer for Swift 3.0 :
Just give zero for don't detect any type link of yourWebView initial code
yourWebView.dataDetectorTypes =  UIDataDetectorTypes(rawValue: 0)

A: Simple answer that works in Swift 2.0:
yourWebView.dataDetectorTypes = UIDataDetectorTypes.None

Just implement it in the view controller where you are defining and using your web view and it will work flawlessly.

A: I had a similar need and for some cases just using the webViewDidFinishLoad was not enough, so I used the webViewDidStartLoad to cover all cases:
func webViewDidStartLoad(webView: UIWebView) {
    startedLoading = true
}

func webViewDidFinishLoad(webView: UIWebView) {
    alreadyOpen = true
}

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if startedLoading && alreadyOpen {
        // do something
        return false
    }else if startedLoading && !alreadyOpen{
        return false
    }else if !startedLoading {
        return true
    }
    return true
}

In some cases when the html was loaded but some resources, like images and some heavy assets inside the DOM were not the didFinishLoad method was not fired and the user could navigate in this "short" interval.


text:
Q: NSFetchRequest could not locate an NSEntityDescription for entity name I've tried the proposed solutions for similar questions on SO but with no luck.  The fetch request can't locate the entity name 'GarmentType'.
Here is my data model:

The error is thrown at the executeFetchRequest in this helper category:
//
//  GarmentType+Create.m
//  Dressy
//
//  Created by Michael Mangold on 9/4/13.
//  Copyright (c) 2013 Michael Mangold. All rights reserved.
//

#import "GarmentType+Create.h"

@implementation GarmentType (Create)

// Creates or fetches a Core Data GarmentType entity.
+ (GarmentType *)garmentTypeWithName:(NSString *)name inManagedObjectContext:(NSManagedObjectContext *)context
{
    NSLog(@"name:%@ context:%@",name,context);
    GarmentType *garmentType = nil;

    // Build fetch request.
    NSFetchRequest *request          = [NSFetchRequest fetchRequestWithEntityName:@"GarmentType"];
    request.sortDescriptors          = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];
    request.predicate                = [NSPredicate predicateWithFormat:@"name = %@",name];

    // Execute fetch requesst.
    NSError *error  = nil;
    NSArray *matches = [context executeFetchRequest:request error:&error]; // This is where it dies.

    if (!matches || [matches count] > 1) {
        NSLog(@"Error creating GarmentType.");
    } else if ([matches count] == 0) {
        garmentType          = [NSEntityDescription insertNewObjectForEntityForName:@"GarmentType" inManagedObjectContext:context];
        garmentType.name     = name;
    } else {
        garmentType = [matches lastObject];
    }

    return garmentType;
}

@end

The name logs the correct name and the context is non nil.
The helper is called from a UITableViewController IBAction when the 'done' button is pressed:
- (IBAction)handleDoneButton:(UIBarButtonItem *)sender
{
    // Add garment type to core data.
    [DressyHelper openDocumentUsingBlock:^(UIManagedDocument *document){
        GarmentType *newGarment = [GarmentType garmentTypeWithName:self.garmentTypeNameTextField.text inManagedObjectContext:document.managedObjectContext];
        NSLog(@"newGarment.name:%@",newGarment.name);
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}

newGarment.name logs fine.
Here is the .h for GarmentType:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Garment;

@interface GarmentType : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *garments;
@end

@interface GarmentType (CoreDataGeneratedAccessors)

- (void)addGarmentsObject:(Garment *)value;
- (void)removeGarmentsObject:(Garment *)value;
- (void)addGarments:(NSSet *)values;
- (void)removeGarments:(NSSet *)values;

@end

Apologies for the code dump but I've been struggling with this for a while.  Changing the entity name results in the same error, just with the new name as the entity not found.
Inspector for GarmentType:

And the exception:
2013-12-10 13:51:50.320 Dressy[4336:70b] name:asdf context:<NSManagedObjectContext: 0x8ad86f0>
2013-12-10 13:51:50.323 Dressy[4336:70b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSFetchRequest could not locate an NSEntityDescription for entity name 'GarmentType''
*** First throw call stack:
(
    0   CoreFoundation                      0x017465e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x014c98b6 objc_exception_throw + 44
    2   CoreData                            0x019b4b6e -[NSFetchRequest(_NSInternalMethods) _resolveEntityWithContext:] + 510
    3   CoreData                            0x019b34d6 -[NSManagedObjectContext executeFetchRequest:error:] + 70
    4   Dressy                              0x000051de +[GarmentType(Create) garmentTypeWithName:inManagedObjectContext:] + 510
    5   Dressy                              0x00002170 __54-[GarmentTypeAddTableViewController handleDoneButton:]_block_invoke + 208
    6   Dressy                              0x00006d51 __39+[DressyHelper openDocumentUsingBlock:]_block_invoke21 + 97
    7   UIKit                               0x00781f7b __59-[UIDocument saveToURL:forSaveOperation:completionHandler:]_block_invoke570 + 54
    8   libdispatch.dylib                   0x01e43440 _dispatch_barrier_sync_f_slow_invoke + 71
    9   libdispatch.dylib                   0x01e544b0 _dispatch_client_callout + 14
    10  libdispatch.dylib                   0x01e4275e _dispatch_main_queue_callback_4CF + 340
    11  CoreFoundation                      0x017aba5e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
    12  CoreFoundation                      0x016ec6bb __CFRunLoopRun + 1963
    13  CoreFoundation                      0x016ebac3 CFRunLoopRunSpecific + 467
    14  CoreFoundation                      0x016eb8db CFRunLoopRunInMode + 123
    15  GraphicsServices                    0x03a4d9e2 GSEventRunModal + 192
    16  GraphicsServices                    0x03a4d809 GSEventRun + 104
    17  UIKit                               0x00237d3b UIApplicationMain + 1225
    18  Dressy                              0x0000585d main + 141
    19  libdyld.dylib                       0x020e670d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

TIA

A: The Entity diagram with Entity names is only half of the puzzle.  For each entity, what have you defined the class names as?  That is what fetchRequestWithEntityName: will go against.
EDIT:
Since the class name is resolved, what is the exception you are getting?  After you continue, does CoreData explain what the problem is that it had?  Does the application actually crash (I ask that because if you have a breakpoint set for exceptions, Core Data will often throw internal exceptions that don't matter or cause the application to crash)?
EDIT2:
The crash doesn't say much beyond us knowing you have a valid context.  The next step would be, to list all of the entities at a breakpoint set just before the fetch request, using code like:
NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel];
NSDictionary *entities = [managedObjectModel entitiesByName];
NSArray *entityNames = [entities allKeys];
NSLog(@"All loaded entities are: %@", entityNames);

A: I finally found the problem.  The .xcdatamodel wasn't included in the target membership.  Selecting the xcdatamodel in the navigator pane on the left in Xcode, then selecting the first tab (File inspector) in the Utilities pane on the right, then selecting the data model in the Target Membership section fixes the problem.  Thank you so much to everyone who responded.

A: I got this after creating a new model version with a new entity, but forgetting to update data file URL:
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Data2.0" <==== Here
                                          withExtension:@"mom"
                                           subdirectory:@"Data.momd"];

_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];