Non-Clickable Menu Items

Question: In a Drupal 8 site, I want to add menu items with "no link", I was thinking that nolink is allowed but when I entered this, I got error

Manually entered paths should start with /, ? or #.

Is there a way for adding menu items not clickable without adding "#" because "#" add attribute [data-drupal-link-system-path=""] and [class="is-active"]
Answer: You need to use route:<nolink> to achieve this. Then it will validate and render without a link.
Comment: That is a separate issue from what you're trying to achieve and either a core bug or problem with your theme, but `route:` is definitely the answer. It even works with Pathauto.
Comment: Thanks so much, I tried it and it working fine, but still adding attributes of [ data-drupal-link-system-path="" ] and [ class="is-active" ]
Comment: The "is-active" class bug has been reported here: https://www.drupal.org/project/drupal/issues/2838351
Comment: It worked for me. Thanks for such a knowledgeable solution.
Comment: +1 upvote - thank you - `` works when adding link in standard Drupal menu, `admin/structure/menu/manage/main/add` so that you can have other words on menu, perhaps to go before a set of links that have similar purpose, e.g. social links (using [menu_link_attributes](https://drupal.org/project/menu_link_attributes) & [fontawesome_menu_icons](https://drupal.org/project/fontawesome_menu_icons) modules. Then also add `nth` child css and the menu can be positioned separately from other links. [menu_export](https://drupal.org/project/menu_export) is handy for putting menu items into config.
Comment: Mind you, I got this error after saving the non-clickable link as per my suggestion "Warning: count(): Parameter must be an array or an object that implements Countable in Drupal\content_sync\Normalizer\ContentEntityNormalizer->getMenuLinkNodeAttached() (line 156 of modules/contrib/content_sync/src/Normalizer/ContentEntityNormalizer.php)."  - this might be specific to my setup but just to note that my suggestion might have issues.
Comment: I think in D9 it is just  now.
Answer: To create a menu item without link in a custom module add to [module_name].links.menu.yml:
url: 'internal:##'
You need to add a second # character (or any other letter or word url: 'internal:#nolink') in order to the href attribute will not rendered empty, which will cause a page reload if the user click the link.
Comment: This is a good solution also. For me better than remove the link, that removes the  tag and then this menu item loose the corresponding css styles.
Answer:
https://www.drupal.org/project/link_attributes
or https://www.drupal.org/project/menu_link_attributes

and add class or style for item [a style="pointer-events:none; cursor:default; text-decoration:none;" ...][/a]
pointer-events:none; cursor:default; text-decoration:none;

Answer: For Drupal 8 you can create a link programmatically using Link::fromTextAndUrl not linkable like that:
$my_link = Link::fromTextAndUrl(t('This is my link text'), Url::fromUri('route:<nolink>'));

Optionally you can convert it to an array using: $my_link = $my_link->toRenderable();

Non-Clickable Menu Items


Check If File Exists, Download and Save File in J2ME

Question: I want to edit my question.
If file still not exist, download and save it, that my case.
To check if file exist, I've try by this code
private boolean isXmlFileExist(){
    try{
        FileConnection fCon = (FileConnection) Connector.open("file:///"+Resource.XML_PATH + "/" + Resource.XML_FILENAME, Connector.READ);
        return fCon.exists();
    }catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

In my resource class
public static final String XML_PATH = "/xml";
public static final String XML_FILENAME = "template.xml";

I have create 'xml' folder under res folder and i have put file 'template.xml' there. But this code always return false.
Whether we can not use the res folder? So, what is the correct path.
Answer: Files under res folder are always available because they are packaged with the class files. So, you do not need to check with FileConnection if they exist.
To access these files you can use Class.getResourceAsStream.
For example:
private InputStream open (String fileName) {
  return getClass().getResourceAsStream(fileName);
}

// call it like this
open(Resource.XML_PATH + "/" + Resource.XML_FILENAME);

Comment: How about download xml file and save it under res folder? Do you have example or tutorial?
Comment: You can not save a file to the application package after it is installed on a device. You may save to the handset internal memory or sd card.
Comment: About download and save file, I have search tutorial about it, but still not find. My plan is to read the file content, create new file and write the content to the new file. Is this a good way?
Comment: Yes, it is. Start finding a place to right that file. Use FileSystemRegistry.listRoots() to see which are available.


Server serving old SSL certificate

Question: About 20 days ago, we have renewed our SSL certificate for https://www.pscquestion.in from GoDaddy. But we are still getting old certificate. But GoDaddy says it is installed properly. We have tested a certificate in sslshopper.com, digicert.com, godaddy.com and ssllabs.com. The results are not stable. sometimes we are getting a valid certificate, but most of the time we are getting an old certificate.
Anyone can give some suggestions to fix this.
Comment: They might have some load balancing setup, and some of their load balanced servers don't have the updated certificate. You need to push GoDaddy to fix the issue. Provide them detailed descriptions how they can see the issue.
Comment: How exactly did you install this certificate? Into what server software?
Comment: What server did they install it on? Why did they do it and not you?
Comment: Godaddy team installed the certificate.
Comment: I think they using apache. i can see that they installed new certificate. issue is we receiving old certificate also (some times). We tested this with different machine, different browser and different network also. Also SSL testing sites also giving different results, some times certificate will be valid, sometimes it shows old invalid certificate.
Comment: That sounds like shared web hosting. We can't support that here; you'll have to follow up with GoDaddy.
Answer: The issue is solved. The issue is with Godaddy. As per support team, they restarted some handler and now it is working well. Thanks for the support.

Server serving old SSL certificate


Images from ipad not rotating properly

Question: I have noticed that users who upload their images from iPad or iPhone have their images sometimes rotated in odd directions. I am not a Drupal guru and I generally find that documentation on drupal "how to" is ..well.. scarce,,
I have spent some time looking into this and did not find anything that would effectively help me.
What I would like to accomplish seems simple in principle but I need help.
Rather then forcing users to rotate images (they find that to be clunky and awkward I have an average user who is interested solely to have things happen simply and without hassle) I would like to have ALL my images on the site checked for orientation and have them automatically display the images in proper orientation.
I came across a module called Imagecache Actions and it is supposed to have Autorotate capability but I have no clue on how to use it for what I need.
ALL help would be greatly appreciated!
Answer: The -auto-orient operator is part of the ImageMagick image processing toolkit, to select the correct orientation of an image based on its EXIF data. Have a look at How to detect shot angle of photo ... for a more complete explanation.
The ImageMagick module integrates this function in Drupal, but they are still having an issue with autorotation. A recent patch is available there.
Your best bet is to try it out and see if it corrects your problem.
Comment: I am getting errors
Warning: Division by zero in theme_image_style_preview()
(which is better then not getting anything)
Comment: I can't use imagemagick (server side limitatons). ImageCache Autorotate does rotate non apple device images Apple device images do not contain exif information so Autorotate does not work.

Images from ipad not rotating properly


Form submit not working in safari and works in all other browsers?

Question: <!DOCTYPE html>

    <title></title>

    <meta charset="utf-8" />
    <link rel="icon" type="image/png" href="images/fav_icon.png">

    <form class="form"  name ="custRegistration"  id="custRegistration"  onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >

            Name *:
            <input type="text" name="name" id="name" placeholder="" pattern="[A-Za-z ]{3,20}" required/>
             <input type="hidden" id="formidentity" name="formidentity" value="domobileappRegistrations"/>

            Email Id *:
            <input type="email" name="email" id="email" pattern="((\w+\.)*\w+)@(\w+\.)+(com|org|net|us|info|biz|co)" required aria-required="true"  placeholder=""  required/>

            <input type="submit" value="Submit" />

    </form>

Above form is working fine in all the browsers except safari(version used is-5.1.7) and iPad.In safari the form is not validating the html5 required attribute and making the form to submit, while in other browsers(chrome,firefox,IE) its working fine.so can anyone tell me how can i make it done with safari??any help would be appreciated..
Comment: The HTML `required` shouldn't be your only validation, just a sidenote
Answer: The HTML form validation is a Working Draft.
It is a method of setting required fields and field types without requiring JavaScript.
Partial support in Safari refers to lack of notice when form with required fields is attempted to be submitted. Partial support in IE10 mobile refers to lack of warning when blocking submission.
Also support for using differently colored borders is not complete in Firefox or Opera - using a separate class for styling works well in both.
In Chrome the attribute formnovalidate doesn't work on <input type="submit"> elements but does on <button type="submit"> elements.
You can try to use the script bellow for all browsers not supporting HTML5 required attribute:
//Required attribute fallback
$('#form').submit(function() {
  if (!attributeSupported("required") || ($.browser.safari)) {
   //If required attribute is not supported or browser is Safari
   //(Safari thinks that it has this attribute, but it does not work),
   //then check all fields that has required attribute
   $("#form [required]").each(function(index) {
    if (!$(this).val()) {
     //If at least one required value is empty, then ask to fill all required fields.
     alert("Please fill all required fields.");
     return false;
    }
   });
  }
  return false; //This is a test form and I'm not going to submit it
});

EDIT:
As alternative, you can use the jQuery validation plugin, in such basic way (more details on how-to use it are if you follow the link):
  $(document).ready(function() {
// validate the form when it is submitted
$("#form").validate();
  });

This is the most browser's compatible solution.
Comment: The code above is jQuery < 1.9.x compatible, test it with jQuery 1.8.2 (because of use of `$.browser`)
Comment: ...or as alternative, include the `jQuery Migrate` plugin together with latest jQuery and the code.
Comment: @bodiO i tried with jquery 1.8.2 its showing the same result...if its working for you and if time permits you  can you please update my code in jsfiddle ???thanks in advance....
Comment: @bodiO thanks for the answers but sorry to say that i am getting the proper output..!!


Only part of a table is parsed

Question: Here is the begging of source code:

Username:

Firstname:

Lastname:

Type:

Crew:

Job title:

Defaultprice class:

Description:

Language:

john.smith

John

Smith

Contractor

Microsoft

Sales manager

A

en

robert.geits

Robert

Geits

Staff

Google

Project manager

B

de

amir.rooney

Amir

Rooney

Staff

Microsoft

Sales manager

A

en

I am using following code for parsing the table. Any ideas why only part of table is parsed? There are a lot of records but current code is able to handle names starting with A and partly with B, but then it stops without giving any errors?
from selenium import webdriver

for tr in driver.find_elements_by_xpath('//*[@id=\"users_table\"]'):
    tds = tr.find_elements_by_tag_name('div')
    print ([td.text for td in tds])

I use selenium because I need to perform login before parsing.
Comment: Are you waiting for the page to fully load before doing the find_elements? - you said yourself it's a big page with a lot of records. If these are delivered by scripts than selenium could be running and getting a partial result before it's complete.  Try a fixed wait to see if this increase your number of hits, if that works, implement a webdriverwait on an object to make sure the page is ready - happy to help more - just say if the fixed wait works and if you need more info :-)
Comment: @RichEdwards I just went for more detailed investigations and noticed that table gets loaded with values on a scroll. So on a scroll it's values are changing in source code. Is there any chance to parse such a case? Haven't seen such a beauty before. Page is fully loaded
Comment: literally helped someone this morning with a scroll issue - but you'll need a  way to scroll, then get your tr's   if you can share a link i can have a look at something better than someone elses question:  -> https://stackoverflow.com/questions/63168429/web-scraping-python-fails-to-load-the-url-on-button-click/63168989#63168989
Comment: Before jumping into the conclusion, can you help me with the information related to the number of rows it's been showing `print len(driver.find_elements_by_css_selector('div.slick-row'))`. By this way we can determine if it's a dynamic loading table or something else.
Answer: Try with the below logic.
# get information from all rows
for tr in driver.find_elements_by_css_selector('div.slick-row'):
    # get the columns in the row
    tds = tr.find_elements_by_tag_name("div")
    # print all td informatoin
    print ([td.text for td in tds])

Only part of a table is parsed


Volume of a bounded solid in R3

Question: What is the volume of the solid in xyz-space bounded by \begin{align}
    y = 2 - x^2 \\
y = x^2 \\
z = 0 \\
z = y + 3 ?
  \end{align}
I have formatted the problem as follows:
$$\iiint 1 \,dx\,dy\,dx$$
\begin{align}
-1 ≤ x ≤ 1 \\
2 - x^2 ≤ y ≤  x^2 \\
0 ≤ z ≤ y + 3 \\
\end{align}
When I solve the triple integral, though, I get a value of zero. My guess is that my limits of integration are wrong, but I need a nudge in the right direction!
Answer: The volume is symmetric with respect to the $yz$-plane, so in the integral:
$$
\int _{-1}^1\int_{x^2}^{2-x^2}\int_0^{y+3} dzdydx
$$
the two parts $\{-1<x<0\}$ and $\{0<x<1\}$ have opposite sign and its sum is null.  You have to express the volume as:
$$
V=2\int _{0}^1\int_{x^2}^{2-x^2}\int_0^{y+3} dzdydx
$$

Volume of a bounded solid in R3


parabola in homogeneous coordinates

Question: So if I have the parabola $Y = X^2$, how do I go about representing this homogeneously?  I know I can parameterize it as $F(t) = (t, t^2)$, but then what?
The reason I ask is because I have a $3\times 3$ matrix that I want to apply to this parabola but before I can do that I need to get it in the proper format.
Answer:
Reformulate this to $x^2 - y = 0$
Homogenize to $x^2 - yz = 0$
Write quadratic form as a matrix:
$$A = \begin{pmatrix}1 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & 0 & 0\end{pmatrix}$$
A point $p$ lies on this parabola if it satisfies $p^T\cdot A\cdot p=0$.
Symmetrize this matrix:
$$B = A+A^T = \begin{pmatrix}2 & 0 & 0 \\ 0 & 0 & -1 \\ 0 & -1 & 0\end{pmatrix}$$
If you want to apply a projective transformation $M$ to all points, i.e. $p\mapsto M\cdot p$, then you can transform the matrix of your conic section to $(M^{-1})^T\cdot B\cdot M^{-1}$.

parabola in homogeneous coordinates


Is fourier transform of $C_0^\infty (\mathbb R)$ dense in $L_\mathbb C ^1 (\mathbb R) \cap L_\mathbb C ^2(\mathbb R) $?

Question: Let $C_0^\infty (\mathbb R)$ be space of smooth functions with compact support on the real line.
Let  $L_\mathbb C ^1 (\mathbb R) \cap L_\mathbb C ^2(\mathbb R) $ be equivalence class of 1-fold and 2-fold integrable functions.
Let $\mathcal F$ denote fourier transformation.
I know $\mathcal F(C_0^\infty) \subseteq L_\mathbb C ^1 (\mathbb R) \cap L_\mathbb C ^2(\mathbb R) $  holds, but is it true that $$\mathcal F(C_0^\infty)=L_\mathbb C ^1 (\mathbb R) \cap L_\mathbb C ^2(\mathbb R) $$ ?
If not true then, is $F(C_0^\infty)$ dense in $L_\mathbb C ^1 (\mathbb R) \cap L_\mathbb C ^2(\mathbb R) $ ?
Thanks in advance.
Answer: Hint: fourier transform is isometery on the shcwartz class or, by density and extension argument, on the space $L^2(\mathbb{R})$. So the image is close. It is also dense. Hence the image will be the all space.
For the density use the following duallity fact.
$\mathscr{F}(F(-x))=f(w)$. Where
$ F(w)= \mathscr{F}(f(x))$.
See the following nice book. The first pages of Chapter 2 answers your question very well.
Fourier Series and Integrals (H. Dym and H. P. McKean)
Comment: Yes but don't forget the normalization constant $\frac{1}{\|\psi\|_{L^1}}$. Note if $f$ is continuous then it is easy to prove $\| f - f \ast \psi_\epsilon \|_{L^2} \to 0$ where $\psi_\epsilon(x) =\frac{1}{\varepsilon \|\psi\|_{L^1}} \psi (x/\varepsilon)$. If $f$ is not continuous, you need to show that $\|f-f_n\|_{L^2 }\to 0$ for some sequence of continuous functions $f_n$.  And note $\phi_\epsilon(x) = \psi(\epsilon x)$ works fine as an approximate ideantity for product. @izimath
Comment: What does density mean? I'm very new at this topic.
Comment: @izimath For $f \in L^2$, if $\varphi,\phi \in C^\infty_c$ then $\varphi \ast f(x) \in C^\infty$ (convolution) and $\phi(x)  \ ( \varphi \ast f(x)) \in C^\infty_c$. Can you describe suitable $\varphi,\phi$ such that $\phi(x)  \ ( \varphi \ast f(x))$ is a good approximation of $f$ in $L^2$ norm ?
Comment: @reuns cutoff function for $\phi$ and the "looking like delta" function(Mollifiers?) for $\varphi$? I forgot the name
Comment: @izimath Yes we need an approximate identity for convolution and an approximate identity for product. Do you know how to construct those from a $C^\infty_c$ function like $\psi(x) = e^{-1/(1-x^2)} 1_{|x| < 1}$ ?
Comment: @reuns I do know how to construct a cutoff function. For the mollifier, maybe $\frac{1}{\varepsilon} \psi (x/\varepsilon)$?


Python invalid format

Question: Running Python 3.12 on Windows. Trying to import multiple .csv files and export as multiple color graphs. I want to add units of measurement and markings also, but I can't seem to get the formatting of my try: section. Every change I could think of to lines 11-13 give me SyntaxError.
import pandas as pd
import matplotlib.pyplot as plt

file_paths = ["1.csv, "2.csv","3.csv", "4.csv"]
import os

try:
    open (r"C:/Users/USER/FOLDER/CSV_FILES")
except: os.path.isfile(path)
with open(path, "r") as f:
    pass
finally IOError
    print("The file cannot be opened")

file_paths = [os.path.join(directory, filename) for filename in
os.listdir(directory) if filename.endswith(".csv")]

colors = plt.cm.viridis(range(len(file_paths)))

for i, file_path in enumerate(file_paths):
    df = pd.read_csv(file_path)

    # Define data to plot
    x = df["column1"]
    y = df["column2"]

    # Create plot with unique color
    plt.plot(x, y, color=colors[i], label=file_path.split("/")[-1].split(".")[0])

    plt.legend()
    plt.title("Graph from", file_path)

    # Save plot as image
    plt.savefig(f"graph_{i + 1}.png")
    plt.clf()

I tried something much simpler for the 'import os' section and I got permission error
PermissionError: [Errno 13] Permission denied: 'C:/Users/USER/FOLDER/CSV_FILES'
 directory = open(r"C:/Users/USER/FOLDER/CSV_FILES")
 assert os.path.isfile(path)
 with open(path, "r") as f:
     pass
 file_paths = [os.path.join(directory, filename) for filename in os.listdir(directory) if filename.endswith(".csv")]

Expected a graph with multiple color for the 4 .csv files
Comment: The permission error appears to be because you're trying to open a folder. You need to open a specific file within the folder. Why are you calling `open` then not doing anything with the file object? And what is `path`?
Comment: The code example is broken. There is a missing `"` in the line where you define `file_paths`. Please edit the question if this error is not in your code.
Answer: You didn't close the double quotes after the first element of your list (1.csv), at line 3:
file_paths = ["1.csv, "2.csv","3.csv", "4.csv"]

Notice that this element even looks different with syntax highlighting. That line should be instead:
file_paths = ["1.csv", "2.csv","3.csv", "4.csv"]

Python invalid format


Inline CSS working ... External CSS not-working for: Text-Align: Center, on a twitter bootstrap Button

Question: Have styled a twitter bootstrap button to be centered in a thumbnail, and when the  CSS is Inline (header or body) it works perfectly, but after moving the styles to an External stylesheet the button is left-aligned..
All the other styles that were inline and moved to an external sheet work perfectly..
Here's a bootply showing a centered-aligned button via an inline style:
http://bootply.com/65903
If you move the style to an external stylesheet, the button will not be centered..
Please advise!
Here's the CSS Style:

Here's the HTML:

                Header

              <button class="btn btn">Button</button>
                <button class="btn btn dropdown-toggle" data-toggle="dropdown">

              </button>

Action

Answer: Try this:

Comment: Great! I'm glad you have been useful.


Do MLB players wear new uniforms every game?

Question: Do MLB players wear new uniforms every game? Or only when pants or top becomes too dirty or torn. The uniforms always look spotless so I assumed they were new.
Comment: Is laundry really impossible in the USA?
Comment: my mom always had trouble with grass stains so I assumed they could be pretty tough.
Answer: The answer is basically No, though there is no official statement of teams many articles I have read so far points out teams does not provide new jerseys to the players for every game. Uniforms are washed, mended and pressed to look as new every game.
From a article of CNN:

Mitch Poole, clubhouse manager for the Los Angeles Dodgers "uniforms used to be scrubbed until the fabric resembled fur. But now they use an industrial stain remover specifically made for Major League called Slide Out".

Factory on Columbus Avenue in New Rochelle (NY), the Raleigh Athletic Equipment Company is where uniforms of the New York Yankees are washed, mended and pressed.
An article on Erica Ford, the official seamstress for the Los Angeles Angels of Anaheim baseball team will further helps in clarifying things.


Eigen value and transpose of the $Matrix$

Question:
Let $A$ and $B$ are linear operator on a finite dimensional vector space $V$ over $\mathbb R$ such that $(AB)^2 = AB$ and $BA$ is invertible , then which of the following are true ?

$AB = BA$ on $V$.

$ Tr (A)$ is non zero

$0$ is an eigen value of $B$

$1$ is an eigen value of$A$

Since $BA$ is invertible , then $A$ and $B$ are invertible , and eigen value of $AB$ are $0$ and $1$ and $AB$ is dioganlizabe , because minimal polynomial of $AB$ is $x^2 -x = 0 $, and we know that the eigen value of $AB$ and $BA$ are same counted with the multiplecity of non -zeroeigen value and $BA$ is invertible . So the eigen value of $BA$ is $1$ with multiplecity $n$.
I am confused. my concept is contradicting.please give a me way how to solve.
Thank you.
Comment: Which linear operator has eigenvalue $1$ with geometric multiplicity $\dim V$? What is then the relation between $A$ and $B$?
Comment: @ Levap   : $AB$ has eigen value $1$ with multiplicity   $dim \ V$
Answer: $A$ and $B$ are square matrices. Since $BA$ is invertible, $A$ and $B$ are both invertible, because $\det(B)\det(A)=\det(BA)\neq 0$.
Thus $ABAB=AB$ implies $AB=I$, and $B$ is the inverse of $A$, thus $AB=BA=I$.
Since $B$ is invertible, it does not have $0$ as an eigenvalue.
You can't say anything about (2) and (4) because all invertible matrices $A$ satisfy your conditions. And of course, not all invertible matrice satisfy (2) or (4), though some do (for example the identity matrix).
A trivial counter example to (2) is a permutation matrix associated to a derangement (thus only $0$s on the diagonal). A trivial counter example to (4) is any multiple $aI$ of the identity matrix with $a\neq 1$.
Comment: @user120386 Actually, what is troublesome here: if $P(A)=0$, then it's a multiple of a *minimal polynomial* (say $Q$), because $\Bbb R[X]$ is a principal ring, and polynomials $P$ such that $P(A)=0$ obviously constitute an ideal. But, given *some* polynomial $P$ such that $P(A)=0$, you only know that $P$ is a multiple of $Q$.
Comment: @ Jean : what can you say about the polylomial $x^2 -x$ which divides the characterstic polynomian of $AB$
Comment: @user120386 Wrong, since $AB=I$ and the characteristic polynomial is thus $(x-1)^n$. You have never proved that $x^2-x$ is the minimal polynomial.
Comment: @ Jean : thanks for your prompt reply.
Answer: can we do this?  it looks like $AB = I.$ here is the reason. we have $$I = (AB)^2 =  ABAB = AB$$ multiplying by $A$ on the right and $(BA)^{-1}$ on the left  gives us $$ABA(BA)(BA)^{-1}=A(BA)(BA)^{-1}\to ABA = A \to (BA)^2 = (BA) $$ and that $BA$ is invertible implies that only eigenvalues of $BA$ is $1.$
i think $(BA)^2 = BA$ and $1$ is the only eigenvalue must imply  that $$BA = I $$ which in turn give $AB = I.$


Number theory: find the value of $a$

Question: In the following problem, you are given three pieces of information. Use them to answer the question.

$GCF(a,b)= 13\cdot 7$
$LCM(a,b) = 13^2 \cdot 7^3 \cdot 41$
$b=13^2 \cdot 7 \cdot 41$
$a \in \mathbb{N}$

What is $a$ ?
Comment: Are you aware of the fact that LCM$\times$GCD = product of the numbers?
Answer: For the solution, it is worth knowing that a * b = GCF(a, b) * LCM(a, b);(If you don't know this, try to prove it(it's easy))
a = GCF(a, b) * LCM(a, b) / b = 4459.
Comment: Thank you so much! :)

Number theory: find the value of $a$


Return object into async.each function in node.js

Question: I want to understand one thing about async module in node.js.
I have created a function that map an object from a form to a model object and return this object.
This object is a video with an array of tags.
My question is where can I return the video ? I know normally it is inside the async callback function but if I do that, the object returned is undefined.
Whereas If i return the video object at the end of the whole function, it works but it's not safe as I'm not sure, my async is finished...
By the way, I don't understand the callback function passed in argument to async.each and
called after  video.products.push(tag); . What does this function do?
Regards
in my mapping.js :
 exports.video = function(object) {

        var video = new Video();
        video.name = object.name;
        video.products = [];

        async.each(object.tags, function(tago, callback) {

                            tag = {
                            "name" : tago.name
                                 }

                            video.products.push(tag);
                            callback();

                        } ,
                   function(err) {
                            if( err ) {
                        console.log('Error' + error);
                                throw err;
                            }

                          logger.debug("into async" + video);

                    }

                    );

           logger.debug("end function " );
            **//return video;**

     }

in my video.js :
 var video = mapping.video(object);
 logger.debug(video);  // return undefined

Comment: Why are you using `async` when your callback function is not asynchronous at all? I really think you want a synchronous [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
Answer: The simple answer is that you can't - at least not via easy or obvious approach. As its name suggests, async is a library for queuing up asynchronous function calls into the event loop. So your exports.video function simply kicks off a bunch of asynchronous functions, which execute one after the other on an unpredictable time-frame, and then returns immediately. No matter where you try to return your video object within the scope of your function calls which are instantiated by async, the exports.video function will already have returned.
In this case it doesn't really seem like you need asynchronous function calls for what you're doing. I'd suggest that you replace your use of async with something like Underscore's each method, which executes synchronously, instead.
http://documentcloud.github.io/underscore/#each
Answer: You'd need to define a callback for your exports.video function e.g..
exports.video = function(object, callback) {
    // video code (snip)...

   async.each(object.tags,
       function eachTag(tag, done) {
           // code run for each tag object (snip)...
           done();
       },
       function finished(err) {
           // code run at the end (snip)...

           callback(thingThatsReturned);
       });
};

...and call it like this:
var videoUtils = require('videoUtils');
var tags = getTags();

videoUtils.video({ tags: tags }, function(thingThatsReturned) {
   // do something with 'thingThatsReturned'
});

By the way, I don't understand the callback function passed in
  argument to async.each and called after video.products.push(tag); .
  What does this function do?

The async.each function will call the 'eachTag' function above (2nd argument) for each item in your array. But because it's done asynchronously, and you might do something else async in the function (hit a database/api etc.), it needs to know when that function for that particular array item has finished. Calling done() tells async.each that the function has finished processing. Once all the functions are finished processing (they've all called done()), async.each will run the 'finished' function above (3rd argument).
This is pretty standard async stuff for Node.js, but it can be tricky to get ones head around it at first. Hang in there :-)

Edit: It looks like your code isn't doing anything asynchronous. If it was, then the above code would be the way to do it, otherwise the following code would work better:
exports.video = function(object) {
    // video code (snip)...

    if (Array.isArray(object.tags)) {
        object.tags.forEach(function eachTag(tag) {
            // code run for each tag object (snip)...
        });
    }

    return thingThatsReturned;
};

...and call it...
var videoUtils = require('videoUtils');
var tags = getTags();

var thingThatsReturned = videoUtils.video({ tags: tags });


OkHttp3 response string show html file instaed of download file data

Question: I using Okhttp3 for download file from server in android application. my link is http://www.webweb.infinityfreeapp.com/lichi/download.php?path=Add.jpg it download file in firefox, chorme smoothly, while in okhttp3 response string shows

but i feel response string has Add.jpg file data. so, what can i change in okhttp3 code or php code that i gather App.jpg data in response string of okhttp3
Php Code
if(isset($_GET['path']))
{
    $url = $_GET['path'];
    $type   = "application/pdf";
    $completePath = "http://www.webweb.infinityfreeapp.com/lichi/";
    $visibleName = "$url";
    $completePath .= $url;
    // Force download
    header("Content-disposition: attachment; filename=$visibleName");
    header("Content-Type: application/force-download");
    header("Content-Transfer-Encoding: $type\n");
    // header("Content-Length: ".filesize($completePath));
    header("Pragma: no-cache");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
    header("Expires: 0");
    readfile($completePath);
    die();
}

I comment Content-Length because it crash system in uncomment
Java code
   OkHttpClient client = new OkHttpClient();
    String url = "http://www.webweb.infinityfreeapp.com/lichi/download.php?path=Add.jpg";
    Call call = client.newCall(new Request.Builder().url(url).get().build());

      Response response = call.execute();
      if (response.code() == 200 || response.code() == 201) {
           Headers responseHeaders = response.headers();
           for (int i = 0; i < responseHeaders.size(); i++)
              Log.d(LOG_TAG, responseHeaders.name(i) + ": " + responseHeaders.value(i));

            String str = response.body().string();
     }

Here str contain above html file information instead Add.jpg file data. so please give answer
Answer: good question
Autually if we send a get request to
http://www.webweb.infinityfreeapp.com/lichi/download.php?path=Add.jpg
we get the right resutl just like
 .
we can get a file in browser, because browser can parse  html ,
when browser get the string result which is a  html page, it create another request with a new Header (Cookie=_test=9e105a99e90025d241c180c29fad3231), and with the Cookie, we get an image file from server.
Comment: so, you need send a request to get a cookie first, and send another request to get the file.
Answer: Thanks for quick and good solution.
i just add header as:-
.header("Cookie", "_test=9e105a99e90025d241c180c29fad3231")
and send again with above code, actual result come


Java Keystore - Where to store the 'Master Password'?

Question: I am developing a Java Swing app that needs to hold passwords to remote servers. I have decided to use the KeyStore to accomplish this.
I store each password under an Alias/Master Password and retrieve them using the same Alias/Master Password.
My question is:
Where should the Master Password be stored?
This is not a cheap attempt at a paradox but a serious question and I am interested in knowing how this problem can be solved.
I don't have any real experience in this area and any help would be appreciated.
Answer:
I store each password under an Alias/Master Password and retrieve them
  using the same Alias/Master Password.

There is a misunderstanding here.
 The keystore is a container for your private credentials and trusted certificates and not just some generic database/hashtable to store passwords.
The best approach would be to store the hash of the password in the database.

Where should the Master Password be stored?

This is a very common problem that comes up very frequent.
Just keep it in your source code which, yes can be decompiled, but delegate the responsibility to the user to keep his account private so that this files are not stolen/examined e.g via a decompiler
Comment: OSX stores generic passwords in its KeyChain, so Apple accept that it can be used for such.
Comment: I don't want users having to enter a password every time they start my app running. So, the only acceptable thing is to store the Master Password. A digest does not solve the problem as the user would have to enter the password...
Comment: @Lyndon:I don't follow:If the user does not provide anything how can you retrieve the password using the alias/password association?
Comment: The Keychain in OSX is accessed using the logged in user's password (I believe). Permission is asked by the OS to access the Keychain. I am developing on OSX but I don't want to use the OSX Keychain as I will also deploy to Windows. For the time being I have hardcoded the Master Password but the problem remains unsolved.
Answer: The master password should either:

be given online by the user
or be stored encrypted with a user-given password. This last should be informed online by the user.
Comment: As above, I don't want my users to have to eneter a password every time they run my app.
Comment: According to Raph Koster: "Never trust the client.
Never put anything on the client. The client is in the hands of the enemy. Never ever ever forget this." (http://www.raphkoster.com/gaming/laws.shtml)


Como pesquisar texto com acentuação, maiusculas e minusculas com html e javascript?

Question: Alguém pode me ajudar, com alguma dica?
Tenho o código abaixo que pesquisa o parágrafo, mas o problema é quando não adicionamos o texto corretamente na caixa de pesquisa (com maiúscula, minúscula e acentos - conforme esta descrito no parágrafo).

$("#textFind").keyup(function(){
    var stringPesquisa = $(this).val();
    $('p').parent().hide();
    $('p:contains('+stringPesquisa+')').parent().show()
  });
div{
  margin: 10px;
  border: 1px solid #333;

}

<input type="text" id="textFind">

 Título 1

 Esse texto está aqui para ser pesquisado.

 Esse outro texto também vai ser pesquisado.

 Texto que vai ser que o usuário vai pesquisar digitando no input.

 Título 2

 esse parágrafo deve aparecer se o texto digitado estiver nessa div.

 esse outro parágrafo vai obedece ao mesmo critério.

 o usuário vai digitar no input e essa div deve aparecer.

Answer: O que você pode fazer é transformar os caracteres maiúsculos em minúsculos ou vice-versa em ambos os casos para a comparação. Com relação aos acentos, você pode substituí-los utilizando uma regex. Você precisaria passar os valores dos parágrafos nos textos e comparar um a um.

$("#textFind").keyup(function(){

    // deixamos a string de pesquisa em minúscula
    var stringPesquisa = $(this).val().toLowerCase();

    // removemos os acentos da string de pesquisa
    stringPesquisa = replaceAccents(stringPesquisa);

    // escondemos o conteúdo
    $('p').parent().hide();

    // executamos a busca por parágrafo e por título
    $('p').each(forEachHandler);
    $('h2').each(forEachHandler);

    // essa função vai receber os valores dos parágrafos e dos títulos
    function forEachHandler() {

          // recuperamos o valor da string do parágrafo/título e deixamos em minúsculo
          var stringP = $(this).text().toLowerCase();

          // removemos os acentos
          stringP = replaceAccents(stringP);

           // efetuamos a pesquisa
           if(stringP.search(stringPesquisa) >= 0) {
              $(this).parent().show();
           }

     }

  });

  // essa função receberá uma string e retornará a mesma string sem os acentos
  function replaceAccents(string) {

     return string != null ? string.replace(/[áàãâä]/gi,"a")
            .replace(/[éè¨ê]/gi,"e")
            .replace(/[íìïî]/gi,"i")
            .replace(/[óòöôõ]/gi,"o")
            .replace(/[úùüû]/gi, "u")
            .replace(/[ç]/gi, "c")
            .replace(/[ñ]/gi, "n")
            .replace(/[^a-zA-Z0-9]/g," ") : "";

  }
div{
  margin: 10px;
  border: 1px solid #333;

}

<input type="text" id="textFind">

 Título 1

 Esse texto está aqui para ser pesquisado.

 Esse outro texto também vai ser pesquisado.

 Texto que vai ser que o usuário vai pesquisar digitando no input.

 Título 2

 esse parágrafo deve aparecer se o texto digitado estiver nessa div.

 esse outro parágrafo vai obedece ao mesmo critério.

 o usuário vai digitar no input e essa div deve aparecer.

O trecho de código da RegEx foi tirado dessa resposta do SOen. Só fiz algumas alterações no código, talvez você deva deixá-lo mais performático.
Comment: Eu editei a resposta. Criei algumas funções para evitar esses códigos duplicados e adicionei a procura por título também, procurando pela tag `h2`. Também adicionei alguns comentários para você entender melhor o que o código está fazendo.
Comment: Para utilizar no título (também), vou ter que adicionar todo o replace para ele?
Comment: obrigado, grande ajuda...
Answer: As pesquisas estão bombando (funcionando) apenas nas tags p, seta pro seu h2 também.
Deve ser algo assim:

$("#textFind").keyup(function(){
    var stringPesquisa = $(this).val();
    $('p').parent().hide();
    $('p:contains('+stringPesquisa+')').parent().show()
    //insere aqui > algo assim
    $('h2:contains('+stringPesquisa+')').parent().show()
});
Comment: obrigado, grande ajuda


Dúvida sobre comando SELECT usando IN

Question: Estou montando um select no MySQL da seguinte forma:
select lista,
 (select if (count(login.LogID) > 0, 'S', 'N') from login where login.LogID = 407 and login.LogID in (11,157,66,158,407)) as Seguindo
from Comentarios

Se eu executo esse select no meu banco ele retorna 'S' no campo Seguindo, porém se eu substituo o meu in da seguinte forma:
select lista,
 (select if (count(login.LogID) > 0, 'S', 'N') from login where login.LogID = 407 and login.LogID in (lista)) as Seguindo
from Comentarios

Onde Lista é um campo da tabela comentarios com o conteúdo 11,157,66,158,407, o MySQL retorna como N no campo Seguindo.
O meu campo lista é do tipo varchar. Alguém saberia me informar o porquê desse comportamento? E como seria possível contornar isso?
Answer: Vamos por partes
1º SQL
select lista,
 (select if (count(login.LogID) > 0, 'S', 'N') from login where login.LogID = 407 and login.LogID in (11,157,66,158,407)) as Seguindo
from Comentarios

Funciona corretamente pois você valida seu LogID dentro de uma lista de inteiros (11,157,66,158,407).
2º SQL
select lista,
 (select if (count(login.LogID) > 0, 'S', 'N') from login where login.LogID = 407 and login.LogID in (lista)) as Seguindo
from Comentarios

Não funciona pois como você disse o campo lista é um varchar, logo quando você passar ele no in desta forma (lista) o campo está sendo entendido como um valor da lista apenas, e não vários valores.
Entenda
Possui 5 itens na lista: (11,157,66,158,407) ou ('11','157','66','158','407')
Possui 1 item na lista: ('11,157,66,158,407')

Cada valor de uma lista é uma linha retornada de um select

Para contornar isso tu pode fazer da seguinte forma
select lista,
 (select if (count(login.LogID) > 0, 'S', 'N') from login where login.LogID = 407 and  FIND_IN_SET(login.LogID, lista)) as Seguindo
from Comentarios

Se quiser saber mais sobre o FIND_IN_SET
Answer: Amigo, você disse que o conteúdo da tabela Comentario é 11,157,66,158,407, se você quis dizer que ao fazer o select nesta tabela ele retorna somente 1 linha com este valor, então o problema é esse, você não esta passando uma lista na sua condição in do select.
Agora, se ao fazer o select ele te retorna 5 linhas e cada linha com um valor, assim:
linha 1 -> 11;
linha 2 -> 157;
linha 3 -> 66;
linha 4 -> 158;
linha 5 -> 407;

Você pode montar seu select assim:
select lista,
 (select if (count(login.LogID) > 0, 'S', 'N') from login where login.LogID = 407 and login.LogID in (select lista from comentarios)) as Seguindo
from Comentarios

Veja aqui um exemplo do select acima.

Dúvida sobre comando SELECT usando IN


Proof that a graph has lebesgue measure zero using fubini's thm

Question: I want to check if my attempt is valid for a problem.
Q. If  $f : E \rightarrow R$ is L-measurable, prove that the graph of $f$ is a null set in $R^{n+1}$ ($\mu = $ Lebesgue measure)
Note: $E\subset R^n$, is a measurable set, hence $x\in R^n, y \in R, R^{n+1} = R^n
 \times R $
My Attempt:
By the corollary: $R^n = R^l \times R^m  \ (n = l+m), $ Suppose X is a L-measurable subset of $R^l$ and Y is a L-measurable subset of $R^m$, then the cartesian product $X\times Y$ is an L-measurable subsest of $R^n$
Define the following measurable subsets
$A = \{ (x,y) \in R^{n+1} \ | \ 0 \leq y < f(x), \ x\in E   \}$
$B = \{ (x,y) \in R^{n+1} \ | \ 0 \leq y \leq f(x), \ x\in E   \}$
$C = \{ (x,y) \in R^{n+1} \ | \ -\infty  \leq f(x) < 0, \ x\in E   \}$
$D = \{ (x,y) \in R^{n+1} \ | \ -\infty  \leq f(x) \leq 0, \ x\in E   \}$
Then, letting $G=graph \ of \ f(x) =y $, we observe that
$\mu(G) = \mu(B-A) + \mu(D-C)  $
After taking the x section of each sets A,B,C,D we see that by fubini's thm
$\mu(A) = \mu(B) = \int_{\{x\in E | 0 \leq f(x) \}}^{} f(x) dx$
$\mu(C) = \mu(D) = \int_{\{x\in E | f(x) < 0 \}}^{} f(x) dx$
Hence, $\mu(G) = 0$
Would appreciate any comments or more elegant/simple solutions!
Answer: Let $G_f$ denote the graph of $f$. If $\mu$ is Lebesgue measure on $\mathbb R^{n}$ and $\nu$ is Lebesgue measure on $\mathbb R$ then  $(\mu \times \nu) (G_f)=\int_{G_f} d\mu \times \nu=0$ by Fubini/Tonelli Theorem because the section of $G_f$ by any point $x \in \mathbb R^{n}$ is the singleton set $\{f(x)\}$ and $\nu \{f(x)\}=0$ for all $x$.


Saber se utilizador está conectado PHP

Question: Quero que um utilizador quando estiver conectado, não deixa ninguem se conectar ao sistema com o mesmo login e password. Ou seja se o admin estiver conectado, e abrir outro browser e abrir com o mesmo utilizador admin, não me deixar. Criei um campo na tabela para guardar se está ou não.
Esta é a tabela, com o novo campo conection para guardar se esta login ou logout.
if(!file_exists($dir.$base)) {

 $base_hndl =   new SQLite3($dir.$base);
 $requete = "CREATE TABLE 'users' (
 id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
 login TEXT NOT NULL,
 password TEXT NOT NULL,
 nom TEXT  NULL,
 prenom TEXT NULL,
 actif INTEGER NOT NULL,
 societe TEXT NULL,
 langue TEXT NULL,
 conection TEXT NULL
 )";
 $resultat = $base_hndl->exec($requete);}

E a variável login
$login=$_SESSION['login'];

Comment: @EnzoTiezzi e se o utilizador não fizer logou e a sessão expirar nunca mais pode fazer login?
Comment: E qual é o problema?
Comment: Queria guardar dentro da tabela, se o utilizador está conectado ou nao. Para dps proibir a entrada, ligarem se com o mesmo utilizador se este estiver no sistema (login).
Comment: é basicamente isso, você cria um campo para armazenar se está logado ou não, ao logar, você verifica se o campo está "true", caso não esteja você cria a sessão, e troca o valor desse campo, caso esteja, você manda uma mensagem que esse usuário já está logado no sistema, e é importante lembrar de voltar o valor desse campo para "false", quando a sessão é destruída.
Comment: O conceito você já tem, te faltou apenas condicionar a criação da variável de sessão com esse campo que você está trazendo ao consultar a existência do usuário (assim espero).
Comment: Verdade, mas também, com os limões que eu tinha, no máximo eu pude fazer uma limonada.
Answer: Você deveria armazenar o horário da última ação/navegação do usuário e o IP.
Assim você poderia verificar com o tempo que sua sessão permanece viva e permitir somente o acesso de quem esta logado naquele momento e ainda informar caso exista uma tentativa de login em outro local, que o usuário já está conectado em outro computador e fornecer até mesmo o IP.
Exemplo, se sua sessão fica viva por 30 minutos, quando o usuário entrar no sistema, ou navegar entre as páginas, fizer alguma ação, você salva o horário no banco de dados e o IP.
| Horario          | Endereco de IP         |
|------------------|------------------------|
| 2014-11-07 08:20 | 22.214.171.124          |

Quando for feito o login ou a mudança de página ou qualquer ação no sistema, você atualiza esses dados, sempre obedecendo o tempo de expiração da sessão.
Se IP do novo acesso = IP do último acesso, o acesso deve ser permitido, pois é o mesmo. Pega o novo horário e atualiza:
| Horario          | Endereco de IP         |
|------------------|------------------------|
| 2014-11-07 08:40 | 184.108.40.206          |

Se for IP do novo acesso diferente do IP do último acesso, então verifica os horários: horário do novo acesso deve ser maior que o horário do último acesso + tempo da vida da sessão.
Ex.:
Novo Acesso            Ultimo Acesso      Tempo Vida Sessao
2014-11-07 08:55       2014-11-07 08:40 + 30
2014-11-07 08:55       2014-11-07 09:10

como 08:55 é anterior a 09:10 (considerando as datas claro) significa que tem outra sessão ativa e o usuário não pode fazer nenhuma ação, incluindo login.
Vamos supor agora que ele tentou fazer o acesso as 09:15
Novo Acesso            Ultimo Acesso      Tempo Vida Sessao
2014-11-07 09:15       2014-11-07 08:40 + 30
2014-11-07 09:15       2014-11-07 09:10

O novo acesso foi feito depois da expiração da sessão ativa do outro usuário então ele pode logar/fazer ações e o banco é atualizado.
| Horario          | Endereco de IP         |
|------------------|------------------------|
| 2014-11-07 09:15 | 126.96.36.199          |

Quando o usuário efetuar o logout, esses campos seriam setados pra null ou, melhor do que isso para facilitar a comparação, para valores default onde fosse possível o acesso.
Ex. no caso de logout:
| Horario          | Endereco de IP         |
|------------------|------------------------|
| null             | null                   |

Com valores default (facilitando a comparação em qualquer situação, evitando exceptions na programação):
| Horario          | Endereco de IP         |
|------------------|------------------------|
| 2000-01-01 00:00 | 0.0.0.0                |

No caso do usuário logado perder a conexão e seu IP ser modificado ele perde o acesso e só consegue acessar novamente quando a sessão dele expirar, ou seja, no meu exemplo, 30 minutos. Para isso, o ideal é avaliar o tempo de sessão que será utilizado, fazendo um equilíbrio entre o tempo que o usuário precisa ter entre uma ação e outra até a sessão expirar e o tempo que o usuário pode esperar caso isso aconteça (mudança do IP e ter necessidade de aguardar a sessão expirar). Acredita-se que sessões curtas são mais seguras. Pode-se aplicar 5 ou 10 minutos para encurtar esse tempo e evitar que o usuário permanece logado caso saia e não efetue o logout.
Pode-se também, para evitar isso, utilizar uma chave gerada na etapa de login e armazena-la em cookie, substituindo a identificação do IP pela chave gerada, contornando assim essa parte do IP. Lembrando que cookies são editáveis, com algumas manobras seria possível acessar de mais de um local. Prefiro a abordagem usando o IP.
Essa é uma das formas de se fazer, das diversas formas possíveis de implementação.
Comment: Gostei da resposta, talvez seja de mais para o caso dele que parece ser mais simples, mas é mais robusta.
Answer: O conceito da forma mais básica de implementação você já tem, ou seja, criar um campo na tabela, mesmo que a tabela errada, que servirá como condicional para criação da variável de sessão.
Te faltou apenas criar essa condição:
// Consulta se o usuário existe e traz os dados

if( $row['conection'] != '1' )
{
    $_SESSION['login'] = $login;
}
else
{
    die( 'Acesso não autorizado. Usuário em uso.' );
}

Lembre-se de atualizar esse campo de volta para zero no logout, caso contrário o usuário nunca mais poderá se re-autenticar.
Comment: Pelo histórico de avaliações alguém não concordou com a resposta e votou contra. Pode dizer o porquê?
Comment: Estou com uma situação, e no caso do cara não fechar o sistema pelo "logout", ou matar o processo do navegador ou der pau na máquina? Nisso ele ficará preso, até ser alterado no banco manualmente.
Comment: A menos que você esteja usando um *handler* de sessões próprio ou autenticação por OAut (Google, Facebook...) a sessão vai expirar quando o navegador fechar, de um jeito ou de outro. Se por um acaso estiver usando mais ou menos como o snippet acima, além de condicionar  valor vindo do banco de dados, condicione também se o superglobal `$_SESSION` foi criado por `session_start()` -E- com algum valor nele.
Comment: Me surgiu essa dúvida porque preciso bloquear acesso simultâneo do mesmo usuário em lugares diferentes

Saber se utilizador está conectado PHP


$C^k_b$ with sup-norm not complete

Question: Let $C^n_b=\{ f : I\rightarrow \mathbb{C}: f~n\textrm{-times continuously differentiable and } \|f\|_{n,\infty} < \infty\}$, where $\emptyset\neq I\subseteq\mathbb{R}$ denotes an open interval and $\|f\|_{n,\infty}=\Sigma_{k=0}^n\|f^{(k)}\|_\infty$ be the function space of our concern. Equipped with the supremum norm this should not be complete.
Does anyone have a (classic) example of a Cauchy sequence for proving the noncompletness?
Comment: Can I ask why you think it's not complete? I think I can prove it's complete.
Answer: The idea is to consider sequence of continuous functions that converge to the function of class $C([a,b])\setminus C^1([a,b])$. Then one needs to integrate this functions $n$ times and prove that the result is Cauchy sequence without limits in $C^n([a,b])$. It will not have the limit because $n$-th derivatives will converge to non-$C^1([a,b])$ function.
For simplicity wee consider case $[a,b]=[-1,1]$. Define functions
$$
y_k(t)=\int_0^t\arctan(ks)ds
$$
One can check that
$$
\lim\limits_{k\to\infty}y_k(t)=\frac{\pi}{2}|t|\notin C^1([-1,1])
$$
One can check that $n$-th antideriveative of $y_k$ is
$$
x_k(t)=\int_0^t\arctan(ks)\frac{(t-s)^n}{n!}ds
$$
You can show that
$$
|x_k^{(r)}(t)-x_l^{(r)}(t)|\leq M\int_0^{|t|}|\arctan (ks)-\arctan(ls)|ds\tag{1}
$$
for any $r=0,\ldots,n$ $k,l\in \mathbb{N}$ and $t\in[-1,1]$. Here
$$
M=\max\limits_{r=0,\ldots,n}\max\limits_{(s,t)\in[-1,1]^2}\frac{d}{dt}\frac{(t-s)^m}{m!}
$$
Using $(1)$ you can show that $\{x_n:n\in\mathbb{N}\}\subset C^n([-1,1])$ is a Cauchy sequence. It is not convergent by arguments given above.
Comment: Thanks for this first answer. This works great for any bounded interval. But i guess, the statement's also true for I=R. But then we dont have $(y_k)_{k\in\mathbb{N}} \subset C^k_n$ since $\|y_k\|_{n,\infty}$ is unbounded. Do you (or anyone else) have any idea how to fix this? - I actually dont have. I also tried to approximate $|x|$ by polynomials and cut it by a constant, but its hard to get this k-times differentiable (or bounded when I integrate). The best thing was of course a sequence in $C^\infty$ but i fear this is not possible.
Comment: In this case, I think, you need to apply the same prcedure to the sequence $y_k(t)=\exp(-k|t|)$. But I have not checked this.
Comment: This is not in $C^k_n$ for $k\geq1$ since its not differentiable in 0 - or am i doing wrong?
Comment: This is $y_k$. Apply to them procedure describeed above to get the desired sequence $x_k$
Comment: @mathmatters have you checked my hypothesis?
Comment: sorry - I tried but on my way I found the sequence $\frac{1}{\sqrt{x^2+1/n}}$ which is $C^\infty$ and converges to a not differentiable function - but thanks for your help!

$C^k_b$ with sup-norm not complete


Alter field content inside modules hook_node_view

Question: I'd like to alter, but not save, a fields output.  I've got a MODULE_node_view already setup.  Is there a way to do this?  I don't want to save the output permanently.
Answer: In HOOK_node_view() you can alter your fields like this:
function MODULE_node_view($node, $view_mode, $langcode) {
  //be sure to be in full page mode, but you can also user 'teaser'
  if ($view_mode == 'full' && node_is_page($node)) {
    //kpr($node); => use devel module and kpr() to inspect your node.
    //Change the title of the node
    $node->title = 'New title';

    //Change the "text" field
    $lang = field_language('node', $node, 'field_text');
    $node->field_text[$lang][0]['value'] = 'New field text value';

    //Change the "body" field which has a slightly different syntax
    $lang = field_language('node', $node, 'body');
    $node->body[$lang][0]['value'] = 'New body value';
  }
}

Note the usage of field_language() to retrieve the correct value for each field.
Comment: This does not work if you make $node->title = 'New title'; it does not change...
Answer: You can print the $node array and then access your field through index.
print_r($node);

Comment: Gee, thanks.  But I need to render the altered field WITHOUT saving it or attaching it to the node.  Any ideas?


In panels, does the right region get its argument from the left?

Question: I plan to have a panel page with two regions:
- on left, a panel of one author
- on right, a view of all the stories written by that author.
I don't yet know how the user arrives at this page (my understanding of panels is still in its infancy).
Does the right panel get its argument from the left panel? Or somewhere else?
If the left panel node has Node ID 62, does the view (right panel) need to be sorted in node ID order (with a contextual filter)?
Answer: It gets its context from the Contexts that you load into the Page on the Page Manager part of the dialog. It looks like this:

In this case I started to override the node view page, so it comes with the initial context of the node (nid, date published etc).
I then added a relationship on that same page of User to bring in the related Author's User data. After I saved it brought that context in for me and it looks like this:

Note the User from Node part.
I can continue to bring in context connected to the node, or now also connected to the user.
To embed a view in a Panels pane you need to first install Views content panes which is part of CTools. You then add a Content Pane via the Views UI to the view. You set the Contextual argument and in ADDITION you need to click on argument input (middle part of the Views UI) to tell the view where the context is coming from. This dialog will then bring up your contextual argument that you added, and a selection for you to specify where or what to get the context from. For the most part you will select From Context and for a node select Node, Content id. Now back in your Panels UI you can add a view as content. You select View panes (though this is just a default that is specified on the view itself and you can alter it per view), select your view, and it will pick up the contextual filter and the type of context you specified for it, and automatically make a selection of contexts that match that you have enabled in Page Manager.
So in order to decide what panel needs what context (or arguments) you need to first establish how the content in the specific panel is related to the type of page your are creating a variant for. I your case of author and stories, you can start with a user page and you want to end with stories on that user page written by the user. Your initial context will be User. No need to bring in extra context as your view for the right panel will take a uid contextual filter. Your right panel will embed a Views content pane with a contextual argument of uid that you connect as the author of the nodes. You will specify in that view that you want the argument input to be of User type from Context, and in your panel, when you add the content pane it will allow you to link it to the user context that is available.
Comment: Thanks. I have Chaos tools. I see the ability to add **Content pane** from the View, but I have no idea what to do with it! I see the  **Argument input**. I'll study what you've written for a bit. Truly, I'm very grateful that you've taken the time to point me in the right direction. :)


How to hide all tabs (local tasks) except the user account tabs?

Question: I want to hide all tabs (local tasks) for non-admin users except the tabs on the user account page (for example, I want to hide tabs on nodes of all content types).
To hide the tabs, I added a check for admin permission in my theme template: templates/menu/menu-local-tasks.html.twig
{% if user.hasPermission('administer nodes') %}
  {% if primary %}

{{ 'Primary tabs'|t }}

{{ primary }}

  {% endif %}
  {% if secondary %}

{{ 'Secondary tabs'|t }}

{{ secondary }}

  {% endif %}
{% endif %}

This works, but it hides the tabs on the user account page as well.
I tried to find a more specific template of menu-local-tasks for the user account. I turned on twig debugging, but these were the suggestions:

All of these affect the entire site; there is no way to target just the user account local tasks.
Is there a way to do this with theme templates?  I chose this approach rather than trying to unset the local tasks in a hook because in a template you can do it in just a line or two of code.
Answer: I wouldn't recommend not doing this by code, this can be achieved using built-in configuration settings, by using a second block with proper rules. Try this:

Go to Structure > Block layout
Select your theme
Place a second tabs block where-ever you want it
Limit the visibility on the block fitting your requirements

Most likely limit Pages to something like user/*
and by Roles, e.g. Authenticated user
(remember that administrators are authenticated users too, so you might need more specific roles to to prevent admins seeing tabs block twice; or add the "hide"-option on user-pages for the first, original tabs block )
Comment: I totally forgot that tabs were a block in D8.  Best way to configure the `Pages` is to use `/user/*` on the "user tabs" and `NOT /user/*` on the "original tabs"; that way, you don't need to set roles.
Comment: Also note I had to change the theme file name to be more specific: `block--mytheme-local-tasks.html.twig`


Margin on custom TextView

Question: I checked a lot of answers, but none helped so far.
I'm trying to extend android's TextView and set the margin of this custom view inside the code, as I'm going to instantiate them on button presses and similar things. It is added to a LinearLayout. That's about what I got:
public class ResultsView extends TextView {
    public ResultsView(Context context) {
        super(context);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layout.setMargins(15, 15, 15, 15);
        setLayoutParams(layout);
    }
}

No sign of margin anywhere.
EDIT: I might want to add, if I assign a margin value in xml, it does work.
Answer: I think the issue is, that by the time you are trying to add the margin the layoutparams are not set yet, why dont you try overriding this method in your ResultsView class:
       protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
            int margin = 15;
            margins.topMargin = margin;
            margins.bottomMargin = margin;
            margins.leftMargin = margin;
            margins.rightMargin = margin;
            setLayoutParams(margins);
        };

And remove the code you have in the Constructor, this way the margin will be applied until we are sure we have a layout object for the view, hope this helps
Regards!
Comment: I think you could probably get away with just modifying the dimensions passed into onLayout() (e.g. left += leftMargin, right -= rightMargin, top += topMargin, bottom -= bottomMargin, super.onLayout(changed, left, top, right, bottom));
Comment: Yay! That really did it, thanks! I actually tried something similar before, but with onFinishInflate, which did not work. Do you know how well this is on the performance side? Should I better add a boolean to check whether we've set it once already?
Comment: I don't think is such a huge performing impact, but if you are concern about it, you can add the flag to do it only once if you want...
Comment: Does not work with LinearLayout. Probably cuz you never called super.onLayout
Comment: @MartinCazares hi i am getting margins as null...any suggestions?
Comment: `onLayout()` is supposed to set the layout for the view's children not to change the view's own layout. So, this approach will trigger an unnecessary run of the `onLayout` chain and may cause screen flickering (at least on Android 12). It is better to set the margins during `setLayoutParams()` which will be called during view inflation. See my answer.
Answer: As @MartinCazares pointed out, the issue is that the layout params are not available in the constructor method and will be overwritten during View inflation. However, it is better to set the margins in setLayoutParams() which will be called during View inflation, instead of in onLayout(). The latter is supposed to set the layout of the view's children and not change the layout of the view itself. So, changing the layout params there caused screen flickering in my case on Android 12.
My solution:
private boolean hasLeftMargin = false;
private boolean hasRightMargin = false;
private boolean hasTopMargin = false;
private boolean hasBottomMargin = false;

public MyView(@NonNull Context context, @Nullable AttributeSet attrs) {
    // Receive styled attributes
    TypedArray arr = context.obtainStyledAttributes(attrs, new int[] {
            android.R.attr.layout_margin,
            android.R.attr.layout_marginLeft, android.R.attr.layout_marginTop,
            android.R.attr.layout_marginRight, android.R.attr.layout_marginBottom,
            android.R.attr.layout_marginStart, android.R.attr.layout_marginEnd});

    // Check whether margin are assigned in xml (by index of int array above)
    hasLeftMargin = arr.hasValue(0) || arr.hasValue(1) || arr.hasValue(5);
    hasRightMargin = arr.hasValue(0) || arr.hasValue(3) || arr.hasValue(6);
    hasTopMargin = arr.hasValue(0) || arr.hasValue(2);
    hasBottomMargin = arr.hasValue(0) || arr.hasValue(4);
    arr.recycle();
}

@Override
public void setLayoutParams(ViewGroup.LayoutParams params) {
    if (params instanceof MarginLayoutParams) {
        MarginLayoutParams p = (MarginLayoutParams) params;
        if (!hasLeftMargin && p.leftMargin <= 0) p.leftMargin = sideMargin;
        if (!hasRightMargin && p.rightMargin <= 0) p.rightMargin = sideMargin;
        if (!hasTopMargin && p.topMargin <= 0) p.topMargin = verticalMargin;
        if (!hasBottomMargin && p.bottomMargin <= 0) p.bottomMargin = verticalMargin;
    }
    super.setLayoutParams(params);
}

Answer: You now need to add this view to the layout which is currently being displayed. You are missing the next step.
So now you need something like :
    currentlayout.addview(View);

Comment: It is added in XML. I can see the textviews in my LinearLayout, but they have no margin.

Margin on custom TextView


error: no matching function for call to 'std::optional::optional(smoltcp::Buffer&)'

Question: I am trying to make a function that returns an std::optional to Buffer:
std::optional<Buffer> receive(SmolSocket smolSocket)
{
   //...
   return std::optional<Buffer>(buffer);
}

Where Buffer is simply
struct Buffer
{
public:
   std::unique_ptr<uint8_t[]> data;
   size_t len = 0;
   bool empty = false;

   Buffer(CBuffer cBuffer)
   {
      data = std::unique_ptr<uint8_t[]>(cBuffer.data);
      len = cBuffer.len;
   }

   Buffer(bool empty)
   {
      data = std::unique_ptr<uint8_t[]>(nullptr);
      this->len = 0;
      this->empty = empty;
   }

   uint8_t* getData()
   {
      return data.get();
   }
};

But I am getting lots of errors:
/workspaces/libopenvpnclient/src/libopenvpn/../../smoltcp_cpp_interface/src/virtual_tun/interface.h:283:52: error: no matching function for call to 'std::optional<smoltcp::Buffer>::optional(smoltcp::Buffer&)'
  283 |                 return std::optional<Buffer>(buffer);

/usr/include/c++/9/optional:760:2: note: candidate: 'template<class ... _Args, typename std::enable_if<__and_v<std::is_constructible<smoltcp::Buffer, _Args&& ...> >, bool>::type <anonymous> > constexpr std::optional<_Tp>::optional(std::in_place_t, _Args&& ...)'
  760 |  optional(in_place_t, _Args&&... __args)
      |  ^~~~~~~~
/usr/include/c++/9/optional:760:2: note:   template argument deduction/substitution failed:
/usr/include/c++/9/optional:758:56: error: no type named 'type' in 'struct std::enable_if<false, bool>'
  758 |         _Requires<is_constructible<_Tp, _Args&&...>> = false>

note:   'smoltcp::Buffer' is not derived from 'std::optional<_Tp>'
  283 |                 return std::optional<Buffer>(buffer);

I have used std::optional in other situations and I can not see what is the problem here.
I also tried using return std::optional<Buffer>{buffer};.
Answer: To be short: You should add copy- or move-constructor to Buffer.
More details:
You have Buffer object and need to create another Buffer (in std::optional), but there is no constructor in Buffer which can accept parameters you're passing. Compiler doesn't generate default copy/move-constructors, because you declared custom one. So, you should construct std::optional<Buffer> from bool, from CBuffer or add another one with const Buffer& or Buffer&&.
Answer: The problem is, in order to do
std::optional<Buffer>(buffer);

you need a copy-or-move constructor. When you provide a parameterized constructor (i.e. Buffer(CBuffer cBuffer)), the compiler will not generate both of them. So you need to explicitly provide them.
However, in your case, you have one more issue. The member data is non-copyable(i.e. std::unique_ptr<uint8_t[]>), meaning only move constructor is that you can provide.
Therefore provide the move-constructor
struct Buffer
{
public:
   Buffer(Buffer&& rhs)
      : data{ std::move(rhs.data) }
      , len{rhs.len}
   {}
   // ... other code
};

and move the buffer in the function:
std::optional<Buffer> receive()
{
   // ...
   return std::optional<Buffer>(std::move(buffer));
}

(See a minimal example demo)


Popover dentro de uma tabela não funciona

Question: Estou tentando colocar um popover dentro de uma linha de uma tabela que é montada dinamicamente de acordo com os dados vindo da base de dados. Testei fora da tabela e funcionou, mas dentro da linha da tabela não.
meu Js está assim
 $(document).ready(function(){
            $('[data-toggle="popover"]').popover();
        });

meu html está assim

                      {{dis.idDistrito}}
                      {{dis.nome}}
                      {{dis.codigoDne}}
                     Toggle popover

Comment: Veja no console se está retornando erro, mais creio que seja a falta do `jQuery` ... ``
Comment: eu testei fora do `` e funcionou
Comment: Pode ser possível que esteja acontecendo algum conflito, algo do tipo, veja no console, porque eu testei aqui e funciona.
Answer: O problema está apenas no apontamento, seu jQuery não está disparando o popover.
Adicione um atributo trigger ao  dentro de :
Toggle popover

E faça uma leve alterada no evento, idicando pra ele adicionar o popover no momento do hover:
$(document).ready(function(){
    $('[data-toggle="popover"').on('mouseover',function(){
        $(this).popover();
    })
});

Exemplo funcional no fiddle: https://jsfiddle.net/AnthraxisBR/nerpsqt7/2/
OBS: inclua o jQuery sempre antes do arquivo js do bootstrap.
Comment: Creio que não seja isso, pois ele disse que colocou fora do `td` e funcionou
Comment: É isso mesmo, ele não tem trigger, por mais que instancie a popover, não vai disparar.
Comment: Veja aqui que eu testei no [jsbin](http://jsbin.com/gecorub/edit?html,output) no caso aqui, que esta igual ao dele tem que clicar pra aparecer. Então a pergunta não está clara.


Questions on Fundamentals of Musical Composition by Arnold Schoenberg

Question: I am reading this book and I need help to understand this line on page 4 (Construction of themes):
"Nearly always the phrase crosses the metrical subdivisions, rather than filling the measures completely."
Are metrical subdivisions each beat of a measure? Say a quarter note in a 4/4 meter?
I am trying to figure out what he means by contrasting these 2 ideas.
Thanks!
Comment: The wording is very ambiguous, maybe because Schoenberg wrote the book in English which was his second language. He never learned to speak it really well.
Answer: The "metrical subdivisions" he's speaking of are whole measures. He's saying that phrases usually cross barlines and end mid-measure.
Answer:
...Are metrical subdivisions each beat of a measure?

That is my understanding of the text.
But the wording is really awkward. The only thing crossed would be barlines. I supposed you can say a dividing line between beats is crossed, but that would be true of anything longer than one beat! Something like "phrases may start or end with incomplete measures" would have been more direct IMO. That is the point I get from the text and especially from comparing the text to the musical illustrations in ex.1 & ex.2.
Answer: He's basically saying that most phrases are "irregular" or, better, they're not that round as we may think when study this set of rules; you'll see what I mean when you get on the part of period/sentence/hybrid structures. We first see these 8 bar patterns and may think "a phrase must start on downbeat measure 1 and end upbeat measure x", but that ain't what's really happening in real music most of time.
A great variety of phrases begins in anacrusis and ends mid-measure - or may a phrase begin, end or join another by some techniques: elision, juxtaposition, omitting a beat or parts et cetera.
Answer: Schoenberg could have said even more clearly: most phrases and motifs start with an up-beat (and have their measure crossing ending, logically).
Answer: Metrical Subdivisions are the "and"s of a beat (meter, metricAL. see?).
Like this: 1 & 2 & 3 & 4 & | 1 & 2 & 3 & 4 & |
Each measure is divided into beats. Each beat is subdivided into subdivisions.
In compound meter, each beat has 3 subdivisions: 1 2 3 4 5 6, 1 2 3 4 5 6,
So, I believe he is saying that the specific theme in question has a phrase that doesn't fit the subdivisions quite as well as, say, a contrived example tune from a textbook might.


Delete dictionary keys that are out of bounds (python)

Question: If you have a dictionary of integers:
d = {
  1:[0],
  2:[1],
  3:[0,1,2,3,4],
  4:[0],
  5:[1],
  6:[0,1,2,3,4],
  11:[0],
  22:[1],
  33:[0,1,2,3,4],
  44:[0],
  55:[1],
  66:[0,1,2,3,4]
}

You want to:

Validate that the keys are between 0 and 25.
Delete any keys that are outside of the range as they are not valid and will ruin the data set.

Dictionary keys are not naturally sorted.
Given, how would validate that your keys are in the required range?
My try:
for x,y in d.items():
    if x<0 or x>25:
         del d[x]

When ran I get the error:
RuntimeError: dictionary changed size during iteration

How would I compensate for this?
Answer: In your example, you are mutating the d while looping through it. This is bad.
The easiest way to do this if you don't need to change the original d is to use a dictionary comprehension:
d = {k: v for k, v in d.items() if 0 <= k <= 25}

Comment: don't you mean d.items()?
Comment: @TheClonerx Yeah I just realized that :P
Answer: If you want to delete keys while iterating, you need to iterate over a copy instead and pop keys that don't hold to your condition:
d = {1:[0], 2:[1], 3:[0,1,2,3,4], 4:[0], 5:[1], 6:[0,1,2,3,4], 11:[0], 22:[1], 33:[0,1,2,3,4], 44:[0], 55:[1], 66:[0,1,2,3,4]}

for k in d.copy(): # or list(d)
    if not 0 <= k <= 25:
        d.pop(k) # or del d[k]

Which Outputs:
{1: [0], 2: [1], 3: [0, 1, 2, 3, 4], 4: [0], 5: [1], 6: [0, 1, 2, 3, 4], 11: [0], 22: [1]}

As others have shown, reconstructing a new dictionary is always an easy way around this.
You can use a basic dict comprehension here:
{k: d[k] for k in d if 0 <= k <= 25}

Or even a functional approach with filter():
dict(filter(lambda x: 0 <= x[0] <= 25, d.items()))

Answer: You can use a dictionary comprehension:
d = { 1:[0], 2:[1], 3:[0,1,2,3,4], 4:[0], 5:[1], 6:[0,1,2,3,4], 11:[0], 22:[1], 33:[0,1,2,3,4], 44:[0], 55:[1], 66:[0,1,2,3,4] }
new_d = {a:b for a, b in d.items() if a <= 25 and a >= 0}

Output:
{1: [0], 2: [1], 3: [0, 1, 2, 3, 4], 4: [0], 5: [1], 6: [0, 1, 2, 3, 4], 11: [0], 22: [1]}


(Scrapy) How to get the CSS rule for a HTML element?

Question: I am building a crawler using Scrapy. I need to get the font-family assigned to a particular HTML element.
Let's say there is a css file, styles.css, which contains the following:
p {
    font-family: "Times New Roman", Georgia, Serif;
}

And in the HTML page there is text as follows:

Hello how are you?

Its easy for me to extract the text using Scrapy, however I would also like to know the font-family applied to Hello how are you?
I am hoping it is simply a case of (imaginary XPATH) /p[font-family] or something like that.
Do you know how I can do this?
Thanks for your thoughts.
Comment: Personally I don't think that's something that could be handled by Scrapy :( You might need to look into something like an HTML renderer.
Comment: You can have a look at https://pythonhosted.org/tinycss/
Answer: You need to download and parse css seperately. For css parsing you can use tinycss or even regex:
import tinycss
class MySpider(Spider):
    name='myspider'
    start_urls = [
        'http://some.url.com'
    ]
    css_rules = {}

def parse(self, response):
    # find css url and parse it
    css_url = response.xpath("").extract_first()
    yield Request(css_url, self.parse_css)

def parse_css(self, response):
    parser = tinycss.make_parser()
    stylesheet = parser.parse_stylesheet(response.body)
    for rule in stylesheet.rules:
        if not getattr(rule, 'selector'):
            continue
        path = rule.selector.as_css()
        css =  [d.value.as_css() for d in rule.declarations]
        self.css_rules[path] = css

Now you have a dictionary with css paths and their attributes that you can use later in your spider request chain to assign some values:
def parse_item(self, response):
    item = {}
    item['name'] = response.css('div.name').extract_first()
    name_css = []
    for k,v in css_rules.items():
        if 'div' in k and '.name' in k:
            name_css.append(v)
    item['name_css'] = name_css

Comment: Thanks for your reply. If the page has multiple CSS files (e.g. Bootstrap, Normalize, etc.) and these files (for example) contain multiple styling for p elements, would your code select the actual p CSS styling being used by the p elements on the page, or would it also select the unused p CSS stylings in the CSS files? As an example, I could create many CSS files and have multiple style entries for p in them, but the HTML on my page might only use one of the p styles due to nesting or some other CSS rule.
Comment: AFAIK html has to specify what css it's using, so you can just select that and parse it. I.e. for stack overflow you can find it via `response.xpath("//link[@rel='stylesheet']/@href")` If it has multiple css files than it will use multiple css files, so you need to parse all of them to generate yourself a dictionary or a tree of sorts.
Comment: Thanks. I need to think about your solution to ensure I understand it. I will get back to you either way!


how to prevent access to admin urls in Django?

Question: Django gives admin url automatically, such as www.example.com/admin.
I do not want any outside visitors to access this url. This should be accessed only with in the host and allowed IP address.
If I try to access to https://instagram.com/admin/ (which is built using Django),it gives 404 page not Found error
How can I achieve the same behavior?
what is the preferred and right way to do it?
I host my webservice inwebfaction and allowing IP address of host means other webfaction account-holders might be able to access the admin URL which I dont want to. Looking for a neat and simple way
Thanks:
PS: I see a similar question posted here but that is with respect to PHP. I am wondering how can I acheive the same using Django?
Comment: You could build a decorator around the admin URLs -- either manually by reproducing the URLs or perhaps programmatically using something like this: http://stackoverflow.com/a/18411661/1345536.  The decorator could then check for whitelisted IP addresses or return a 404.
Answer: One common method, which is advocated by Two Scoops of Django, is to change your admin url. Thus, rather than logging into your admin at www.example.com/admin/, you would log in at www.example.com/supers3cret4dm1n/ or something  that you've set.  This is likely what Instagram has done in your example.
Example code:
urlpatterns = patterns(''
    ...
    url(r'^supers3cret4dm1n/', include(admin.site.urls)), # Change the pattern to whatever you want here
    ...
)

Note that this doesn't make it accessible from only one IP address, but it does effectively 'hide' your admin login page.
Another tip is to use the django-admin-honeypot package. This sets up a fake admin page at www.example.com/admin while having your real admin page at another site that you've set. Then, django-admin-honeypot will alert you if anyone tries to hack your admin at the fake admin site.
EDIT:
If you're dead-set on restricting by IP address, here's a SO question and answer showing how to do it with nginx. I imagine it'd be similar with others.
Comment: But that still doesnt stop bots from crawling the URL. And if you dissallow that in robots.txt, then anyone who looks at robots file can find the URL.
Comment: what you suggested seems reasonable rather than playing around with IP address
Answer: simply you can treat the admin path as a secret, so set it as an environment variable in your system and then retrieve it (good approach if your source code is public).
ADMIN_URL_PATH = os.getenv('DJANGO_ADMIN_PATH')

urlpatterns = [
    ...
    path(ADMIN_URL_PATH, admin.site.urls)
    ...
]


Prepopulating userform failed gives "type mismatch" error

Question: So I have a Userform that can either take information from the excel sheet and prepopulate the Userform or output Userform information back to the excel sheet. The issue took place when prepopulating the Userform from excel data.

As seen in the picture above, it's the Userform itself and after clicking on Prepopulate option I get the Run-time error "13": Type Mismatch. So when I debugged it, it went to line 5 line seen below which corresponds to the Prepopulate section of  the code.
    With Sheets("DoNotPrint - Setup")
    If .Range("H28").value = "Chief Process Safety" Then
        ToggleButton1 = True
     Else
     If .Range("H28").value = "Senior Process Safety" Or "Interm Process Safety" Or "" Then
        ToggleButton1 = False
    End If
    End If
End With

The picture above is what it looks like on excel where the user inputs the fields and the last field is a drop down list to choose 1 from the three options that is linked to the piece of code within the Userform as shown above.
So I am wondering to get rid of this error do I have to assign some kind of a variable to the range possibly?
Comment: You have to repeat the `.Range("H28").Value` for each condition in the `If` statement: `If .Range("H28").Value = "Senior Process Safety" Or .Range("H28").Value = "Interm Process Safety" Or .Range("H28").Value = "" Then`.
Comment: This line? `If .Range("H28").value = "Senior Process Safety" Or "Interm Process Safety" Or "" Then`
Comment: @DavidZemens yep
Answer: Better (for legibility IMO) to use a Select Case switch in this instance:
With Sheets("DoNotPrint - Setup")
Select Case .Range("H28").Value
    Case "Chief Process Safety"
        ToggleButton1 = True
    Case "Senior Process Safety", "Interm Process Safety", ""
        ToggleButton1 = False
End Select
End With

Alternatively, you need to properly construct your boolean expression:
If .Range("H28").value = "Senior Process Safety" Or _
   .Range("H28").value = "Interm Process Safety" Or _
   .Range("H28").value = "" Then

Because as currently constructed, your If statement is comparing a boolean with a string(s) which results in the Mismatch Error. Breaking it down, it is this:
If (.Range("H28").Value = "Senior Process Safety") Or "Interim Process Safety" Or "" Then

And because you can't compare these types, If True Or "foo" raises a mismatch error just as your code will raise the mismatch error.
Comment: There was an syntax error with the first option so I went with the second option and it worked flawlessly.
Comment: The syntax error is the extra `Then` at the end of the second `Case` - sure you know that but pointing it out to @GoldFusion.


postfix dovecot disable lmtp

Question: I have 3 servers. 1 MX server with postfix and 2 dovecot servers. MX server receive emails and then serve them through LMTP to specific dovecot server. All mailboxes from same domain are on same server.
Is there any way to temporary disable LMTP and deffer messages for specific domain? For example in case of migrating domains between dovecot servers.
On postfix I use transport_maps
transport_maps = mysql:/etc/postfix/sql/transport.cf

With this query
 query = SELECT concat('lmtp:',servers.address, ':24') FROM servers
         JOIN domains ON (domains.server_id=servers.ID)
         WHERE domains.name LIKE SUBSTRING_INDEX("%s", "@", -1)
         LIMIT 1;

Dovecot is listening for lmtp on port 24, user_query in dovecot is
user_query = SELECT 1
        FROM domains
        JOIN mailboxes ON (domains.ID=mailboxes.domain_id)
        WHERE
            domains.name LIKE '%d'
            AND mailboxes.name LIKE '%n'
            AND domains.server_id='X'
        LIMIT 1;

I checked dovecot user_query man page, but there is nothing what can help me (http://wiki2.dovecot.org/UserDatabase and http://wiki2.dovecot.org/UserDatabase/ExtraFields)
I have tried to add condition to user_query "AND domains.enable_lmtp = 1", but then postfix server successfully passed email to dovecot server and dovecot server returned to sender error "User doesn't exists".
Next I tried to add same condition to server query on postfix server. Query returned nothing (nowhere to transport), email was deleted and in log said
postfix/virtual[724]: fatal: bad string length 0 < 1: virtual_mailbox_base =
postfix/master[32263]: warning: process /usr/libexec/postfix/virtual pid 724 exit status 1
postfix postfix/master[32263]: warning: /usr/libexec/postfix/virtual: bad command startup -- throttling

I hoped that postfix would put messages into deferred queue, but it didn't. Messages were deleted. Same think happened when I changed transport server to non exist address.
So am I doing something wrong? Is there any way to solve my problem?
My postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
config_directory = /etc/postfix
content_filter = smtp-amavis:[127.0.0.1]:10024
mydestination = $myhostname, localhost.$mydomain, localhost
smtpd_client_restrictions = permit_mynetworks, reject_unknown_client_hostname, reject_unknown_reverse_client_hostname
smtpd_helo_restrictions = permit_mynetworks, reject_invalid_hostname, reject_non_fqdn_hostname,
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, reject_unauth_destination, reject_unknown_recipient_domain, reject_non_fqdn_recipient, check_policy_service unix:/var/spool/postfix/postgrey/socket, check_policy_service unix:private/recipient_restrictions
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, defer_unauth_destination
smtpd_sender_restrictions = permit_mynetworks, reject_non_fqdn_sender, reject_unknown_sender_domain
smtpd_tls_cert_file = /etc/postfix/smtpd.cert
smtpd_tls_key_file = /etc/postfix/smtpd.key
smtpd_tls_loglevel = 0
smtpd_tls_received_header = yes
smtpd_use_tls = yes
transport_maps = mysql:/etc/postfix/sql/transport.cf
unknown_local_recipient_reject_code = 550
virtual_mailbox_domains = mysql:/etc/postfix/sql/mailbox_domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/sql/mailbox_maps.cf

Comment: So, you want your postfix requeue the message until you enable the LMTP again?
Comment: Can you post the output of `postconf -n`?
Comment: @masegaloeh ok, edited
Comment: Yes, thats exactly what I want, but only for specific domain (domain which has enable_lmtp = 0 in sql table)
Answer: This problem can be tackled either by postfix or dovecot.

In dovecot, you should set the LMTP service to reply with temporary reject 4XX (for your "special" domain) when postfix send email.
In postfix, you need to configure postfix so it must defer the email if the recipient domain match your "special" domain.

Option 1 isn't possible because -unlike postfix- dovecot can't be configured to issue the tempfail error to particular domain. See the discussion on [Dovecot] Configuration of LMTP Reject Code.
For option 2, you need to transport the "special" domain to non-working address, for example you can deliver it to closed port in your LMTP server. For that, you need second transport_maps with query like this
#/etc/postfix/sql/transport-defer.cf

query = SELECT concat('lmtp:',servers.address, ':2424') FROM servers
        JOIN domains ON (domains.server_id=servers.ID)
        WHERE domains.name LIKE SUBSTRING_INDEX("%s", "@", -1)
        AND domains.enable_lmtp != 1
        LIMIT 1;

In above query, I use port 2424 as closed port to keep postfix defer the message.
Then put it next to  mysql:/etc/postfix/sql/transport.cf
#main.cf
transport_maps = mysql:/etc/postfix/sql/transport.cf mysql:/etc/postfix/sql/transport-defer.cf

PS: Because you have no mailbox in postfix server then it would be preferable to use relay_domains and relay_recipient_maps to replace virtual_mailbox_domains and virtual_mailbox_maps. See relay domain class documentation.

postfix dovecot disable lmtp


Services 3 File upload, create/return image styles

Question: Ahoy all!
So, long story short, I'm uploading files to drupal through services from an angular app, and getting a response/url/etc no problem. My question is, how do I enable image styles to be created on REST upload from services? I'm receiving an empty response in the image_styles array. I am assuming it likely isn't something I need to add into the POST request, but happy to add POST request code if needed.
I am coming up a little short on my google-fu on this one, and any help appreciated!
Answer: the image created with the style when you request a page displaying that image_style So you have to call it in code.
The default generation method only creates images when they are requested by a user's browser.
image_style_url  Returns the URL for an image derivative given a style and image path
code sample :
<code>// $file object from file_load($fid)
image_style_url('style name', $file->uri)
</code>


Why does this Roman numeral chord have a ♯ prefix?

Question: These are the chords for some A minor scales:

For melodic minor, why does the F♯o diminished chord have a '♯' in front of the Roman numeral, and the G♯o diminished chord does not?
Comment: In much music, the minor mode is treated as the union of these scales. The minor chord on step 5 is common though mostly as a key area. Often the v-i pattern will be used at non-final cadential points, reserving the V-i for the final cadence. The III+ is rare as is shown. The major IV sometimes occurs as it's used both for "color" and for giving a "modal" feel. Both ii and II (and II7) occur, especially at final cadences. My point is that all these need practice.
Answer: When analyzing a piece in a minor key, the VI chord is presumed to be on the 6 native to that key (signature), while the vii is presumed to be raised. Since the 6 in melodic minor is raised, its triad requires a # to differentiate it and make clear it's the raised sixth. While vii is presumed raised, one sometimes sees bVII when appropriate, for clarity.
Answer: A sharp or flat precedes a Roman numeral if the chord root differs from the key signature.
That system is consistent except for chord roots of the seventh scale degree. Unfortunately, that is a mix of various assumptions.
If upper and lower case letters are being used, upper case VII is assumed to be a chord root on the subtonic, the scale degree one whole step below the tonic, and the chord quality will be a major triad. If the lower case vii is used, the chord root is assumed to be a leading tone one half step below the tonic, and the chord quality can either be assumed a diminished triad, or the o diminished symbol should ideally be given as viio.
While not part of your question, I dispute the "rare" label on the minor v and the augmented III+. Minor v is actually common. III+ is also fairly common, but you might be able to analyze that chord as some kind of non-chord tone action involving a dominant chord. Ex. root E with a G♯ and above a C moving down to B. E G♯ C being an augmented chord, which has some ambiguity regarding the root, or it's a dominant chord E G♯ with C and appoggiatura resolving down to B.
What the charts in your example do not show, but are probably more common uses of sharp and flat prefixes to Roman numerals are the neapolitan chord, which could be labelled as ♭II and borrowed chords. For example, in C major the submediant triad is labelled  C:vi, but borrowed from the minor the submediant will be labelled C:♭VI.


How can I add markup above the table in a custom module?

Question: I am working on a Drupal 8 custom module which renders pages as shown in the following image.

So far, I am able to build the table and my code is the following.
  public function dexp_layerslider_list() {
    $header = [
        'ID',
        'Name',
        'Action',
    ] ;
    $results = db_select('{dexp_layerslider}', 'd')->fields('d', [
        'id',
        'name',
    ])->execute();
    foreach ($results as $row) {
        $url = Url::fromUserInput("/admin/dexp_layerslider/". $row->id . "/edit");
        $row->name = (Link::fromTextAndUrl($row->name, $url));
        $editslides = Url::fromUserInput('/admin/dexp_layerslider/'.$row->id.'/editslides');
        $editslides_link = (Link::fromTextAndUrl('Edit slides', $editslides))->toString();
        $exportslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/export');
        $exportslides_link =  (Link::fromTextAndUrl('Export slides', $exportslides))->toString();
        $deleteslides = Url::fromUserInput('/admin/dexp_layerslider/'. $row->id . '/delete');
        $deleteslides_link =  (Link::fromTextAndUrl('Delete', $deleteslides))->toString();
     $tmp =  [
            '#type' => 'inline_template',
             '#template' => '{{ link1 |raw }}, {{ link2 | raw }}, {{ link3 | raw}}',
                '#context' => [
                         'link1' => $editslides_link->getGeneratedLink(),
                         'link2' => $exportslides_link->getGeneratedLink(),
                            'link3' => $deleteslides_link->getGeneratedLink(),
                            ]
                    ];
        // Row with attributes on the row and some of its cells.
     $rows[] = array(
            'data' => array($row->id,$row->name,$tmp )
                );
        }
     $table = array(
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#sticky' => FALSE,
        '#empty' => t('No slider created yet.'),
         );
        for($i= 0; $i
            $table['#rows'][$i]['data'][2] = $tmp;
        }
    return $table;
 }

How do I add a "Add slide" and "Export slide" links?
Answer: You have multiple solutions to achieve what you want

Using #prefix
 $table = array(
  '#prefix'=> '
my link
',
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

A better way to do this is
 $table = array(
  'links' => [
     '#type'=> 'container'
     'link_one'=> [
        '#type' => 'link',
        '#title' => $this->t('Add slide'),
        '#url' => Url::fromRoute('my_route'),
      ],
   ],
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#sticky' => FALSE,
  '#empty' => t('No slider created yet.'),
 );
for($i= 0; $i
    $table['#rows'][$i]['data'][2] = $tmp;
}

Add module definied actions: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-actions
Comment: Third option was best , second option appends the link at bottom of table.
Comment: you can add a #weight to put it above the table


Retrofit 2.0: How to map objects with different type

Question: This is my sample JSON Response:
{
"success": true,
"details": {
    "banners": [
        {
            "banner_id": "1",
            "file_id": "368",
            "title": "INANG KALIKASAN'S BAD HAIR DAY",
            "description": "Et aeterno partiendo his, vim ponderum abhorreant et. Eum debet recusabo repudiandae in.",
            "created": "2018-03-09 07:56:04",
            "modified": "2018-04-02 09:59:54",
            "deleted": "",
            "file_name": "https://globegfs.imgix.net/uploads/2018-04-02/8a90371e9ad33cf06848b354b1fbd795.jpg",
            "orig_file_name": "hero-1.jpg"
        }
    ],
    "recent_books": [
        {
            "content_id": "353",
            "category_id": "24",
            "title": "One Hundred Fourth Symphony, in D-major",
            "author": "Franz Josef Haydn",
            "description": "The last of the 12 London Symphonies written by Franz Haydn. This ebook contains copies of the 4 movements in .mid format.",
            "tags": [
                {
                    "content_id": "353",
                    "tag_id": "14",
                    "created": "2018-04-27 15:57:46",
                    "tag_name": "Ray Collections"
                }
            ]
        }
    ],
    "classics": [
        {
            "content_id": "353",
            "category_id": "24",
            "title": "One Hundred Fourth Symphony, in D-major",
            "author": "Franz Josef Haydn",
            "description": "The last of the 12 London Symphonies written by Franz Haydn. This ebook contains copies of the 4 movements in .mid format.",
            "tags": [
                {
                    "content_id": "353",
                    "tag_id": "14",
                    "created": "2018-04-27 15:57:46",
                    "tag_name": "Ray Collections"
                }
            ]
        }
    ]
}

}
Only the banners object has a different list of contents. All the succeeding Json Elements will have the same contents but in a list, having its Json Node its actual title. How can I map this into a HashMap?
I figured it will look something like this:
private List<GFSBannerResponse> banners;
private List<HashMap<String, List<GFSContentResponse>>> featuredContent;

but I still don't have an idea on how to implement this. I am using Retrofit 2.0 and Gson.
Comment: you can use jsonschema to pojo which will manage your response and generate related model class.
Answer: I ended up implementing it this way:
@SerializedName("details")
@Expose
private JsonElement details;

I just used JsonParser to parse the content to a JsonElement. Stuck with GSON for all of this, although this wasn't the ideal implementation. Will try to implement a custom Deserializer in the future.