Reportlab - Unicode characters appear as boxes in unicode-supported font

Question: Trying to use reportlab through python 3 to write a document that includes macrons (ā ē ī ō ū), but the macrons are showing up as boxes (■). The document is written in Arial font -- but if I open up the file in a word processor to check the font, the boxes are in 'Segoe UI Symbol' font.
For importing in Arial as a font that supports a broad range of unicode characters (which seems to have worked):
import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))

I also import a dictionary through json, looking something like this when I open the json file in notepad:
{"example1":"b\u0101s"}

The program reads and writes this dictionary:
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
doc = SimpleDocTemplate("hello.pdf")
Story = [Spacer(1,2*inch)]
style = styles["Normal"]
with open('CompDict.json','r') as f:
        m_dic=json.load(f)
for key,value in m_dic:
     p=Paragraph(key+":"+value,style)
     Story.append(p)
doc.build(Story)

The outcome should be a pdf with example1:bās but instead comes out as example1:b■s
Comment: Just an observation: The JSON snippet you show isn't valid JSON (which requires double quotes). But that's probably not related to your problem.
Comment: Python 2.x or 3?
Comment: I'm using python 3.6
Answer: #Here I am writing chunks of code, hope you will understand

from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER,TA_JUSTIFY
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.fonts import addMapping

pdfmetrics.registerFont(TTFont('devaNagri', 'NotoSerifDevanagari.ttf')) # devaNagri is a folder located in **/usr/share/fonts/truetype** and 'NotoSerifDevanagari.ttf' file you just download it from https://www.google.com/get/noto/#sans-deva and move to devaNagri folder.

addMapping('devaNagri', 0, 0, 'NotoSerifDevanagari') #devnagri is a folder name and NotoSerifDevanagari is file name

style = getSampleStyleSheet()
style.add(ParagraphStyle(name="ParagraphTitle", alignment=TA_JUSTIFY, fontName="devaNagri")) # after mapping fontName define your folder name.
paragraph = Paragraph('your unicode string', style["ParagraphTitle"])

Answer: Find your character under this link:
UTF-8 encoding table and Unicode characters

Go to (utf-in literal) row of the table.
You will see some: \xc3\x85 like characters. Choose your character...
Then for text output, in your code type something like :
Canvas.drawString(x,y,'\xc3\x85') =>  and it will print Å ...

So you have to change your dictionary items to UTF-8 LITERALS because it will not understand "b\u0101s"Unicode, which there are many ways to do so ...
best regards


Checksum algorithm for SQL query?

Question: I need to generate a checksum based on a SQL query and the string values of any parameters used in that query. The checksum is used in a caching scenario. If the checksum exists in cache, so does the result and then I don't need to hit the DB.
Req 1:
It's important that two different queries doesn't generate the same hash. Because that could lead to an unexpected result being returned.
Req 2:
It can't be tremendously slow, but again it's in memory and shouldn't have to much content.
Given the context, what algorithm is best fit? CRC32, MD5, SHA1 or anything else?
//Daniel
Comment: The choice of hashfunction is relatively unimportant, since you can keep the (canonical) querystrings and use them for a final compare to resolve collisions. If you don't intend to keep more than 64K items in the cache, any reasonable 32 bits hashfunction would suffice.
Comment: "It's important that two different queries doesn't generate the same hash. Because that could lead to an unexpected result being returned."  Then the only acceptable hash is the entire query itself or some lossless compression of the query.  Anything shorter cannot be assured to have no collisions.  If you use hashing you have to be able to properly deal with collisions, however rare they may be.
Comment: this question is basically an popularity poll and therefore not fit for SO QA format. Try to rephrase it in a way that makes a simple, to the point answer possible. Also, in my opinion, its always better to ask for what you want done, not for the tools you think are necessary for the task. In this case, you should ask for query result cashing on the application side (im guessing you want to limit network traffic). Otherwise, you could be asking for a knife to screw in some screws, while someone could have offered you an electric screwdriver.
Comment: "it's kind of important that two different queries doesn't generate the same hash" - that's unfortunate.
Comment: 1) parse the query 2) transform the parse tree into a canonical form 3) serialise the tree into a (canonical) string 4) use the resulting string as a key, or use it as the input for a 5) hashfunction
Comment: @wildplasser I do that, the question is which hash algorithm to use of the resulting string?
Answer: Put the whole query string concatenated with the arguments in a regular HashTable / Dictionary / HashMap or whatever it is called in your language. Put the SQL query as the key and the result as the value.
Your HashTable will use an appropriate hashing function for your strings and resolve any hash collisions.
Comment: Not sure about that. Sounds appealing but as long as I can't read up in the docs about what kind of uniqueness they guarantee, it suddenly isn't that attractive. It's like the GetHashCode implementation. It's not guaranteed to be unique....
Comment: @Daniel, yes, there is no uniqueness in the GetHashCode, but has not to be. Most HashTables store duplicate hashes in a linked list or in the next available slot. To be sure you don't get the wrong item back the whole key is compared when a hash of the key is found.
Comment: @Daniel, what language do you use?

Checksum algorithm for SQL query?


Why does "git fetch" fail on HTTPS URLs with "Function is not available" on HP-UX?

Question: When I run git fetch I get the following:
$ git fetch
Password for 'xxx':
error: cannot create thread: Function is not available
fatal: cannot start thread to parse advertised refs
$

Answer: The issue is that this particular distribution of git/curl is lacking pthread. One way to fix it is to use LD_PRELOAD:
$ LD_PRELOAD=/usr/lib/hpux32/libpthread.so git fetch
Password for 'xxx':
$

Answer: For me, finally this problem was caused by Cannot allocate memory, low memory problem.
So Pls check it. Hope it helps.


Como manter a assinatura do email remetente ao usar a função Mail::send() no laravel?

Question: Eu consigo enviar o email corretamente mas, o email vai sem assinatura do email remetente, e não estou encontrando como resolver.
$emails = ['email@example.com', 'firstname.lastname@example.com'];
$copias = ['firstname.lastname@example.com', 'firstname.lastname@example.com'];

Mail::send('dashboard.teste', ['curso' => 'Eloquent'], function($m) use ($emails,  $assunto, $copias)
{
        $m->to($emails)->subject($assunto)->from("firstname.lastname@example.com", "Remetente")->cc($copias, "email cópia");
});

Código da dashboard.teste
teste {{$curso}}

Comment: não entendi bem o que quis dizer com "manter assinatura do email remetente", pode me explicar?
Comment: Meu email tem uma assinatura com meu nome, telefone e email por exemplo, o email enviado via aplicação utilizando esta função vai sem a assinatura. Deu pra entender?
Comment: @Lorena por favor atualiza a pergunta e colocar a blade `dasborad.teste`
Comment: @Bulfaitelo atualizada.
Answer: Ao que entendi você esta esperando que o Mailer identifique a assinatura configurada no seu servidor e inclua também em cada envio pelo fato de você estar usando o mesmo SMTP/POP certo?
O Mailer não identifica a assinatura que você configurou no servidor automaticamente (não sei se isso é possivel), então você precisa incluir a informação no template explicitamente, veja:
Template email:
Curso: {{ $curso }}

{{ $nomeAssinatura }} - Setor
Nome da Empresa
Endereço
Phone: {{ $telefone }}

Controller:
$emails = ['email@example.com', 'email@example.com'];
$copias = ['email@example.com', 'email@example.com'];
$emailInfo = [
    'curso' => 'Eloquente' ,
    'nomeAssinatura' => 'Lorena',
    'telefone' => $telefone
];

Mail::send('dashboard.teste', $emailInfo, function($m) use ($emails,  $assunto, $copias)
{
    $m->to($emails)->subject($assunto)->from("firstname.lastname@example.com", "Remetente")->cc($copias, "email cópia");
});

Comment: Entendi, muito obrigada, vou tentar essa solução.
Comment: Deu certo, muito obrigada pela ajuda!


RAID 1 fault " Status Ready for Rebuild : Rebuild Percentage Complete 0%"

Question: Our RAID 1 system partition failed on our Windows 2008 SBS (physical environment).  We still have disc 1 running but the 2nd disc in the raid is a failure.  To add to the complication, disc 1 has bad sectors but in a partition that is not required.  HP have sent out a replacement for disc 2 but the RAID rebuild has failed due to bad sectors on disc 1.
We have backups from last night (backup exec) and a Windows backup from a week ago.  We are at risk as we are running our Windows 2008 sbs on 1 hard drive with a bad sector.  If anyone has any solutions, please help?
We have a spare in our RAID 5 (same server).  Could I make the spare a standalone HD (not RAID), shut the server down and use Acronis (or similar imaging product) to image the good partitions on disc 1 to the standalone HD (the old spare from RAID 5).  We have time over the weekend when people are not using the system.
Thanks
Answer: "Ready for Rebuild" is one of the worst errors you can receive on an HP ProLiant system. This indicates that the drive can't finish its rebuild because the disk you replaced is having trouble reading from its partner drive(s). Essentially this means that you have a failed disk and a failing disk.
See the following:
HP Proliant ML350 G5 SAS HDD
Force LUN in a HP Smart Array to rebuild
You can try a reboot (or power cycle... leave the machine off for a few minutes). Maybe that will jumpstart the process (it's worked once or twice for me in the past). If you have HP support, you can also pull an ACU diagnostic to see the specifics about the stalled rebuild.
As for moving data around, as long as you have good backups, anything is possible. But you know the details more than we do... Can you provide the disk sizes, array configuration, server model, controller model and firmware information? All of these matter, since they determine the options available to you. The output of the hpacucli ctrl all show config utility will be extremely helpful.
Answer: Problem fixed.  Here's what i did:
Ran a backup on Thursday night of C drive.   I waited until Friday and ran check disc on the good partitions. all came back ok.  Shut down the server.  Unplugged the RAID 1 with the HD with bad sectors.  I then inserted 2 new HD's with and created a fresh RAID 1.  I then plugged the bad sector drive into a spare SATA port and boot the server with Paragon Disk Manager 14 Business.  I then imaged the good partitions from the old RAID to the new RAID.  All worked ok after a few hours.    restarted and everything came back up.


Links from external XML not working anymore, AS3/Flash

Question: Hope somebody can help me...I have an external XML file loading in Flash. It worked perfect but since this week not anymore. The links in the XML file are the problem.  I have no idea why.
In Flash I get the message:
Error #2044: Unhandled IOErrorEvent:. text=Error #2035: URL Not Found.
The XML is loading the first time I click on the button and the  link works, but after that no text and links are loading at all!
I give the code that I use:
var txtFld:TextField = new TextField();
var txtFmt:TextFormat = new TextFormat();

var xml:XML;
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest("background.xml");
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE, onComplete, false,0,true);
function onComplete(evt:Event):void {
evt.target.removeEventListener(Event.COMPLETE, onComplete);
xml = new XML(evt.target.data);
}

txtFmt.font = avenirRoman.fontName;
txtFmt.size = 12;
txtFmt.leading = 4;
txtFmt.color = 0x616161;
txtFld.defaultTextFormat = txtFmt;
txtFld.embedFonts = true;
txtFld.antiAliasType = AntiAliasType.ADVANCED;
txtFld.thickness = -100;
txtFld.sharpness = 50;
txtFld.multiline = true;
txtFld.wordWrap = true;
txtFld.width = 500;
txtFld.autoSize = TextFieldAutoSize.LEFT;
txtFld.x = 270;
txtFld.y = 145;

btn10.addEventListener("click", afterClick2);
function afterClick2(e:Event):void {
txtFld.htmlText = xml.INFO[0].toString();
addChild(txtFld);

}

btn11.addEventListener("click", afterClick3);
function afterClick3(e:Event):void {
txtFld.htmlText = xml.INFO[1].toString();
addChild(txtFld);

}

btn12.addEventListener("click", afterClick4);
function afterClick4(e:Event):void {
txtFld.htmlText = xml.INFO[2].toString();
addChild(txtFld);

}

Then I tried to put in extra (IOErrorEvent) code:
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, catchIOError);
function catchIOError(event:IOErrorEvent){
trace("Error caught: "+event.type);
}
urlLoader.load(new URLRequest("Invalid XML URL"));
trace("Continuing with script...");***

Then I get the message:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at main3_fla::MainTimeline/afterClick2()
And the XML file is not loading at all.If I take out all the links in the XML, text is loading perfect.
Can anybody tell me what's wrong?
Thanks
Comment: Maybe your XML are malformed. Can you show it?
Comment: Here's my XML:

www.yahoo.com
Comment: You're really opening a tag ** and closing as ** ?
If yes, that's the error.
Comment: sorry, I gave the wrong xml. Here's the good one I use:
Comment:
www.yahoo.com
Comment:
www.yahoo.com
Comment: I don't know what happens, but this editor doesn't give http before yahoo. But I'm sure the code is right...because it is working, only after clicking the link, the xml is not displayed in my Flash site anymore
Comment: I can't figure out anything that happened to your site. Try placing traces everywhere for debuging, maybe you can find the error.
Comment: I solved the problem, maybe it will help somebody else too:
I wrote this line extra:txtFld.setTextFormat(txtFmt);

and that helped. Among other things, for example a link in xml works good with this code:
text

and not

maybe it will help somebody else and thanks for your reply, it helped a lot
Answer: This entire "issue" is really weird, are you sure you are writing AS3-code?
I can't for my life understand the following things:

What is your issue? Can you load your xml-file and all links
once? Is the trouble the second time when you try to reload your xml
file? Does it always work whenever you don't have links inside
xml-file?
You mention a button that loads your xml file, I see no
button in your code that provides that functionality
From where are you trying to load your xml-file, is it a local file from your
computer or is it from the web somewhere (on a web-server)?
You do a new URLRequest("background.xml") but you provide no absolute
URL, meaning this could be some kind of path change so
"background.xml" links to something else the second time (no idea how, but anything is possible)
Your code seems weird I can't tell if the entire code is some part of a
constructor or something else. You do "addChild" more than once,
this could become an issue if txtFld is some kind of class member
and there are multiple instances of the class.
I don't understand that IOErrorEvent-example you provided, you deliberatley throw an
error, catch it somewhere and then expect it to continue with script
outside of the catch block before the invalid urlRequest?

The Error #1009 thing you were describing is quite simple, when you
    enter that function, you don't have access to either variables
    "txtFld", "xml" or xml doesn't look as you expect it to.
This all boils down to the following:

I can't help you with your issue unless you provider more context for
when things are initialized/created and when things are called, as it
is now you are mixing initialization and invocation without giving
the correct context for either


Different Homepages based on user role

Question: I'm starting a new site for a client. They have different user roles depending on what account you sign into on their site. Some users will see all options others won't. Some will see options that other accounts can't and vice versa. I was wondering if I will need a separate view-page made for each type of account or if I could use one view-page but lock specific people out from seeing specific things on their page. If able to do either way what would be the easier/recommended of the two.
Answer: I think you should use second variant, cuz support a few page very hard. So if you chose second variant  you just use @if(isAdmin){one html} else {other html} in your view page.
Comment: Okay I'll try this. Thank you for helping. I'm a student doing a work term and everything my job entails I will learn next semester haha. Any and all help is welcome

Different Homepages based on user role


Android - ArrayAdapter mixed positions?

Question: TL;DR - I have an array adapter, filled by an ArrayList of User object,
and I want to print their order numbers - 1st, 2nd, 3rd... etc
- while scrolling fast back and forth.. those numbers get mixed..
instead of 1,2,3,4 after scrolling fast back and forth I get 1,2,9,4 for example..
I don't get why this happens, I've tried several stuff to solve it but with no success, I even took that text view out of the view holder to see if it helps but no success there too.
here's my adapter:
public class HomeHallOfFameAdapter extends ArrayAdapter<User> {

private HomeFragment fragment;
private ArrayList<User> data;
int page;

public HomeHallOfFameAdapter(Context context, ArrayList<User> data, HomeFragment fragment, int page) {
    super(context, 0);
    this.data = data;
    this.fragment = fragment;
    this.page = page;
}

@Override
public int getCount() {
    return data != null ? data.size() : 0;
}

@Override
public User getItem(final int position) {
    return data.get(position);
}

@Override
public long getItemId(final int position) {
    //only used for adapters connected to a cursor.
    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    MyHolder holder = null;

    final User user = data.get(position);

    //initiallize the views
    if (convertView == null) {

        convertView = LayoutInflater.from(getContext()).inflate(R.layout.home_frag_hall_of_fame_item, null);
        holder = new MyHolder();

        holder.profileImage1 = (ImageView) convertView.findViewById(R.id.home_hallofame_image);

        convertView.setTag(holder);

    } else {
        holder = (MyHolder) convertView.getTag();
    }

    final TextView titleRank = (TextView) convertView.findViewById(R.id.home_hallofame_title);
    final String numberEnding = MainScreenActivity.getInstance().NumberWithSuffix(position+1);
    titleRank.setText(numberEnding);

    loadImage(user.getImages().get(0), holder.profileImage1);

    return convertView;
    //return super.getView(position, convertView, parent);
}

private class MyHolder {
    //TextView titleRank;
    ImageView profileImage1; //fameBlueBtn;
}

}

the problem is the titleRank textView..
NumberWithSuffix is just a method that implements the number ending:
//method to get the currect number endings.
public String NumberWithSuffix(int number) {

    String outputNumber = "";
    String numberString = String.valueOf(number);

    if (String.valueOf(number).endsWith("11")) {
        outputNumber = numberString + "th";
    } else if (String.valueOf(number).endsWith("12")) {
        outputNumber = numberString + "th";
    } else if (String.valueOf(number).endsWith("13")) {
        outputNumber = numberString + "th";
    } else if (String.valueOf(number).endsWith("1")) {
        outputNumber = numberString + "st";
    } else if (String.valueOf(number).endsWith("2")) {
        outputNumber = numberString + "nd";
    } else if (String.valueOf(number).endsWith("3")) {
        outputNumber = numberString + "rd";
    } else {
        outputNumber = numberString + "th";
    }
    return outputNumber.trim();
}

any idea what's my problem?
thanks for any help.
Comment: then it shouldn't be in MainActivity it should rather be a Utillity class. You can make that static in utility class and access it and your problem is related to reycling mechanism.
Comment: implement viewholder pattern for textview also just like imageview. also what is `MainScreenActivity.getInstance()` ??. you can have your conditions in adapter itself
Comment: you also need to  understand listview recycling mechanism
Comment: I understand the list view recycling mechanism.. I took the textview out of the view holder to try and see if that's the problem,
Comment: MainScreenActivity.getInstance() is used to get to that method as it is used by me from several locations.. wouldn't want to write the same code more then once
Comment: on that my friend i agree :>
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/83658/discussion-between-raghunandan-and-jozeri).
Answer: You have this
MainScreenActivity.getInstance()

I assume you instantiate a Activity class here. I suggest you move your NumberWithSuffix(int number) to a appropriate Utility class make the method static and you can use the same else where. All your utilities should not be in Activity. Also take care of holding reference to a activity and avoiding memory leaks
Your position of items seems to be fine. I tested your sample and it works fine.
You can make few changes to follow the viewholder pattern as below
@Override
public View getView(final int position, View convertView, ViewGroup parent)  {

MyHolder holder = null;

final User user = data.get(position);

//initiallize the views
if (convertView == null) {

    convertView = LayoutInflater.from(getContext()).inflate(R.layout.home_frag_hall_of_fame_item, null);
    holder = new MyHolder();

    holder.profileImage1 = (ImageView) convertView.findViewById(R.id.home_hallofame_image);
    holder.titleRank = (TextView) convertView.findViewById(R.id.home_hallofame_title);

    convertView.setTag(holder);

} else {
    holder = (MyHolder) convertView.getTag();
}
final String numberEnding = Utility.NumberWithSuffix(position+1);
holder.titleRank.setText(numberEnding);

loadImage(user.getImages().get(0), holder.profileImage1);

return convertView;

}

ViewHolder
private static class MyHolder {
    TextView titleRank;
    ImageView profileImage1; //fameBlueBtn;

}

Create a Utility class
public class Utility {

    public static String NumberWithSuffix(int number) {

        String outputNumber = "";
        String numberString = String.valueOf(number);

        if (String.valueOf(number).endsWith("11")) {
            outputNumber = numberString + "th";
        } else if (String.valueOf(number).endsWith("12")) {
            outputNumber = numberString + "th";
        } else if (String.valueOf(number).endsWith("13")) {
            outputNumber = numberString + "th";
        } else if (String.valueOf(number).endsWith("1")) {
            outputNumber = numberString + "st";
        } else if (String.valueOf(number).endsWith("2")) {
            outputNumber = numberString + "nd";
        } else if (String.valueOf(number).endsWith("3")) {
            outputNumber = numberString + "rd";
        } else {
            outputNumber = numberString + "th";
        }
        return outputNumber.trim();
    }
}

Also instead of this
final User user = data.get(position);

You can use
final User user = getItem(position);

since you already have
@Override
public User getItem(final int position) {
return data.get(position);
}

Comment: Hi, first.. thanks a lot for taking your time and trying to help me!

sadly, this still doesn't help. but at least I'm thinking of approaching the problem differently now, tried my code in a "normal" list view.. it works.
so im guessing the problem is with the horizontal list view library i am using.. =\
Comment: I don't know you were using horizontal list
Comment: U can try locus Rocha two way view available on github
Answer: I would just go with BaseAdapter with a 2 datasets (or more is you need) and just mix them by type from your datasets in getView()...
Answer: So.. I've solved this issue..
my code was ok, as I mentioned, it works fine in a vertical list view, but this problem happens in a horizontal list view..
I removed the list view github library i was using and switched to Horizontal Recycler View.. it works great now !

Android - ArrayAdapter mixed positions?


Why $f(x)$ is Riemann integrable?

Question: If somebody can explain to me why the following function is Riemann Integrable on $[0,1]$ and how to find $\int_0^1 f(x)~dx$
$$f(x)= \begin{cases}1 &\text{ if }  x=0\\
0 &\text{ if } x \in [0,1] \setminus \Bbb{Q}, \\
\frac 1n &\text{ if } x=\frac mn \in [0,1] \cap \Bbb{Q} \text{ with } \gcd(n,m)=1\end{cases}
$$
Comment: Do you mean $f(x)=0$ if $x\in[0,1]\setminus\mathbb Q$?
Comment: At $x=0.5$ $f(x)=$  both $0$ and $0.2$
Comment: what's the value of $f$ for $x$ irrational of $(0,1)$ ?
Comment: As a side note, the $\LaTeX$ treatment of piecewise "case" definitions is covered [in this part](http://meta.math.stackexchange.com/a/5025/3111) of the homegrown MathJax quick tutorial.
Comment: See http://math.stackexchange.com/questions/309763/f-is-riemann-integrable?rq=1
Comment: Thank you, yes, its $[0,1]\Q$
Answer: Assuming that you mean
$$f(x)=\begin{cases}1,&x=0, \\ 0, & x\in [0,1]\setminus\mathbb Q, \\ \frac{1}{n},&x=\frac{m}{n}\in [0,1]\cap\mathbb Q,~\operatorname{gcd}(m,n)=1\\ \end{cases}$$
We first note that $0\leq f\leq 1$ and therefor
$$0\leq\int\limits_{0^*}^{1}\!f(x)\,\mathrm{d}x \leq \int\limits_{0}^{1^*}\!f(x)\,\mathrm{d}x.$$
Let $\varepsilon>0$, then the set
$M:=\{\frac{p}{q}~|~1\leq q\leq \frac{1}{\varepsilon},~0\leq p\leq q\}$ is finite and we can define a step function
$$\psi:[0,1]\rightarrow\mathbb R,~\psi(x)=\begin{cases} f(x),&x\in M \\ \varepsilon,&x\notin M\end{cases}.$$
It is obvious that we have $f\leq\psi$ and therefor
$\int\limits_{0}^{1^*}\!f(x)\,\mathrm{d}x\leq\int\limits_{0}^{1}\!\psi(x)\,\mathrm{d}x=\varepsilon$. This yields that $f$ is riemann-integrable with $$\int\limits_{0}^{1}\!f(x)\,\mathrm{d}x=0.$$
Comment: What is this symbol you are using in the second formula on the integration bounds?
Comment: $\int\limits_{a^*}^{b}\!f(x) \, \mathrm{d}x=\sup\{\int\limits_{a}^{b}\!\varphi(x)\,\mathrm{d}x~|~\varphi~\text{is a step-function},~\varphi\leq f\}$ and $\int\limits_{a}^{b^*}\!f(x)\,\mathrm{d}x=\inf\{\int\limits_{a}^{b}\!\psi(x) \, \mathrm{d}x~|~\psi~\text{is a step-function},~f\leq\psi\}$ denote the lower integral and the upper integral of $f$. $f$ is riemann-integrable if it is bounded and $\int\limits_{a^*}^{b}\!f(x)\,\mathrm{d}x=\int\limits_{a}^{b^*}\!f(x) \, \mathrm{d}x.$
Answer: For a slightly more high-powered answer, this function is continuous everywhere except the rationals, so it meets the Lebesgue criterion for Riemann integrability: A bounded function on a compact interval is Riemann integrable if and only if it is continuous except on a set of measure zero.

Why $f(x)$ is Riemann integrable?


Compiled error, declared with attribute error in qcacld-2.0

Question: <code>CC      drivers/staging/qcacld-2.0/CORE/SERVICES/COMMON/adf/adf_nbuf.o
In file included from include/linux/linkage.h:4:0,
                 from include/linux/kernel.h:6,
                 from drivers/staging/qcacld-2.0/CORE/SERVICES/COMMON/adf/adf_nbuf.c:29:
drivers/staging/qcacld-2.0/CORE/SERVICES/COMMON/adf/adf_nbuf.c: In function '__adf_nbuf_validate_skb_cb':
include/linux/compiler.h:347:38: error: call to '__compiletime_assert_1270' declared with attribute error: BUILD_BUG_ON failed: sizeof(struct cvg_nbuf_cb) > FIELD_SIZEOF(struct sk_buff, cb)
  _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)
                                      ^
include/linux/compiler.h:330:4: note: in definition of macro '__compiletime_assert'
    prefix ## suffix();    \
    ^
include/linux/compiler.h:347:2: note: in expansion of macro '_compiletime_assert'
  _compiletime_assert(condition, msg, __compiletime_assert_, __LINE__)
  ^
include/linux/bug.h:50:37: note: in expansion of macro 'compiletime_assert'
 #define BUILD_BUG_ON_MSG(cond, msg) compiletime_assert(!(cond), msg)
                                     ^
include/linux/bug.h:74:2: note: in expansion of macro 'BUILD_BUG_ON_MSG'
  BUILD_BUG_ON_MSG(condition, "BUILD_BUG_ON failed: " #condition)
  ^
drivers/staging/qcacld-2.0/CORE/SERVICES/COMMON/adf/adf_nbuf.c:1269:2: note: in expansion of macro 'BUILD_BUG_ON'
  BUILD_BUG_ON(sizeof(struct cvg_nbuf_cb) >
  ^
scripts/Makefile.build:308: recipe for target 'drivers/staging/qcacld-2.0/CORE/SERVICES/COMMON/adf/adf_nbuf.o' failed
make[3]: *** [drivers/staging/qcacld-2.0/CORE/SERVICES/COMMON/adf/adf_nbuf.o] Error 1
scripts/Makefile.build:455: recipe for target 'drivers/staging/qcacld-2.0' failed
make[2]: *** [drivers/staging/qcacld-2.0] Error 2
scripts/Makefile.build:455: recipe for target 'drivers/staging' failed
make[1]: *** [drivers/staging] Error 2
Makefile:824: recipe for target 'drivers' failed
make: *** [drivers] Error 2
</code>
How can I fix it?

misource
compiler:GCC4.9
wlan driver:qcacld-2.0 LA.bf184.108.40.206.rb1.17
I'm a noob and use google seem can't found some answer
Comment: These errors are about the compiler not finding the headers where these things are declared. Pick one of the errors and find out where it is supposed to be getting these symbols from. I'm not sure anyone here can really help you because this is going to be very specific to your build environment. Certainly, without the CMake file(s) it is impossible to even guess at the problem.
Answer: Nuke the python wrapper in your root makefile like this
https://android.googlesource.com/kernel/msm/+/e7fb62baa7c8b803d7e3b3f3d8bf4e2b916b659d
And nuke Wall and Werror flags from Kbuild of qcacld
https://github.com/DerpGang/msm-3.18/blob/f8b18a46f0da4d3aed84f29eb29f2578884e90d4/drivers/staging/qcacld-2.0/Kbuild#L1009
https://github.com/DerpGang/msm-3.18/blob/f8b18a46f0da4d3aed84f29eb29f2578884e90d4/drivers/staging/qcacld-2.0/Kbuild#L1008
Here we are disabling the compiler flags so the code warnings won't be treated as errors.
Note:-
In case you get segmentation fault after removing python wrapper, check for any residual compiler flags or re add the wraper
Comment: `EXTRA_CFLAGS += -Wno-implicit-function-declaration`
thanks man


Example: outer measure is sub-additive but not countable additive

Question: I am looking for an explicit example, but cannot find one. Any help would be great. Thanks a lot!
Comment: For a rather extreme example see [Is there a maximum to the amount of disjoint non-measurable subsets of the unit interval with full outer measure?](http://mathoverflow.net/questions/119646/is-there-a-maximum-to-the-amount-of-disjoint-non-measurable-subsets-of-the-unit).
Answer: Nonmeasurable sets give examples. One is "the" Vitali set, which contains exactly one element of each equivalence class of elements of $[0,1]$ by the relation "$x$ is related to $y$ if and only if $x-y \in \mathbb{Q}$". Denoting this by $V$, there are countably many disjoint translates of $V$, namely $V+q$ where $q \in \mathbb{Q} \cap [-1,1]$. The union of these is some set $U$, and $[0,1] \subseteq U \subseteq [-1,2]$. So $m^*(U) \in [1,3]$. But the outer measures of each of the translates are the same; thus the sum of the outer measures of the translates is not $m^*(U)$ but rather $+\infty$.
Comment: @AyushKhaitan You may miss an important detail: the domain of the outer measure is the entire power set. The outer measure is indeed countably additive when restricted to the measurable sets. Thus *any* counterexample must involve a bunch of nonmeasurable sets.
Comment: I understand the example. But how does non measurability show subadditivity? Shouldn't I have a countable number of measurable sets, the sum of whose individual measures exceeds the measure of the countable union, to show subadditivity?
Comment: @AyushKhaitan And you do, that's what I pointed out in the last two sentences. More explicitly, $m^* \left ( \bigcup_{q \in \mathbb{Q} \cap [-1,1]} V+q \right )$ is some number between $1$ and $3$ while $\sum_{q \in \mathbb{Q} \cap [-1,1]} m^*(V+q)$ is $+\infty$.
Comment: Thanks! But the Wikipedia article on Vitali sets says that we cannot assign a measure to a Vitali set at all. Are you saying that we can indeed assign an outer measure to it, although we can't explicitly determine it?
Comment: Yes (this is a part of my comment from a moment ago).
Comment: What if the outer measure of a Vitali set is 0? If we cannot explicitly determine the outer measure of a Vitali set, how can we be sure it is not zero?
Comment: @AyushKhaitan It cannot be zero. I can give two proofs. First: any set with outer measure zero is Lebesgue measurable. (More generally, the measure produced by the Caratheodory construction is always complete.) This can be seen using the monotonicity of the outer measure. Second: $m^*(U) \geq 1$ because $[0,1] \subseteq U$. Thus if $m^*(V)$ were zero then there would be a contradiction (we would be able to conclude $1 \leq 0$). Similarly $m^*(V)$ cannot be any larger than $1$, since $V \subset [0,1]$.


How can I implement probability prediction for One vs One classifier specifically in Sklearn?

Question: I am trying to get probability instead of hard prediction by a One vs One classifier. It is not supported by Sklearn implicitly. Is there nay way to implement it by myself? If so please explain?
For instance the thing in mid is getting scores per classifier and summing them up per class then l1 norm these scores to get a prob values. Do you think this is right intuition ?
Answer: It's already one method for classifiers in development version. You can take the risk to use them.
It provides more precise probability value than other classifiers with probability value by regression
http://scikit-learn.org/dev/modules/calibration.html
Answer: Following this issue, looks like it is recommended to use the decision_function() in such a case.
For example:
X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]])
y = np.array([2, 0, 1, 2])

multi_clf = OneVsOneClassifier(Perceptron(shuffle=False))
ovo_prediction = multi_clf.fit(X, y).predict(X)

ovo_decision = multi_clf.decision_function(X)

votes = np.round(ovo_decision)
normalized_confidences = ovo_decision - votes


Increment/Decrement to only odd values in Kendo Numerictextbox on up/down spinners/keys

Question: I have a Kendo NumericTextBox. When some certain field has some certain values,the range of values for that NumericTextBox would be only odd values.
Setting step to 2 will work if current value is odd value.
So if user enters some value like  22 and clicks on up spinner, it should increase values to 23, then 25 on next click.
If current value is 30 and user clicks on down spinner , it should decrease value to 29 , then  27 on next click.
Answer: Here is solution for you: http://jsfiddle.net/a6Ek2/8/
var numericTextBox = $("#bar").kendoNumericTextBox({
    format: "d",
    value: 1,
    step: 2, }).data('kendoNumericTextBox');

numericTextBox.element.parent().find('.k-link').mousedown(function () {
    var value = numericTextBox.value();
    if (value % 2 === 0) {
        if ($(this).find('span.k-icon').hasClass('k-i-arrow-n')) {
            numericTextBox.value(value - 1);
        }
        else {
            numericTextBox.value(value + 1);
        }
    } });

You can also block entering data from keyboard and set step on 2:
$("#foo").kendoNumericTextBox({
    format: "d",
    value: 1,
    step: 2,
});

$("#foo").attr('readonly', true);

Comment: I'm afraid that catch keydown event of the numericTextBox is the only way to do it. Kendo don't provides last spin direction in their api. I updated jsFiddle for you here: http://jsfiddle.net/a6Ek2/9/
Comment: Thanks,It works on up/down spinners. what about on key press?  I wish I could detect whether it's  up or down clicked/pressed on bind event.
Answer: This is a little tricky but might work. You should play with step setting it to 1 or 2 depending on the current value of the numeric text field.
Then you change the value when the spinner is clicked or the value changes. Something like this:
function adjustStep() {
    var value = this.value();
    if (value % 2 == 1) {
        number.options.step = 1;
    } else {
        number.options.step = 2;
    }
}

var number = $("#numerictextbox").kendoNumericTextBox({
    step : 1,
    value : 21,
    spin: adjustStep,
    change: adjustStep
}).data("kendoNumericTextBox");

JSFiddle here: http://jsfiddle.net/kF2h7/1/
Comment: Setting step 2 will work once value in textbox gets to odd value but not  for a even value. It seems there is no easy way to detect whether user clicked on  up/down spinner or pressed up/down key.


Unity Addforce Bug

Question: I'm currently working on a simple 2d jump and run game. I want to move my player with physics (using addforce).

In the editor,  my player jumps at a normal height. But when i build the game it suddenly jumps way higher. I put everything in fixedUpdate() and don't know where the problem is?
<code> //Movement
 rb.velocity = new Vector2(horizontalMove, rb.velocity.y);
 //Jump
 if (jumpPressed)
 {
     if (isGrounded)
     {
         rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
         anim.SetTrigger("takeOf");
     }
 }
</code>

Dan
Comment: Please edit your post to make it about *one* point - asking two questions in a single post doesn't work well on Stack Overflow.
Answer: If jumpPressed is true for every frame when the jump key is held, this could be the issue. This would mean that the code could act several times, reapplying the upwards force several times (before it goes far away enough from the ground that the ground check does not detect it). If this is the case, it can be fixed by:

rather than using AddForce, set the vertical velocity to the velocity of the jump.
changing the jumpPressed to only return true if jump was pressed this frame
Imposing a limit to how often you can jump (if you cannot jump twice within 0.1 seconds, that could fix the issue)
Comment: yeah, thats the issue. Thank you very very much :)

Unity Addforce Bug


How to make a block matrix positive semi-definite?

Question: I have a matrix $A=\begin{bmatrix}
\textbf{0}_{N\times N} & S\\
S^T & \textbf{0}_{M\times M}
\end{bmatrix},$ where $S\in R^{N\times M}$. What $S$ would make $A$ a positive semi-definite matrix?
Answer: Take any $z = (z_1,z_2)^T$. We have
\begin{align*}
& \left(z_1^T z_2^T \right) A \begin{pmatrix} z_1 \\ z_2 \end{pmatrix} \\
& = z_1^T S z_2 + z_2^T S^T z_1 \\
& = k(z) + k(z)^T \\
& = 2k(z)
\end{align*}
where $k(z) = z_1^T S z_2$.
Now suppose $k \geq 0$. If you take the vector $z^\prime = (-z_1 , z_2)^T$, $k(z^\prime) \leq 0$.
So positive semi-definiteness can only be achieved if $k(z) = 0$ for all $z$ which is the case if $S = 0$.
Answer: Since $A$ is real symmetric, $A$ is diagonalizable and similar to some diagonal matrix $D$.
If $A$ is positive semi-definite, so does $D$ and hence all entries in $D$ are non-negative numbers.
Since $A$ is traceless, so does $D$ and hence all entries of $D$ are zero.
This means $D$ is the zero matrix and so does $A$.


Exibir imagem recebida via socket na tag img

Question: Estou recebendo imagens de um servidor e preciso exibir a imagem na página html.As imagens são recebidas via socket, então tenho apenas o conteúdo da imagem.
A tag img exibe uma imagem quando há o src, neste caso seria necessário salvar a imagem no lado do cliente para depois exibir?
Agradeço pela atenção.
Comment: Em qual formato a imagem é recebida, base64?
Comment: @LucasCosta obrigado pela ajuda. Para funcionar eu precisei fazer apenas isso:
var b64Response = btoa(image);
document.querySelector("#myImage").src ='data:image/jpeg;base64,'+b64Response;
http://stackoverflow.com/questions/20784145/display-image-from-http-response-with-image-content-type
Comment: Não tenho certeza de qual formato. Uso uma biblioteca para extrair a imagem de um vídeo mjpeg no servidor e enviá-la ao cliente.
Comment: Se for base64, essa resposta pode te ajudar: http://pt.stackoverflow.com/a/169877/32827
Comment: Legal @BrunoClementino, responda sua pergunta :)
Answer: Encontrei a solução com base nestes links:
https://pt.stackoverflow.com/a/169877/32827  sugerido por @LucasCosta e
https://stackoverflow.com/questions/20784145/display-image-from-http-response-with-image-content-type
Precisei converter a imagem recebida var b64Response = btoa(image);
e por fim atribuir a img.src dessa forma: document.querySelector("#myImage").src ='data:image/jpeg;base64,'+b64Response;


How to Resize UiButtons to fit on any iPhone Screen Size

Question: I made an app (using storyboard) that fits the screen of iPhone 6. So when I tested it in iPhone 5 it becomes different.
I enabled auto layout and size classes but I don't know how I can use them to make this work.
How can I make the buttons (Event, Dialled, Missed, and Received) resize to fit on other iPhone screen sizes.
Comment: Select your blue view. and add constraints to it like here discussed in detail:

http://stackoverflow.com/a/34368263/4272498
Comment: basics of autolayout and constraints http://stackoverflow.com/questions/31799888/constraints-to-take-care-of-different-iphone-ipad-sizes-for-images-xcode-7-beta/31800662#31800662
Comment: Is the blue bar a subview of the table view, or a sibling of it? Post a screen shot of that scene's section in the document outline, with all the disclosure triangles turned down.
Comment: @Irfan you saved me. Thank you very much.
Answer: Looks like the UITableView is is missing some basic constraints. Or there are other constraints, that block others. (i.e. fixed width constraint)
This is how it should be:

Simple.


Retirar um valor a partir de um menu de radio button

Question: Bom dia, estou a tentar fazer um sistema de rating de estrelas com javascript mas não estou a conseguir retirar um valor apartir da escolha do menu de radio buttons.
O botão Add serve para adicionar o valor que cada radio button tem ao texto do input readonly que está à direita mas com o meu código o output é apenas undefined.
Este é o meu layout, tem 5 radio buttons juntamente com 5 labels editadas em CSS para ficarem com este aspeto:

Ainda sou muito novato no Javascript por isso se descobrirem código desnecessário no meu script ficarei feliz pela ajuda, este é o script:
var estrelas;

var estrela5 = document.getElementById('star5').value;

var estrela4 = document.getElementById('star4').value;

var estrela3 = document.getElementById('star3').value;

var estrela2 = document.getElementById('star2').value;

var estrela1 = document.getElementById('star1').value;

if (document.getElementById('star5').click()) {
    estrelas.value = estrela5;
}

if (document.getElementById('star4').click()) {
   estrelas.value = estrela4;
}

if (document.getElementById('star3').click()) {
   estrelas.value = estrela3;
}

if (document.getElementById('star2').click()) {
   estrelas.value = estrela2;
}

if (document.getElementById('star1').click()) {
   estrelas.value = estrela1;
}

function setValue() {
     if (input2.value == '' || input2.value == null) {
          input2.value = estrelas;
     }
};

Este é o meu código do menu de radio buttons HTML:
<input type="radio" id="star5" name="rate" value="5" />
5 stars
<input type="radio" id="star4" name="rate" value="4" />
4 stars
<input type="radio" id="star3" name="rate" value="3" />
3 stars
<input type="radio" id="star2" name="rate" value="2" />
2 stars
<input type="radio" id="star1" name="rate" value="1" />
1 star

Comment: não seria mais simples contar o número de estrelas que foram selecionadas (em amarelo)?  mas o seu código se vc inverter a ordem dos `if`, começando por "star1" até "star5", vais ter ao final o maior valor, o que já resolveria o seu problema, só falta verificar se está selecionado,ou seja, se está "checked"
Answer: Como as estrelas tem valor fixo (de 1 a 5) acho desnecessário você precisar pegar esse valor de inputs, como você ja sabe os valores, creio que você pode armazenar esses valores em um array e fazer a inserção em seu input readonly conforme necessário.
Fiz um exemplo, você pode adaptar caso queira.

const stars = [1,2,3,4,5];
document.querySelectorAll('.stars li').forEach(function(li, index) {
    li.addEventListener('click', function() {
        document.querySelector('.starSelected').innerHTML = (index == 0 ? stars[index] + " Estrela" : stars[index] + " Estrelas")
    });
});
ul {
  display: flex;
  justify-content: center;
  align-items: center;
  list-style: none;
}

li {
  border: 1px solid;
  border-radius: 5px;
  margin: 10px;
  padding: 10px;
  cursor: pointer;
}

.starSelected {
display: flex;
    justify-content: center;
    align-items: center;
    text-transform: uppercase;
    padding: 5px;
    border-radius: 5px;
    background-color: #e1fd66;
    width: 100%;
    max-width: 200px;
    margin: 0 auto;
   }

1 star

2 star

3 star

4 star

5 star

Sem Estrelas

Comment: Olá Lucas, agradeço a sua ajuda mas consegui resolver o meu problema criando uma função onclick para cada input, muito obrigado na mesma :)


Why do marches usually end with a repetition of the last note?

Question: In many marches, such as the following, the last note of the melody is repeated emphatically (or repeated an octave above). Often using sforzando, marcato, or fortissimo possibile. Here are a few examples:
The Gallant Seventh

King Cotton

Stars and Stripes Forever

Why do marches often employ this technique? Is there a name for it?
Answer: That's called a 'stinger'.
It's an idiomatic thing to do in traditional march writing, and it usually completes the last musical phrase.
Some conductors will play with time right between the penultimate note and the stinger as a last little bit of tension and release--a quasi-allargando of sorts. (In effect, playing with the audience, as they are all expecting the stinger at the end.)
Also, marches were traditionally performed with one additional D.C. (da capo), returning to the beginning to play the opening section one last time. In this case, the stinger acts as a pick-up note to the beginning phrase.
Comment: The stinger is _so_ idiomatic and expected that its omission can also play with the audience's expectations.  One of the better-known examples is Sousa's _Semper Fidelis_.
Comment: Often conductors opt not to play them as well.  I know a former conductor at Ithaca hated them and would point blank refuse to have his ensembles play them.
Answer: I think it's due to the (obvious) association with Marching. The two beats of the stinger tell the marchers when to stop moving their feet.


Cannot pass string variable to function to use eval

Question: I'm trying to use eval built in function within my function, if I do eval(text) or eval("x * 2 + (x + 5)") it could return the calculation but when I pass the text to my function it said TypeError: can only concatenate str (not "int") to str. I already cast it to string but still no avail
x = 1
text = "x * 2 + (x + 5)"

def test_func(x):
    res = eval(x)
    return res

test_func(text)

Comment: You're telling me `x` inside `test_func` is `1`‽ **Are you sure?!**
Comment: Think about what the value of `x` is inside and outside the function…
Comment: I already checked it and the value and the type is the same
Comment: oh sorry, I thought the variable x outside the function and inside the function is different (local function variable)
Answer: the argument x of the test_func is assumed to be an integer becasue you decalare before x=1. If you rename the argument it works:
x = 1
text = "x * 2 + (x + 5)"

def test_func(my_eval_string):
    res = eval(my_eval_string)
    return res

Answer: You are passing 'x' instead of 'text'.
Please check below one:
x = 1
text = "x * 2 + (x + 5)"

def test_func(text):
    res = eval(text)
    return res

print(test_func(text))


Convergence/ divergence tests

Question: If i split this equation to test for convergence/divergence, I get one part to be divergent and the other convergent. Can I say something meaningful about convergent + divergent = ? Or is there another way?
$$\frac{3}{\ln(n)}+\frac{(-1)^n}{\ln(n)}$$
$$\frac{3+(-1)^n}{\ln(n)}$$
Comment: Convergent+Divergent=Divergent
Comment: what's your original sequence? To split you usually have to prove absolute convergence first
Comment: In your example, both parts are convergent (and converge to zero) as $n$ approaches positive infinity. Did you mean something else?
Comment: @Christian original is the last 'function'. I left the sigma notation out. It goes to infinity and start with n=2. I think I wasn't supposed to split it then since conditional and absolute convergence is explained in another section.
Answer: HINT Note that
$$\dfrac2{\ln(n)} \leq \dfrac{3+(-1)^n}{\ln(n)} \leq \dfrac4{\ln(n)}$$
Comment: So 2/ln (n) is divergent, and since that is less than the original 'function'. The original function must be divergent?
Comment: @flux $\lim_{n \to \infty} \dfrac2{\ln(n)} = 0$

Convergence/ divergence tests


Why Linux guest VMs performs better than Windows ones in terms of network?

Question: I am testing the network performance of VMs in Xen and Hyper-V using Iperf and Netperf. In both hypervisors I found a Linux guest VM in different modes is having a relatively high performance than a Windows one. Even a fully virtualized Linux guest VM showed a better performance than a Windows guest VM with PV drivers.
So for each virtual machine I used the loopback address to create a client-server model on the same virtual machine. I established the same tests on all virtual machines and I didn't specify any buffer size or window size, and I left it for the tools to decide.
For instance, testing a TCP conncetion using the following commands:

iperf -c 127.0.0.1

or

netperf -H 127.0.0.1

and I have got the follwing results by Iperf on Hyper-V in 32-bit environments:
Linux (Enlightened): 18 Gbits/s
Linux (Unenlightened): 10.5 Gbits/s
Windows (Enlightened): 3 Gbits/s
Windows (FV+IS): 0.5 Gbits/s
Windows (Unenlightened): 0.4 Gbits/s
Both hypervisors and both tools showed the same performance, also in 64-bit environments.
So is there any explanation for this ?!
Note: FV+IS >> unenlightened guest VM with Integration Services installed.
Comment: You're testing the performance of the loopback device? For why?
Comment: Please share your testing methods and data.
Comment: @tristan I apologize for the undetailed question..I have edited it.
Comment: @ChrisS Well it is only a test environment, and all what I am trying to do is to benchmark the performance of the VMs in their different modes.
Comment: You can't test network performance over loopback.  Windows loopback is entirely different to the Linux one.  The Windows loopback performance is really bad even on bare metal in comparison to Linux.  Don't even go there.
Answer: Your benchmark is not testing the network performance of either operating system.
Linux implements the loopback device as a pure software layer, with no connection to actual networking devices. On Windows, there isn't even a loopback device linked to the 127.0.0.1 address.
All your tests could be measuring is the performance of CPU scheduling and memory bandwidth. Linux and Windows have very different network stacks and I'm not sure anyone paid attention to do any performance optimizations on the loopback device driver (or whatever is the equivalent in the Windows kernel).
Is there any particular application you use that is transferring large amounts of data through local TCP/IP connections? If so, that's one of the most inefficient methods of transferring data locally.
Regarding actual network performance, please beware that Windows and Linux have different network stack with different default settings. You should investigate what your application will be using in terms of buffers, TCP window, etc and adjust iperf/netperf accordingly to mimic that behavior. Then transfer data between different VMs on the same host, VMs on different hosts, VMs and physical servers, etc. Pay attention to network ports' settings, uplink saturation, etc.
Again, your tests are only benchmarking non-optimized algorithms and data structures running purely in software.
EDIT: You may want to read more about the improvements done in loopback network in Windows Server 2012 and Windows 8.
Comment: What would be an efficient method for transferring data locally?
Comment: Shared memory? Named pipes? Writing to a file? TCP/IP was designed to work over unreliable network connections and thus adds unnecessary complexity when data has to travel locally within a single computer. Note that the OP is talking about maxing out his local data transfer over TCP/IP, so I assume he wants to transfer a huge amount of data. If your application is not doing that, TCP/IP locally is more than adequate, even with the added complexity.


Scraping content from html page

Question: I'm using nokogiri to scrape web pages. The structure of the page is made of an unordered list containing multiple list items each of which has a link, an image and text, all contained in a div.
I'm trying to find clean way to extract the elements in each list item so I can have each li contained in an array or hash like so:
li[0] = ['Acme co 1', 'image1.png', 'Customer 1 details']
li[1] = ['Acme co 2', 'image2.png', 'Customer 2 details']

At the moment I get all the elements in one go then store them in separate arrays. Is there a better, more idiomatic way of doing this?
This is the code atm:
data = Nokogiri::HTML(html)
images = []
name = []
data.css('ul li img').each {|l| images << l}
data.css('ul li a').each {|a| names << a.text }

This is the html I'm working from:

      Acme co 1

       Cusomter 1 details

        Acme co 2

         Customer 2 details

Thanks
Comment: Looks about right to me. What's not working?
Answer: Assuming the code you have is giving you what you want, I wouldn't try to rewrite anything significant. You can be more brief and idiomatic by replacing your #each methods with #map:
data = Nokogiri::HTML(html)
images = data.css('ul li img')
names = data.css('ul li a').map(&:text)

Comment: `.map(&:self)` is illegal syntax, no? I guess you mean `.map(&:itself)`; but then why `map` at all?
Comment: Thanks for that, that's much cleaner than mine!

Ideally what I'd like, and I may not explained in properly above,  is process each li separately. For example if the first list item is missing an image then the image array will be offset by one.
Answer: data = Nokogiri::HTML(html)
images = data.css('ul li img')
names = data.css('ul li a').map(&:text)

This simplifies your code slightly, but your original version wasn't too bad.
And my simplification may not generalise if you are, for example, scraping images from multiple regions on the page! In which case, reverting back to something like your original may be fine.

Scraping content from html page


Coldfusion/IIS - Errors occuring when refreshing pages

Question: We have 2 load balanced web servers running Windows Server 2012 and ColdFusion 11 which replaced servers running Windows Server 2008 and ColdFusion 10. We had no issues under ColdFusion 10. Under ColdFusion 11 pages initially load without error but refreshing the page in the browser consistently produces error messages in Firefox developer tools similar to below.
<code>GET http://abc.web.def.com/CFIDE/scripts/cfform.js [HTTP/1.1 304 Not Modified 98ms]

GET http://abc.web.def.com/CFIDE/scripts/masks.js [HTTP/1.1 500 Internal Server Error 105ms]

GET http://abc.web.def.com/includes/jquery/UI/jquery-ui-1.9.2.custom/js/jquery-1.8.3.js [HTTP/1.1 304 Not Modified 102ms]

GET http://abc.web.def.com/includes/jquery/UI/jquery-ui-1.9.2.custom/js/jquery-ui-1.9.2.custom.min.js [HTTP/1.1 500 Internal Server Error 105ms]

GET http://abc.web.def.com/myFolder/mySubFolder/myApp.css [HTTP/1.1 500 Internal Server Error 105ms]
</code>
Again, these errors don't occur on initial page load - only when the page is refreshed and as a result it is impossible to get a page to reload completely. The issue occurs on both of the new servers. We've compared every IIS and ColdFusion setting we can think of, to no avail.
Any idea as to what is going on here?
Comment: If the error only occurs on reload, possible causes could be cookies (session-handling) or the http-referrer. As far as I know these are the only parts of a GET request that differ on the second run.
Comment: The 304 status code are not errors. The web server should send that on a refresh to tell the browser it is okay to use its cached version (the file has not been modified).  The 500 error on JavaScript and css files is odd.  By persistence we mean is the load balancer configured to deliver each request from the browser to the same ColdFusion server? Otherwise each request may be delivered to a different server than the first and that will cause session errors if they are not shared.
Comment: Also those 500 errors should be writing some entries is the Windows system event log. Look there.  You won't find anything in the ColdFusion logs because those are not files handled by ColdFusion (js and css from your example). And if you don't see any of these requests or errors on your web servers then the response could be coming from your load balancer.
Comment: I really appreciate the responses. It turns out the culprit was the web.config files under the root folder of the sites (we have 2). I'm not even sure how it happened, but we seemed to have had a mixture of CF10 and CF11 versions of web.config, e.g. Server 1: site A with CF10 version, site B with CF 11 and then Server 2: site A with CF11 and site B with CF10. What's the proper way to close this question out?
Comment: (Edit) Yes, cookie/session related issues would be my first guess as well. What kind of persistence? Also, what errors do you see in the logs: IIS failed request logs, CF error logs, event logs, etc...?
Comment: Thanks for the responses.
Comment: Thanks for the responses. Any further advise on troubleshooting or verifying session handling? Leigh - what do you mean by persistence? The IIS error log is empty; no CF error are logged on these failures. Still reviewing the event logs but nothing so far...
Comment: Did you search both cf_root\logs and \runtime\logs\? I guess whether they contain any info depends on exactly when the error occurs. Is failed request tracing enabled in IIS (probably not enabled by default)? Is the load balancer using some sort of sticky session or [persistence](https://en.wikipedia.org/wiki/Load_balancing_%28computing%29#Persistence)?
Comment: @Miguel-F - Good catch on the file type. I did not notice they are all css/js files, doh.  user3455390 - Is it *only* those file types?
Comment: You can just add an answer with your solution. It is okay to answer your own question. Try to be descriptive. That way if someone comes across this issue later they can clearly see what the issue was. Glad you figured it out.
Answer: It turns out the culprit was the web.config files under the root folder of the sites (we have 2). I'm not even sure how it happened, but we seemed to have had a mixture of CF10 and CF11 versions of web.config, e.g.
Server 1:

site A with CF10 version
site B with CF11 version

Server 2:

site A with CF11 version
site B with CF10 version

My co-worked actually figured this out after getting an error in IIS manager when attempting to view mime types on one of the sites. IIS manager returned an error pointing to a problem with web.config.
Comment: "This week on the WebDev channel: Web.config files, friend or foe?" ;-)
Comment: I have had my share of headaches dealing with web.config files.


Does the bijectivity of a continuous linear operator on a dense subspace of a Banach space imply the injectivity on the whole space?

Question: Let $X$ be a Banach space and let $T:X\longrightarrow X$ be a continuous linear operator. Suppose that there is a dense subspace $N$ of $X$ such that the restriction $T|_{N}:N\longrightarrow N$ is injective and ${\bf surjective}$, i.e., it is a bijection. Is it true that $T$ is necessarily an injection on the whole $X$ (i.e., is it one-to-one on the whole $X$)?
(And, what is the situation if $X$ is a (separable) Hilbert space?)
I think/feel that the answer is negative, but I am unable to find a counterexample. Does anybody have a counterexample for the question? Thanks in advance.
Comment: I  have heard something like this from my advisor if I am not mistaking: There exists a space with a subspace of codimension 1 that is dense in it! If this is true, then the embedding (identity) of this subspace provides a counter-example.
Comment: I am not sure about Banach assumption though.
Comment: How is this a counterexample?  The embedding is of course still invective on a full space
Answer: Let $X = \ell^2(\mathbb{Z}^+)$, and $N = c_{00}(\mathbb{Z}^+)$ the subspace of sequences with only finitely many nonzero terms. Let $T = I - S$, where $S(e_1) = 0$ and $S(e_n) = \frac{n}{n-1} e_{n-1}$ for $n > 1$. Then
$$\ker T = \mathbb{C}\cdot \sum_{n = 1}^{\infty} \frac{1}{n}e_n \neq \{0\},$$
but $T\lvert_N$ is bijective, for $x \in N$ with $x_n = 0$ for $n > k$, we have
$$(T\lvert_N)^{-1}(x) = \sum_{m = 0}^k S^m(x).$$


If $K$ is a splitting field of $f\in F[x]$, is $F(\alpha)$ a splitting field of $f/(x - \alpha)$?

Question: My definitions ($F$, $K$, $L$ denote fields):

A field extension is any field homomorphism. An $F$-extension homomorphism between extensions $\phi\colon F\to K$ and $\psi\colon F\to L$ is a field homomorphism $\xi\colon K\to L$ such that $\xi\circ\phi = \psi$.
A splitting extension of an $f\in F[x]\setminus\{0\}$ is an extension $\phi\colon F\to K$ such that $f_\phi$ splits into linear factors (by $f_\phi$, I mean $f$ with with coefficients replaced with their $\phi$-images), and it satisfies the following "minimality" condition: If $\psi\colon F\to L$ is another extension wherein $f_\psi$ splits, then we have an $F$-extension homomorphism $\xi\colon K\to L$.

I am trying to prove that

Every (nonzero) polynomial of $F$ has a splitting extension unique up to $F$-extension isomorphism.

I am stuck on proving the "uniqueness up to isomorphism" part (having successfully proven the existence part). In particular, the question that has cropped up is essentially this:

Question: Let $\phi\colon F\to K$ be a splitting extension of $f$. Let $f_\phi(\alpha) = 0$ for $\alpha\in K$ so that $f_\phi = (x - \alpha)g$ in $L[x]$, where $L := \phi(F)(\alpha)$. Is the inclusion $L\hookrightarrow K$ a splitting extension of $g$?

Can you help?
Comment: I don't see why you have any doubts: $f_\phi$ is both $(x-\alpha)g$ and a product of linear factors in $K[x]$, so by uniqueness of factorisation $g$ is a product of linear factors in $K[x]$.
Comment: @ancientmathematician Shoot! I forgot to add another property of a splitting extension.
Comment: @ancientmathematician Added now.
Answer: Yes. More generally, for all field extensions $F\le L\le K$, if $K$ is a splitting field for some $f(x)\in F[x]$ over $F$,
then $K$ is a splitting field for $f(x)$ over $L$.
First, $K$ is by definition an extension of $L$.
Let $L\le E\le K$ and suppose $f$ splits over $E$.
Now, we have $F\le E$, so $E$ is an intermediate extension of $K/F$ such that $f$ splits over $E$.
Since $K$ is a splitting field over $F$,
we have $E=K$.
Of course, you can translate all these into mappings (for example, $F\le K$ means there exists a field homomorphism $\phi:F\to K$),
but there is really no need to complicate things.


Query for get Execution Time in Prometheus

Question: I used Grafana ,Prometheus and Metrics
I need to Prometheus Query for get Execution-Time(Latency) for each request process
Answer: If you are using Prometheus server >= 2.16, you can enable query logging. This will log all the queries made and their stats/timings.


Mixed Effects Analysis in MATLAB

Question: I am new to Mixed Effects analysis, so please forgive my ignorance. I would like to determine if there is any significance between the means of two successive time points in an imaging ROI study. Each ROI contains 2500 voxels and there are 6 time points (thus, 6 mean values, one for each time point). Currently, I set up the analysis as follows:
tbl = table(Voxels, Mean, Time, 'VariableNames', {'Voxels','Mean','Time'});

Voxels, Mean, and Time are 15000 x 1 vectors as follows:
Voxels Mean Time
   2   3.4   1
   3   3.4   1
   .    .    .
   23   19   2
   16   19   2
   .    .    .
   19   13   6
   6    13   6

How do I go about setting up the model equation? I was thinking,
fitlme(tbl, 'Mean ~ Voxels + (1 | Time)  + (Voxels-1 | Time)' );

Answer: If your interest lies in comparing the mean outcome scores over time, it sounds like time should be adjusted in the model as a fixed effect, i.e. Mean ~ time. To specify a random intercept for voxel, accounting for some of the intracluster variability, you may use a term like (1 | voxel) in the formula. This gives you something very similar to the repeated measures ANOVA.

Mixed Effects Analysis in MATLAB


Como tiro as caixas de explicação do Microsoft VSCode?

Question: Olá, boa noite!
Estou programando em python pelo VSCode e sempre que escrevo alguns comandos, aparecem explicações sobre o que estou digitando, me atrapalhando pq aparece um BLOCO ENORME me explicando o que é um print(), e o que ele pode fazer...
Segue a img mostrando o que estou falando:
Imagem do bloco de explicação do VSCode
Answer: Pode desativar nas definições.
Ir a File -> Preferences -> Settings
Text Editor -> Suggestions


How to filter URLs for embedded IMG tags?

Question: This is a great presentation about Drupal security. They were talking about ways to only allow  tags from certain trusted domains.
Any ideas how to do that? I couldn't find a D7 module for that.
Answer: If you mean disallowing  elements where the src isn't on a whitelist, then you can make a custom input filter.
The first step is to make a hook_filter_info to declare your input filter.  You would then make a callback function that does the work.
The callback would do some regex matching, looking for  elements and pulling out the src attributes.  Then regex match the src against your whitelisted domains.  If everything is OK, let the image pass, else replace it with whitespace.
Finally, make a hook_menu which sets up a settings page so you can enter your whitelist via the UI.
Once you have done all of this, you add your filter to the appropriate input formats.  When the page gets rendered out, the filter will be applied.
All of this is rather easy.  The heavy listing is the  regex, but I suspect 15 min of googling will find some good ones.
Answer: What I've done in this circumstance is to create my own BBCode style filter so as to take out that huge regex issue and have total control over the creation of the img tag, eg, I never allow casual users to enter it in any html filter.  Also, it's a lot easier to input for some less than stellar users :)
For example, [img:www.host.com/foo/bar/baz.jpg] can be easily checked for the host, and if you don't want potentially animated gifs, you can disallow them (although yes I do know browsers are looking at the contents of the file now, not the extension, but that's another story), and also, important at least for me, you can set up the css so you don't have a huge image ruining your site formatting, and pretty easily the above turns into

if all is good in the world, or

or even
if it's not.
Obviously, this doesn't help with any pre-imported content, but moving forward, it might help out.
ADDITION:
I pulled this out of some code and I hope I got all of it:
function YOURMODULE_bbc_inject($text) {

  $types=array('img', 'youtube');

  foreach ($types as $type) {
    $match=array();
    if (preg_match_all('/\[(' . $type . '):([^=\\]]+)\]/i', $text, $match)) {
      $s = $r = array();
      foreach ($match[2] as $before => $after) {
        $s[] = $match[0][$before];
        $r[] = YOURMODULE_bbc($type, $after);
      }
      $text=str_replace($s, $r, $text);
    }
  }

  return $text;
}

and then helpers:
function YOURMODULE_bbc($type, $after) {

  switch ($type) {

    case 'img':
      $foo=explode('/',$after);
      $host=$foo[0];

      if (YOURMODULE_valid_img_host($host)) {
        return '';
      } else {
        return '[INVALID IMAGE]';
      }

    case 'youtube':
      return '';

    default:
      return '[HUH?]';
  }

}

function YOURMODULE_valid_img_host($host) {

  $foo=explode(',', variable_get('YOURMODULE_img_host_blacklist','www.foo.com,foo.com,www.bar.com,bar.com'));

  if (in_array($host, $foo)) {
    return FALSE;
  } else {
    // you can check for valid image type here if desired, otherwise...
    return TRUE;
  }
}

You would use the first function in a filter process, I'd show you how to do it in D6 in a second or two, but I know you are using D7, but it should be straightforward enough to figure that out from some of the other questions and answers on here.  Just make sure it runs as late as possible so it doesn't inject some HTML that another filter would disable.
But, if all is installed correctly, you "should" now be able to have a [img:www.foo.com/evil.jpg] denied on your website, plus I threw in the [youtube:35I6Iue_XDE] to show how to extend it to other injectable things.
(It's up to you to add the black list variable into an admin/settings form, but that's also pretty straightforward)
END OF ADDITION :)
Of course, another avenue for this is to not allow images at all in your text and instead have a multiple value image field that can populated and then displayed alongside the text or in a lightbox, etc.  And there you could use all sorts of node() and validate() operations to check those fields for sanity/safety before displaying them.
Comment: You let your user put whatever they want in the text field, and then use the filter to modify it on display. That way, if a blacklist changes, for example, it catches it.  You rarely want to modify input and then save it.  So I would do it in a filter.  If you are asking about the last alternative, I like doing that in nodeapi('view') (D6) or for you in D7 its equivalent.  That way the validation is done in real time, eg, on display/view.
Comment: thanks. You do that with a hook_filter_info() or with a hook_form_alter() when the user submits the form?


PHP: Confused about FOR loops and 2 brackets

Question: just a question about the following loop and the brackets at the end (i just started learning PHP so its likely a noob question).
i wrote the following code and it didnt work:
        <?php
        function maximum(){
        $wieviele = func_num_args();
        $arg = func_get_args();
        $first = $arg[0];

        for ($i = 1;$i < $wieviele;$i++){
        if ($first < $arg[$i])
        $first = $arg[$i];

        return $first;
        }

        }

        echo maximum(1,4,64,9);
        ?>

Now i checked it out in the book i'm reading and the solution is the following code which is nearly equal except the brackets at the end.
        <?php
        function maximum(){
        $wieviele = func_num_args();
        $arg = func_get_args();
        $first = $arg[0];

        for ($i = 1;$i < $wieviele;$i++)
        if ($first < $arg[$i])
        $first = $arg[$i];

        return $first;

        }

        echo maximum(1,4,64,9);
        ?>

And now i would love to know why it only works without the brackets for the FOR-loop.
Thank you
Comment: @Cheesebaron Though I think editing code to make it look better is always a good thing, in this case, leaving it as is might be better. It shows how bad indentation and leaving out braces plays a part in the OP's confusion.
Comment: Please indent your code.
Answer: When you have a control structure such as a for loop or an if statement and you don't include a set of brackets after it, only the next line is considered to be inside the control structure.
So when you have
    for ($i = 1;$i < $wieviele;$i++)
    if ($first < $arg[$i])
    $first = $arg[$i];

    return $first;

It means
    for ($i = 1;$i < $wieviele;$i++){
        if ($first < $arg[$i]){
            $first = $arg[$i];
        }
    }
    return $first;

That is, it sets $first equal to $arg[$i] when appropriate and returns once the loop is finished.
In your code, you have
    for ($i = 1;$i < $wieviele;$i++){
    if ($first < $arg[$i])
    $first = $arg[$i];

    return $first;
    }

Which is equivalent to
    for ($i = 1;$i < $wieviele;$i++){
        if ($first < $arg[$i]){
            $first = $arg[$i];
        }
        return $first;
    }

So you'll enter the first iteration of the loop, check the condition, and then return $first. That is, you return after the first iteration, not when the loop is complete.
My advice concerning omitting/including brackets is to always be as explicit as you can, to make the purpose and effect of your code as intuitive as possible.
Answer: You need to add return $first; outside of your for loop on your first code block to make it work properly.
Demonstration
The first code didn't work because you were returning the value prematurely

Why not make it simpler ?
Use max() instead...
$array = array(1,4,64,9); //<--- Add elements to your array
echo max($array); // 64

Comment: I didnt make it simpler because this was an exercise given in a book. But thx.
Answer: It is reccommended to use bracket even for one line body of loops.if-statemnts.
Equivalent with bracets of this code
for ($i = 1;$i < $wieviele;$i++)
if ($first < $arg[$i])
$first = $arg[$i];

is
for ($i = 1;$i < $wieviele;$i++)
{
    if ($first < $arg[$i])
    {
        $first = $arg[$i];
    }
}


how to increment a count every seconds

Question: I'm trying to develop a stopwatch,But i have problem increment my count using for and while statement please can somebody tel me where am going and help me fix my code,my problem is that once after the interval of time i set it increment from 1 to 10 at one second but i want it to add one every one second.
var count=0;
var s = 0;
setInterval(function(){
    while(count < 10){
    $("#mi").html(count);
        count++;
    }
},1000);

//i also use for but both give did same thing
setInterval(function(){
    for(count=0;count < 10;count++){
        $("#mi").html(count);
    }
},1000);

0

Comment: An interval is something that happens over and over and over so you do not need the loop inside the interval.
Answer: You could use clearInterval to break timer.

The clearInterval() method clears a timer set with the setInterval()
  method.
The ID value returned by setInterval() is used as the parameter for
  the clearInterval() method.

So try this:

    var count=0;
    var tHnd = setInterval(function(){
       if(count == 10)
           clearInterval(tHnd);
       $("#mi").html(count);
       count++;
    },1000);

Answer: The code below works. Why do want to use a loop ? If the point is to increment it by one every second do this :
var count=0;
setInterval(function()
{
  console.log(count++);
},1000);

if you want to increment it by 10 then this
var count=0;
setInterval(function()
{
  console.log(count += 10);
},1000);

how to increment a count every seconds


How to access webform elements in webform.html.twig

Question: I'm trying to figure out a way to access webform elements from webform.html.twig.
I need to style the form; wrapping some elements and adding bunch of styles
all I have in the webform.html.twig is "children" variable which renders the whole form, whereas I need to access every element individually.
I found a link on the web for webform-form.html.twig which might do what I need, however I can't find it in webform template folder
http://cgit.drupalcode.org/webform/tree/templates/webform-form.html.twig?id=1135b65031cd6cd195c2e638300e5ef945a6f652
Any help with this matter is much appreciated.
Answer: I have figured out a solutions for this situation.

create a tempalte file for your form (ex. webform--newsletter.html.twig)
there is a variable (element) where you can access each field of the form like this:

{{ element.elements.YOUR_FIELD_NAME }}

you need to output the form action (submit) at the end of the form link this:

{{ element.actions }}

the trick with this solution is that you need to output a couple of hidden form elements that is required for the form to be submitted properly:

{{ element.form_token }}
{{ element.form_build_id }}
{{ element.form_id }}

My final form template looks like this:

      {{ element.elements.form_description }}

      <form{{ attributes }}>
        {{ title_prefix }}

            {{ element.elements.name }}
            {{ element.elements.email }}
            {{ element.elements.phone }}

            {{ element.elements.message }}
            {{ element.form_token }}
            {{ element.form_build_id }}
            {{ element.form_id }}
            {{ element.actions }}

        {{ title_suffix }}
      </form>

Hope that helps anyone else
Update:
I forgot to mention that you also need to print out the following element:

{{ element.form_token }}

Credit goes to maestrojed Webform twig template causes "the form has become outdated" error
Answer: I know this is a late reply, but I haven't seen the following approach mentioned anywhere else. I think the above answers are a bit hacky. What I do is edit the webform submission html twig file with my own markup, right above the {{form}} line. So in essence, I would access the name input and label by typing {{form.elements.name}} between my html tags, and then between my markup and the {{form}} line type this {% set form =form|without('elements') %}
This keeps the form token, the form id, the form build id so the form can submit
Comment: Yes, using `webform-submission-form.html.twig` is the correct way for a complex form like a webform. Everything else is indeed a bit hacky, as explained here https://drupal.stackexchange.com/a/249864/47547
Answer:

    {{ element.elements.form_token }}
    {{ element.elements.form_build_id }}
    {{ element.elements.form_id }}

          {{ element.elements.form_description }}

          <form{{ attributes }}>
            {{ title_prefix }}

                {{ element.elements.salutation }}
                {{ element.elements.company }}
                {{ element.elements.first_and_last_name }}
                {{ element.elements.phone_number }}
                {{ element.elements.phone_number }}
                {{ element.elements.e_mail }}
                {{ element.elements.theme }}
                {{ element.elements.meeting }}

                {{ element.elements.message }}
                {{ element.form_token }}
                {{ element.form_build_id }}
                {{ element.form_id }}
                {{ element.elements.actions }}

            {{ title_suffix }}
          </form>

Comment: This one work for me as expected.
Comment: Can you explain a little how this is different that the other answers?
Comment: thanks for your help, this is the same way I figured out using kint.
I guess no need for this:

    {{ element.elements.form_token }}
    {{ element.elements.form_build_id }}
    {{ element.elements.form_id }}
Answer: Webforms in Drupal 8 are basically just FAPI render arrays with a UI plus some enhancements. To learn how to theme a Webform and its elements, you should search for articles about theming forms in Drupal 8 which will return some useful blog posts like this one.
Comment: Thanks @jrockowitz for your reply. I have already checked this link before. it is useful when you need to style individual element in the form (e.g email), whereas what I'm seeking is how to theme the form itself and access its elements within the form template. I also want to avoid fields theming (if I have a form with doszens of fields I will end up with dozens of twig files). Anyhow I've figured a solution that I'm going to post it now


How can I track order details (products, quantities) in PayPal?

Question: BACKGROUND
I have an online store.  Previously, I used PayPal "Buy it now" buttons, and I had a button for each product.  I would then periodically export the data from PayPal (download history as CSV) and it would have the following field/value pairs:
Item Title: Type of product (e.g., Nintendo DS)
Option 1 Name: Type of product (e.g., Nintendo DS)
Option 1 Value: Color (e.g., red)
Users were limited to ordering one item per order.  I used this information to analyze what are the top selling products/variations in the store in Excel, and I have a few years of historical data.
DRUPAL COMMERCE
I recently moved the store to Drupal Commerce, although I am still using PayPal for payment (PayPal Payments Standard/WPS) via the Commerce PayPal module.  This works very well, and users are still limited to one item per order.  However, when I export the transaction data from PayPal, it now looks like this:
Item Title: Shopping Cart
Option 1 Name: null
Option 1 Value: null
Is it possible to set the Item Title and options somehow during checkout with Commerce?  If not, how can I analyze my new sales data in Excel in a way that is (at least mostly) consistent with the years of PayPal exports I already have?
Answer: Right now, Commerce PayPal does not itemize order information for PayPal WPS. We implemented itemized order details for Express Checkout in the 2.0 branch, but we currently just have a patch in a feature request to add this support to WPS. If you'd like to review it or follow along, the issue is here: https://drupal.org/node/1301570
In the meantime, your alternative could be to create a View inside your Drupal site that uses Views Bonus Pack to generate a CSV in the same format for your completed orders. That might even be a preferable long term solution, as it will work regardless of what payment method a customer uses to buy from you (in the event that you add additional methods).
Comment: I don't think views bonus pack has a drupal 7 version. I think it should be views data export https://drupal.org/project/views_data_export .


How can I fix the "discount" badge showing on top of everything on my website? I'm using Acowebs Product Labels For Woocommerce 1.1.8

Question: If I scroll on my webpage (tencuialamecaniatatraditionala.ro) the discount
badge is always on top of everything, even on top of the header, which I hate... Please help!
A screenshot with the problem
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Hi Ethan! I sent an image link with my problem in the description of my question, I think that if you open that up you can easily understand what I am asking for... With the addition of the title and description of course!
Answer: For the ones that still face this problem:
Change the z-index value eg.
<code>.element-you-want-to-change {
    z-index: 0;
 }
</code>


Is it possible to give to a specific user role the permission to create content only in a language?

Question: I've a Drupal 8 site using 8 languages. The site is not a multi-domain.
The Admin DE role should have only the permission to create nodes or translate nodes in German, but can view all node in all languages.
I don't find a module that can implement this functionality.
Do you have any ideas?
Answer: Create a custom module for this. I'm including some code that may help get you started. The idea behind this code (below) is preventing a user without the role 'admin_de' from editing content that has a different language than what the 'admin_de' user has set for their account. So there are some obvious differences, but this should be a good start.
In MY_MODULE.info.yml:
name: MY_MODULE
type: module
description: Allows user with particular role to edit content of particular
language.
core: 8.x

In a file called MY_MODULE.permissions.yml, include:
edit same language:
  title: 'Edit Same Language Only'
  description: 'Allow user to edit only nodes matching their account language'

In a file called MY_MODULE.module, include:
<?php

use \Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityForm;

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $currentUser = Drupal::currentUser();
  $roles = $currentUser->getRoles();

  if (in_array('admin_de', $roles)) {
    switch ($form_id) {
      case 'node_CONTENT_TYPE_edit_form':
        $currentUserLanguages = getUserLanguage($currentUser->id());
        $submissionLanguage = getSubmissionLanguage($form_state);
        $status = (Drupal::currentUser()
        ->hasPermission('edit same language') && ($submissionLanguage == $currentUserLanguages));
        if (!$status) {
          throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
        }
        break;
    }
  }
}

/**
 * @param $userId
 * logged in user id
 *
 * @return string of language id logged in user is associated with.
 */
function getUserLanguage($userId) {
  $user = \Drupal\user\Entity\User::load($userId);
  $languageId = $user->language()->getId();

  return $languageId;
}

/**
 * @param FormStateInterface $form_state
 *
 * @return string language id of page
 */
function getSubmissionLanguage(FormStateInterface $form_state) {
  $language = '';
  $form_object = $form_state->getFormObject();
  if ($form_object instanceof EntityForm) {
    $entity = $form_object->getEntity();
    $language = $entity->langcode->value;
  }

  return $language;
}

Hope this helps!


ServerConnection.Cancel method

Question: The SqlCommand class has a Cancel method that, according to the documentation, allows one to cancel a command.
I'm looking for an equivalent method for commands executed through the smo Server class. The ServerConnection class (connectioncontext field of the server class) has a Cancel method but the documentation is not clear on what it does.
Comment: I recommend avoiding SMO. It has a whole host of problems including not being even remotely thread safe. I ended up throwing it away and did everything with `sys.` views.
Comment: Cancel is only useful when you have defined a `SqlBatch` for the command to be executed within.  This is generally done with the `SqlConnection` object but can be between the `SqlConnect` and `SqlCommand`, in the event you need to execute multiple Batches with each Batch containing multiple Commands within a single Connection timeline.
Comment: SQL Profiler doesn't seem to be clear about what it does either.  Whatever it does, doesn't show up in SQL Profiler as a logout event, or anything else I can discern.  I can cancel the connection and then continue what I was doing without throwing any errors.  I'm with Jonathan Allen.  Do it without SMOs.
Comment: Maybe you want to disconnect the serverconnection? https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.common.connectionmanager.disconnect
Answer: The SeverConnection.Cancel() Method works similarly to the SqlCommand.Cancel() method and the Documentation states:

If there is nothing to cancel, nothing occurs. However, if there is a command in process, and the attempt to cancel fails, no exception is
  generated.
In some, rare, cases, if you call ExecuteReader then call Close
  (implicitily or explicitly) before calling Cancel, and then call
  Cancel, the cancel command will not be sent to SQL Server and the
  result set can continue to stream after you call Close. To avoid this,
  make sure that you call Cancel before closing the reader or
  connection.

Meaning that the cancel method will work, If you call it before the call to the close() method.
If you call it after, the command will not be sent to the sql resulting in continues stream to the sql after to call the close() method.
Moreover, if there is a command in process and the attempt to cancel fails, you will not receive an error as no exception is generated in such case.

ServerConnection.Cancel method


Separate get request and database hit for each post to get like status

Question: So I am trying to make a social network on Django. Like any other social network users get the option to like a post, and each of these likes are stored in a model that is different from the model used for posts that show up in the news feed. Now I have tried two choices to get the like status on the go.
1.Least database hits:
Make one sql query and get the like entry for every post id if they exist.Now I use a custom django template tag to see if the like entry for the current post exist in the Queryset by searching an array that contains like statuses of all posts.
This way I use the database to get all values and search for a particular value from the list using python.
2.Separate Database Query for each query:
Here i use the same custom template tag but rather that searching through a Queryset I use the mysql database for most of the heavy lifting.
I use model.objects.get() for each entry.
Which is a more efficient algorithm. Also I was planning on getting another database server, can this change the choice if network latency is only around 0.1 ms.
Is there anyway that I can get these like statuses on the go as boolean values along with all the posts in a single db query.
An example query for the first method can be like
Let post_list be the post QuerySet
models.likes.objects.filter(user=current_user,post__in = post_list)

Comment: I have one word for you: `benchmarking`. There is no simple answer, all will depend on your models, database structure, server configuration and even hardware that you're using. In some cases, python will be faster, in other it will be better choice to filter in on database - level.
Comment: It is a bit hard to read your question because it has so many typos and omissions. `"Make one sql query and get like entry every post id if they exist."` I am really not sure what you are trying to say here.
Comment: @krishnan I am not able to understand what you write. There are too many grammatical mistakes. My comment was referring to this, it was not giving advice on the topic.
Answer: This is not a direct answer to your question, but I hope it is useful nonetheless.

and each of these likes are stored in a model that is different from the model used for news feed

I think you have a design issue here. It is better if you create a model that describes a post, and then add a field users_that_liked_it as a many-to-many relationship to your user model. Then, you can do something like post.users_that_liked_it and get a query set of all users that liked your page.
In my eyes you should also avoid putting logic in templates as much as possible. They are simply not made for it. Logic belongs into the model class, or, if it is dependent on the page visited, in the view. (As a rule of thumb).
Lastly, if performance is your main worry, you probably shouldn't be using Django anyway. It is just not that fast. What Django gives you is the ability to write clean, concise code. This is much more important for a new project than performance. Ask yourself: How many (personal) projects fail because their performance is bad? And how many fail because the creator gets caught in messy code?
Here is my advice: Favor clarity over performance. Especially in a young project.
Comment: Thanks a lot @Konstantin. Adding a many-to-many relation really did give me a new insight. But I don't want a list of everyone who liked the post **won't this be unnecessary overhead for the database**? .Rather, similar to using a many to many relationship is there a way to get only the entry corresponding to the current logged in user.
Comment: You could also add the many-to-many field to the user model instead, (like: `user.posts_the_user_liked`) but that's a bit complicated because you would need to modify the user model. Alternatively, with the design I suggested you can get all posts that are liked by a user via: `user.post_set.all()` Please read http://stackoverflow.com/questions/9352662/how-to-use-the-reverse-of-a-django-manytomany-relationship for more information. As I said, I would worry more about code clarity than performance.
Comment: I  have implemented a UserProfile model that follows a one-to-one relationship with the auth_user model .I have already made a working social network, so now I believe it's time for me to optimize it.If I get all the posts a user has liked, I believe that I will still be forced to search the whole list for only those likes concerning the posts in the context. Would  this be any different from `models.likes.objects.filter(user=current_user, post__in=posts_list)`
Comment: @krishnan I don't know. Sorry.


Puppet: compiling binaries

Question: We use puppet to distribute our own software (i.e., the stuff we write, which we want running on our own servers).  So somewhere we have to compile this software.
It makes sense to me that I might git pull and compile it on the puppet master.  Compile once, distribute, our machines are homogeneous and the binaries run on their anointed hosts.
But when we upgrade hosts, various libraries will change, and we can find ourselves needing to recompile for the new library set.
It seems the right thing to do is to package our software, serve these debs to ourself, and then just use package directives in puppet.
Q1: Does this sound right / Did I miss something important here?
Q2: Then how do the deb's get packaged and uploaded?  Is this a manual release process?  Meaning we upgrade a test server to the new OS and library versions in order to compile and package.
Q2B: Now suppose I install that CI server I keep telling my team I'll get around to installing.  The CI server knows nothing about dist-upgrades, as far as I can tell.  So does this part have to remain manual?
Comment: You create your own apt repository, and you point your CI system at it.
Answer: Your build procedure can be either manual or automated via CI, via a number of triggers. For example (and this is only one example), you can tag a new release in Git, or move an existing tag and your CI application watches that repository or that tag, and builds/uploads your package.
Your release procedure can also be either manual or automated.

Use ensure => latest on your Puppet package resources so that as soon as you publish packages to your repository, they are picked up and installed by your nodes.
Use ensure => 'x.y.z' to pin a package to a specific version. With this approach, you can manually bump the versions on specific nodes/roles/environments.
You can take a hybrid approach combining the two above by using hiera and parametising your modules - you can ensure latest on your dev/build environments, and x.y.z on your production environment for example.
You can remove Puppet from the equation entirely and do manual releases using a tool such as Capistrano.

A separate solution entirely is to utilise Continuous Delivery and treat your servers at cattle, and completely reprovision them with every release - see Martin Fowler's blog for more information on this.
Important Note: The build and release procedures should ideally be completely independent and should not interact, though a successful build could trigger an automated release to a UAT environment for example, and then use a manual/different release procedure for production.

Puppet: compiling binaries