concise book on MDPs with stress on solving them using DP

Question: What is a good book for MDP with a stress on solving them using DP? However, the book should stress on the theorems and proofs and make a case for why DP is the most popular tool to solve MDPs.
I am not looking for an introductory book but a book that can stress on the maths behind MDP and why DP is used to solve it mostly?
Algorithms are not necessarily required in the book. If the book also addresses the question of developing algorithms that's a bonus.
One desired requirement is that the book be concise and to the point. It should try to be within 200 pages but still cover all the core technical details.
I am in interested in learning to write proofs for certain stochastic MDP results that i am working with.
Answer: This is not a whole book, but I recommend the chapter on controlled Markov chains in Kushner, Harold, and Paul G. Dupuis. Numerical methods for stochastic control problems in continuous time. Vol. 24. Springer Science & Business Media, 2013.
Another option is Puterman, Martin L. Markov decision processes: discrete stochastic dynamic programming. John Wiley & Sons, 2014, though I have not read it myself.
Comment: I have added another popular option above.
Comment: It surely covers the core concepts required but is there a more self-contained exposition?
Comment: @GoCodes For your intended use, I am seconding the recommendation for the Puterman book. It is a very comprehensive general reference, though not very concise at 600+ pages.
Answer: "Algorithms for Reinforcement Learning"  (concise)
Csaba Szepesvari
https://sites.ualberta.ca/~szepesva/RLBook.html
"Dynamic Programming and Optimal Control"  Dimitri P. Bertsekas
http://www.athenasc.com/dpbook.html


MySQL insert [Err] 1136 - Column count doesn't match value count at row 1

Question: It is too simple sql,but there is error.
The type of user_id is varchar,the type of times is also varchar.
insert into operationlog(user_id,times) VALUES('323423443' '2016-01-0415:');

Comment: you miss a `,` between the values: `VALUES('323423443',  '2016-01-0415:');`
Answer: As I can see, you are missing a comma in values brackets.
Answer: You missed comma between two string values while inserting:
insert into operationlog(user_id,times) VALUES('323423443','2016-01-0415:');
Comment: Do not answer with code only. Explain what you have changed and why.


How to obtain the statistical significance of a given community structure for a directed network?

Question: So, I have several directed (multi-edged) networks, and within them each node has been assigned to one of seven categories (based on some a priori circumstances). Each category should have a higher within-category interaction rate, but I want to test the statistical significance of this.
Since "a set of nodes, densely connected internally" is pretty much the definition of a community, I want to manually impose my community assignments on the nodes in the network and then test whether this assignment is statistically more "community-like" than a random assignment. In essence, my question is: "Is this given community structure statistically significant?"
I found this paper which seems to have a way of measuring the statistical significance of a single community group in the network, but it doesn't seem to apply to a given, entire community structure. I also found this baby, but it seems to only be focused on much smaller, local structures.
There's gotta be a way to do this for directed, multi-edged networks, I just can't seem to find any! (Additionally, I'll have to do this analysis in R, so mega-triple-extra bonus points if you know of an R package that already does this.)
Thanks in advance!
Answer: What you're looking for is the subject of this gem by Peel, Larremore and Clauset: The ground truth about metadata and community detection.  See the section where they introduce the blockmodel entropy significance test.  I dont know of an implementation in R, but Leto's original implementation is in matlab on his Github.
Comment: It seems that the significance test [BESTest](https://github.com/dblarremore/BESTest) takes an "NxN *undirected* network adjacency matrix. Code will check to ensure that the matrix is either symmetric or triangular."  This is still better than any other leads I have, but it looks like I'd have to lose the directed aspect of my networks.
Comment: Ok, sorry I missed that.  Its probably possible to generalize their method to directed stochastic block models.  I'll mess around with it over the next few days to see.


proper syntax for stylus mixin using transform translate() or other 2 part rules

Question: In stylus, when trying to make mixins with transform translate() - or any other multipart rules...
I get: "Maximum stylus call stack size exceeded at "
scale(n)
    transform scale(n)

scale()
    transform scale(arguments)

(tried a bunch of stuff...)
Here is an example CodePen
Answer: Yep, if you're trying to produce the value with the same function as the one you're calling, you should output it literally, like this:
scale(n)
  transform 'scale(%s)' % n

This way it would output the ident entity and won't call the scale function, so there won't be any infinite loops.
Answer: This is what I found. I had made mixins for each, but I forgot that they override each other. So, this seems like the best option for me.
transform(value)
  transform: value

.thing
  background red
  width 3rem
  height 3rem
  transform( translate(20%,20%) scale(1.2) rotate(98deg) )

Answer: if you define your mixin func name with a builtin css method, you may get this error. for example:
rotate($angular)               // mixin func name
  transform rotate($angular)   // rotate is a builtin css method, but stylus treats this "rotate" as a mixin usage, which makes a dead loop.


Head Pose Estimation Using Facial Landmarks

Question: I want to implement a vector starting from my nose and pointing in the same direction that I'm looking. The problem is the few examples I have found without dlib using facial landmarks are all broken. I don't want to use dlib because it will not install on this machine and I don't have time to troubleshoot it any longer. All landmarks are accurate, so the problem has to lay elsewhere.
This is what I'm shooting for.
The code I have written is here. The vector line is off significantly.
import numpy as np
import mediapipe as mp

def x_element(elem):
    return elem[0]
def y_element(elem):
    return elem[1]

cap = cv2.VideoCapture(0)
pTime = 0
faceXY = []
mpDraw = mp.solutions.drawing_utils
mpFaceMesh = mp.solutions.face_mesh
faceMesh = mpFaceMesh.FaceMesh(max_num_faces=5, min_detection_confidence=.9, min_tracking_confidence=.01)
drawSpec = mpDraw.DrawingSpec(0,1,1)

success, img = cap.read()
height, width = img.shape[:2]
size = img.shape

# 3D model points.
face3Dmodel = np.array([
    (0.0, 0.0, 0.0),  # Nose tip
    (0.0, -330.0, -65.0),  # Chin
    (-225.0, 170.0, -135.0),  # Left eye left corner
    (225.0, 170.0, -135.0),  # Right eye right corne
    (-150.0, -150.0, -125.0),  # Left Mouth corner
    (150.0, -150.0, -125.0)  # Right mouth corner
],dtype=np.float64)

dist_coeffs = np.zeros((4, 1))  # Assuming no lens distortion
focal_length = size[1]
center = (size[1] / 2, size[0] / 2)
camera_matrix = np.array(
    [[focal_length, 0, center[0]],
     [0, focal_length, center[1]],
     [0, 0, 1]], dtype="double"
)

while True:
    success, img = cap.read()
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = faceMesh.process(imgRGB)
    if results.multi_face_landmarks:                                            # if faces found
        dist=[]
        for faceNum, faceLms in enumerate(results.multi_face_landmarks):                            # loop through all matches
            mpDraw.draw_landmarks(img, faceLms, landmark_drawing_spec=drawSpec) # draw every match
            faceXY = []
            for id,lm in enumerate(faceLms.landmark):                           # loop over all land marks of one face
                ih, iw, _ = img.shape
                x,y = int(lm.x*iw), int(lm.y*ih)
                # print(lm)
                faceXY.append((x, y))                                           # put all xy points in neat array
            image_points = np.array([
                faceXY[1],
                faceXY[175],
                faceXY[446],
                faceXY[226],
                faceXY[57],
                faceXY[287]
            ], dtype="double")
            for i in image_points:
                cv2.circle(img,(int(i[0]),int(i[1])),4,(255,0,0),-1)
            maxXY = max(faceXY, key=x_element)[0], max(faceXY, key=y_element)[1]
            minXY = min(faceXY, key=x_element)[0], min(faceXY, key=y_element)[1]

            xcenter = (maxXY[0] + minXY[0]) / 2
            ycenter = (maxXY[1] + minXY[1]) / 2

            dist.append((faceNum, (int(((xcenter-width/2)**2+(ycenter-height/2)**2)**.4)), maxXY, minXY))     # faceID, distance, maxXY, minXY

            print(image_points)

            (success, rotation_vector, translation_vector) = cv2.solvePnP(face3Dmodel, image_points,  camera_matrix, dist_coeffs)
            (nose_end_point2D, jacobian) = cv2.projectPoints(np.array([(0.0, 0.0, 1000.0)]), rotation_vector, translation_vector, camera_matrix, dist_coeffs)

            p1 = (int(image_points[0][0]), int(image_points[0][1]))
            p2 = (int(nose_end_point2D[0][0][0]), int(nose_end_point2D[0][0][1]))

            cv2.line(img, p1, p2, (255, 0, 0), 2)

        dist.sort(key=y_element)
        # print(dist)

        for i,faceLms in enumerate(results.multi_face_landmarks):
            if i == 0:
                cv2.rectangle(img,dist[i][2],dist[i][3],(0,255,0),2)
            else:
                cv2.rectangle(img, dist[i][2], dist[i][3], (0, 0, 255), 2)

    cv2.imshow("Image", img)
    cv2.waitKey(1)

Answer: Turns out my table for facial points were unorganized.
This is the basic face template depths, it has an order.
face3Dmodel = np.array([
    (0.0, 0.0, 0.0),            # Nose tip
    (0.0, -330.0, -65.0),       # Chin
    (-225.0, 170.0, -135.0),    # Left eye left corner
    (225.0, 170.0, -135.0),     # Right eye right corner
    (-150.0, -150.0, -125.0),   # Left Mouth corner
    (150.0, -150.0, -125.0)     # Right mouth corner
    ], dtype=np.float64)

I typed it in the wrong order originally. This is now the same order as above.
            image_points = np.array([
                faceXY[1],      # "nose"
                faceXY[152],    # "chin"
                faceXY[226],    # "left eye"
                faceXY[446],    # "right eye"
                faceXY[57],     # "left mouth"
                faceXY[287]     # "right mouth"
            ], dtype="double")


How to always show Save as ... when download a image file in Webform result?

Question: If the upload file is an image in a Webform's result, clicking the link will show the image in the browser.
Is it possible to force to popup a Save as... dialog? Such the user downloads the file instead of viewing it?
Answer: This is technically not a drupal specific issue it is just how browsers deal with certain file types on the web in general.
Also note that you can right click a link to save the file always, so if this is an admin only feature then maybe that is sufficient?
If you are using Drupal's public file system for the images then it is possible to change your .htaccess file to change the behaviour of certain file types.
For more info on that see: Force files to download instead of showing up in the browser.
The .htaccess method should be the best performing and most reliable method, however if there is any reason you don't want to do it the .htaccess way there are a couple of drupal module that can help.
The File Force and Download File modules will allow you to configure file downloading however if you are making custom links to your files (for example if you are entering links directly into a text field or in custom code) you have to use a different url for the images to make sure that the links use the module's functionality, so be sure to read the documentation for whichever module you are using.
The modules are quite similar so use whichever you prefer.
[Edit]
I just remembered you are interested in webform related links.
Unfortunately since the current version of webform doesn't use Drupal's normal fields it won't work properly with these file downloading modules out of the box.
A feature request for the modules will be needed to add webform support.
Alternatively you could modify your webform links to use the special formatting the download module you are using supports.
For example, overriding the themeing of the webform file display like this would work if you are using the file force module:
<code>/**
 * Format the output of text data for this component
 */
function THEMENAME_webform_display_file($variables) {
  $element = $variables['element'];

  $file = $element['#value'];
  $url = (!empty($file) && !empty($file->uri)) ? webform_file_url($file->uri) : t('no upload');
  return (!empty($file) && !empty($file->uri)) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url, array('query' => array('download' => '1')))) : ' ';
}
</code>
It would be a similar process with the download file module.
Comment: Yes, .htaccess files will affect sub-directories.
Comment: Does the `.htaccess` way work for the current folder and also sub-folders? Or does it work for current folder only?
Answer: You can do it overriding below webform theme function in your theme
<code>/**
 * Format the output of text data for this component
 */
function theme_webform_display_file($variables) {
  $element = $variables['element'];
  $file = $element['#value'];
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url)) : ' ';
}
</code>
Override theme function in your theme folder ... I did for seven theme using code below , replace seven with your theme name in your template.php file..
<code>function seven_webform_display_file($variables) {
  $element = $variables['element'];
  $file = $element['#value'];
  $url = !empty($file) ? webform_file_url($file->uri) : t('no upload');
  return !empty($file) ? ($element['#format'] == 'text' ? $url : l($file->filename, $url, array('attributes' => array('download' => $file->filename)))) : ' ';
}
</code>
Trick here is to use Download attribute in HTML and it worked :-)
PS:  The download attribute is not supported in Internet Explorer, Safari or Opera 12 and earlier versions.
Comment: Note that the download attribute doesn't work in all browsers, although that might be fine depending on your needs.


CSS keep height, crop width in a div

Question: I have been searching for a while, I still cannot find the exact answer.
I have a
 for which the width takes 100% of the screen, the height is fixed at 600px.
I would like to add a background picture to the div for which the picture height would fit the
 height (600px and no picture crop). Whenever I modify the width of the screen, the height should always remain 600px. The picture would then be centered and cropped on the width direction.
Answer: Try this:

.container {
  width: 100%;
  height: 600px;
  background: url('https://images.pexels.com/photos/268415/pexels-photo-268415.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260');
  background-repeat: no-repeat;
  background-position: center;
  background-size: auto 100%;
}

Answer: Did you tried
`
    background-image: url('your-image.gif');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;

    `

Comment: It almost works. The only problem is that it also crop the height of the picture. for example if the picture is 700px, it will crop 100px from the picture. BTW to define the height of the div, I am using min-height: 600px;
Answer: I think this what you are looking for :

body {
  margin: 0px;
  padding: 0px;
}

div {
  width: 100vw;
  height: 600px;
  background: url('https://wallpaperbrowse.com/media/images/704532.jpg') no-repeat;
  background-size: 100% 600px;
  float: left;
  background-position: center;
}

  test

Hope this was helpful for you.

CSS keep height, crop width in a div


Theming views and overwriting the default file upload display

Question: Theming views in Drupal 7 can be very tedious to newbies. In the following example, a seemingly simple task has become an overwhelming research project into the innards of Drupal! Hoping an experienced drupalite can make quick sense of this.
In our example view we are outputing a product list to a page. One of the fields is a file type where the user uploads a PDF file. To gain maximum control of the layout, we were trying to utilize 'Rewrite the output of this field, and want to create a link to the PDF file with text inside of it that says Download PDF. Sounds simple!! However, so far it has not been.
Because this view is a list of a certain content type, node theming doesn't appear as one of the potential options for template theming. See bottom of the post for potential theming file name conventions that Drupal is offering up.
Also, this may be something easy to do with a hook in the theme's template file, but as of now, that is a little confusing as well and I'm not sure where to look for that solution.
So, for this post, we're hoping to get a clearer picture into the stock views management system. However, all suggestions are welcome!

Here is the code that resides in the rewrite section of the view for the Content-PDF field:

Here are the relevant Replacement Patterns:
[field_pdf_upload] == Content: PDF
[field_pdf_upload-fid] == Raw fid
[field_pdf_upload-display] == Raw display
[field_pdf_upload-description] == Raw description
The problem,
[field_pdf_upload] - gives you a PDF icon, a link to the PDF and it names the title of the file. If I could figure out how to replace the file name inside the href tag with "Download PDF", then this would be essentially solved. I've tried many options in the replacement patterns and what not, but nothing has worked yet. I tried stripping HTML and then adding the direct path to the file and that worked, but if the upload has spaces in it, the path breaks.
If I had access to php in this section, I could do something like this
$fid = [field_pdf_upload];
$file = file_load($fid);
Maybe there is a way to do this and I'm just not getting it?
I am going to start a separate jquery option thread for this in a second, bare w me and it will be written soon.

An alternate method would be to alter one of the theme suggestion templates listed under Advanced->Information - Below is the list of options.
Display output: views-view.tpl.php, views-view--product-landing.tpl.php, views-view--page.tpl.php, views-view--product-landing--page.tpl.php, views-view--default.tpl.php, views-view--default.tpl.php, views-view--page-1.tpl.php, views-view--product-landing--page-1.tpl.php
Style output: views-view-unformatted.tpl.php, views-view-unformatted--product-landing.tpl.php, views-view-unformatted--page.tpl.php, views-view-unformatted--product-landing--page.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--default.tpl.php, views-view-unformatted--page-1.tpl.php, views-view-unformatted--product-landing--page-1.tpl.php
Row style output: views-view-fields.tpl.php, views-view-fields--product-landing.tpl.php, views-view-fields--page.tpl.php, views-view-fields--product-landing--page.tpl.php, views-view-fields--default.tpl.php, views-view-fields--default.tpl.php, views-view-fields--page-1.tpl.php, views-view-fields--product-landing--page-1.tpl.php
Field Content: PDF (ID: field_pdf_upload): views-view-field.tpl.php, views-view-field--field-pdf-upload.tpl.php, views-view-field--product-landing.tpl.php, views-view-field--product-landing--field-pdf-upload.tpl.php, views-view-field--page.tpl.php, views-view-field--page--field-pdf-upload.tpl.php, views-view-field--product-landing--page.tpl.php, views-view-field--product-landing--page--field-pdf-upload.tpl.php, views-view-field--page-1.tpl.php, views-view-field--page-1--field-pdf-upload.tpl.php, views-view-field--product-landing--page-1.tpl.php, views-view-field--product-landing--page-1--field-pdf-upload.tpl.php
Can anyone recommend a method and sample code for accomplishing this task?
Answer: You don't need to use a template or get your hands dirty with code.
Just add the field to the view twice.  Hide the first field from display, but change the formatter to "URL to file".  Rewrite the output of the second field to "Download PDF".  On the second field, select output field as link and assuming your field is named 'pdf', make the path [field_pdf].


Predict when a user logins next

Question: I am building a user login prediction system. This is my first time building any prediction system. Main aim is to predict when a user might login next in future. That is i need to predict "Time". I have a dataset of hundreds of users and when did they login. It is shown below. I only have login time and nothing else. no activity time or logout time. i have gigabytes of such data.
<code>+----+----------------------------+----------------------------+----------+-----------------+
| Id | Time_Stamp                 | Login_Time                 | Day      | Account_name    |
+----+----------------------------+----------------------------+----------+-----------------+
|  1 | 2019-01-31 00:01:35.818000 | 00:01:35.818000         | Thursday | user1           |
|  2 | 2019-01-31 00:01:35.885000 | 00:01:35.885000         | Thursday | user2          |
|  3 | 2019-01-31 00:01:26.335000 | 00:01:26.335000         | Thursday | user2          |
|  4 | 2019-01-31 00:01:35.885000 | 00:01:35.885000         | Thursday | user1          |
|  5 | 2019-01-31 00:01:26.336000 | 00:01:26.336000         | Thursday | user2          |
|  6 | 2019-01-31 00:01:29.842000 | 00:01:29.842000         | Thursday | user3       |
|  7 | 2019-01-31 00:01:35.819000 | 00:01:35.819000         | Thursday | user4           |
|  8 | 2019-01-31 00:01:26.336000 | 00:01:26.336000         | Thursday | user7          |
|  9 | 2019-01-31 00:01:35.821000 | 00:01:35.821000         | Thursday | user5       |
| 10 | 2019-01-31 00:01:35.886000 | 00:01:35.886000         | Thursday | user4          |
+----+----------------------------+----------------------------+----------+-----------------+
</code>
My approach
1) Store data into data base and get data for each user as the original dataset has data combined for all users.
2) Run machine learning algorithms on each user and predict when he will login next
3) cross verify predicted result with actual result when the user does login.
Machine learning algorithm I am thinking is linear regression or SVM but the issue is in some user the data is too less and some is too much. so I need some algorithm which will work for both. Also I am planning to combine pattern recognition and time series prediction algorithms to get more accuracy.
Another issue is what variable should i take into account. Should I just pass login date and login time of each user and let the algorithm predict next? or is there any better way?
i need suggestion whether my approach is correct or not? How can I predict time? Do libraries support that or do I need to write my own algorithm?
Most Machine learning problems take some sort of numbers into consideration like stock market prediction but how should i take "time" into consideration?
Comment: OK.  Then it looks like you'll need to use just the limited number of variables that you have.  You can try running the algorithms separately for each user or your model might perform better by running the algorithm on the entire dataset and then making individual predictions (for example by treating User as a random effect in you use a regression modelling approach).  Regardless it would be imperative to split your data into training and validation datasets, being sure to select the algorithm that leads to the smallest prediction error.
Comment: It seems like you are leaving a lot of data on the table that could be useful to you.  I'd imagine you'd have some basic demographics of users that could be powerful predictors.  For example, time-zone, age, gender, etc.
Comment: If you're privy to network traffic statistics or load, that may be helpful too.
Comment: One good place to start looking may be [churn analysis](https://www.datascience.com/blog/what-is-a-churn-analysis-and-why-is-it-valuable-for-business).
Churn analysis deals with why people stop using a service, and usage patterns (including login patterns) are a key part of that. Some of the techniques used in such analyses may be of use to you.
https://www.r-bloggers.com/churn-analysis-part-1-model-selection/
https://towardsdatascience.com/predict-customer-churn-with-r-9e62357d47b4
Comment: @StatsStudent No. thats the biggest issue. I only have what is shown in the table above.
Comment: You don't have IP address that can then be used for geolocating users?
Comment: nope. No IP or even logout time or Amount of time spend etc. nothing.
Comment: I did look into this post which is quite similar to mine but it has more information where as mine doesnot. https://stats.stackexchange.com/questions/326884/predicting-which-users-will-login-at-a-particular-time
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/89103/discussion-between-samvid-kulkarni-and-statsstudent).
Comment: @Ingolifs This is really interesting. thanks for it. i will definitely look into it.
Answer: Without having seen the data, I don't think machine learning is the appropriate choice here because your data is not IID.
It is reasonable to believe that users may have different login habits, and we should allow for that in our model by modelling time between logins as a hierarchical model.
Posit that each user's time between logins has some distribution (maybe it is exponential), which is parameterized by $\lambda_i$. Then, maybe you say that the $\lambda_i$ come from some distribution.
So your model posits the following:
$$ (\Delta_{t})_{i} \sim \operatorname{Exponential}(\lambda _i) \quad i = 1 \dots N $$
$$ \lambda_i \sim P(\lambda)$$
Here $P$ is the distribution for the $\lambda_i$.  Maybe the $\lambda$ are gamma distributed or something.  I'm not saying that this is the model, but I think an approach like this is reasonable.  If you have a lot of data, you could even do an Empirical Bayes approach and construct "priors" from the data.
Comment: very sorry for late response. your answer seems reasonable to me as well. my approach is quite similar to yours.
Comment: Also can you suggest some ways to take time into consideration? should I separate time into hours, minutes and seconds then pass them into library or is there any other eay?
Comment: You can convert the time to fractional minutes, or days if the login times are sufficiently long.
Comment: (+1) Seems reasonable to me.

Predict when a user logins next


Filtered HTML Text format without an editor

Question: How can I set up the following:

Administrator should be able to use Full HTML with an editor window in Nodes.
Users should be able to use Filtered HTML in Nodes without an editor - just the markup.
Everybody should be able to use Filtered HTML in comments via markup - no editor.
Comment: Which editor are you trying to use?
Comment: Use ckEditor module.
Answer: First you create your two text formats (if not already present).
Then you can use the wysiwyg module (http://drupal.org/project/wysiwyg) to display an editor for the Full HTML text format (on /admin/config/content/wysiwyg). wysiwyg will only display editors that you have set up properly (usually by placing a third party library in sites/all/libraries)
You can limit use of the text formats via the permission settings.


Installing curl inside nginx docker image

Question: The following Dockerfile few lines suppose to install curl inside the nginx custom image to run under ubuntu.
The second group of code is an attempt to convert the task to do the same but to run on Amazon Linux.
Any suggestion as to what would be the yum equivalent to the rest of the apt-get command?
-no-install-recommends curl && rm -rf /var/lib/apt/lists/*
//Dockerfile for ubuntu
FROM nginx
RUN apt-get update && apt-get install -y -no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

//Dockerfile for Amazon linux
FROM nginx
RUN yum update && yum install -y curl

Answer: For Nginx image use Debian as OS use below : -
FROM nginx
RUN apt-get update && apt-get install -y curl && apt-get clean

Answer: if you're asking how to get the Amazon Linux-based Dockerfile to install curl without prompting you, you can add -y to yum update:
//Dockerfile for Amazon linux
FROM nginx
RUN yum -y update && yum install -y curl

Comment: No, that is not what I am asking. The question is in regards to the rest of the apt-get command which installed recommended dependencies. Also you put the `-y` after yum then after install in the second command.
Comment: no, there is no analog to 'recommended' dependencies when using yum like there is with apt-get. have you tried running the second Dockerfile build?
Answer: -no-install-recommends curl
should be
--no-install-recommends curl
you forgot to put double-dash
Comment: Be wary that `--no-install-recommends` may leave your image without certs needed to trust common services like GitHub.


Why use NSFetchedResultsController when inserting Core Data objects?

Question: I'm trying to get my head around Core Data on the iphone.
This is code from Apple's 'Navigation based app using Core data' template (method - insertNewObject)
<code>// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
</code>
It seems completely counter intuitive to me that the fetched results controller is used when inserting a new object.
I changed the code to this:
<code>NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name]
                                                                  inManagedObjectContext:managedObjectContext];
</code>
which works just as well and does not require access to the fetch request.
Am I missing something here? Is there any good reason to use the fetched results controller in the insert method?
Answer: The purpose of using the fetchedResultsConstroller in the Apple sample is to obtain the Entity type.  The obvious benefit that I see is that you're guaranteed type safety for the insert.  Whereas in your re-factored version you hard-code the entity type.
Although this isn't a big deal if you were to change the entity name to say, Event2, you would then have to change the hard-coded NSString (@"Event").
Comment: Ok but I could achieve type safety by declaring an ivar to hold the entity name or by using a #define statement.  The line I inserted staring NSEntityDescription is copied from the 'fetchedResultsController' method so @"Event" has to be hard-coded somewhere, I still don't see the benefit of using the fetch request.
Comment: Alternatively, you could create a constant which holds the entity name and use that in both the fetchedResultsController and insertNewObject methods?
Comment: That looks like the best approach to me!


Multiple func parameters for LINQ - EF

Question: I was fiddling around with the linq its Func parameter(on entity framework). Then I found out this behaviour
var idMatchQuery = new Func<MyClass, bool>(x => x.Id == someId);
var statusMatchQuery = new Func<MyClass, bool>(x => x.Status == someStatus);

/// works
var a = myClassEntity.FirstOrDefault(idMatchQuery);

/// doesn't work
var b = myClassEntity.FirstOrDefault(p => idMatchQuery(p) && statusMatchQuery(p));

/// doesn't work
var c = myClassEntity.FirstOrDefault(p => idMatchQuery(p) && p.Status == 1);

It throws UnsupportedOperationException since the EF does not recognize those queries. I could have accept it much easier if none of the above were not working. But it bugs me when it works with one and only one Func query, but not with combinations with other queries.
I'm sure there exist an explanation for it, but I guess my search terms were too naive for the answer I'm looking for.
What is the explanation for this behaviour?
Comment: Whether the first version "works" is debatable, because it resolves to `Enumerable.FirstOrDefault` call, not the `Queryable`, so it will bring the whole table in memory before applying your func, which I guess is not what you expect.
Comment: well if thats the case I am not even feeling okay now.
Answer: It is caused that, EF should translate your predicate to TSQL language. You can check, that parameter of FirstOrDefault method is not Func<T, bool>, but instead Expression<Func<T, bool>>, because last one give us oppotunity to parse it and translate to TSQL. When you use two Func<T, bool> or Func<T, bool> with simple condition EF can't translate and parse it to TSQL due to Expression<Func<T, bool>> inner stuff and features complexity, that is why EF keep this predicates at origin state and send to server as it was written at first, as a result - UnsupportedOperationException. So, for EF - parse first predicate much more easily than other two.
Conclusion: it is caused by features and methodology of translation C# predicates from Expression<Func<T,bool>> to TSQL, because of it's sometimes enough high complexity.
Comment: I see. Sounds valid. Let me give it a shot, and I'll get back to you.

Multiple func parameters for LINQ - EF


Parsing a file into separate strings

Question: File consist of 2 line of text.
need to parse the file so that each line of text is assigned to a string. my string variables are "PhoneNumber" and "Location" and the incoming file is stored in string "line".
 using (var sr = new StreamReader(incoming))
                {

                    while ((line = sr.ReadLine()) != null)
                    {

                        PhoneNumber = ??
                        Location = ??

                    }
                }

Comment: We can't help you without more information. In particular, what's in the file. If the first line is the phone number and the second the location, then initialize a counter (`var lineNumer=0;`) outside the loop, increment it inside the loop (as the last statement within the loop's code, `++loopNumber;`), and use that to decide to which variable you should assign `line`.
Comment: the file is a txt file and consist of 2 lines of text. Line is a phone number and line 2 is a location (Nebraska) and need to take each line from txt file and parse into PhoneNumber to consist of line 1 and Location to consist of line 2.
Answer: Maybe something like this?
using System.IO;

string Phonenumber = "";
string Location = "";
string[] filecontent = File.ReadAllLines("Filepath");
if (filecontent.Length > 0)
    Phonenumber = filecontent[0];
if (filecontent.Length > 1)
    Location = filecontent[1];

Edit:
Option 2 using StreamReader:
string Phonenumber = "";
string Location = "";
int LineCount = 0;

using (var sr = new StreamReader(@"Path"))
{
    var linecontent = "";
    while ((linecontent = sr.ReadLine()) != null)
    {
    if (LineCount == 0)
        Phonenumber = linecontent;
    if (LineCount == 1)
        Location = linecontent;
    LineCount++;
    }
}

Option 3 also using StreamReader:
using (var sr = new StreamReader(@"Path"))
{
    string Phonenumber = "";
    string Location = "";
    string[] filecontent = sr.ReadToEnd().Split("\n"); //Read text from file and split it into single lines
    if (filecontent.Length > 0)
        Phonenumber = filecontent[0];
    if (filecontent.Length > 1)
        Location = filecontent[1];
}

Comment: Not having much luck.
Comment: Does it matter that I am using "using (var sr = new StreamReader(incoming))" to retrieve file?
Comment: It only matters, when you call the read text function, make sure you read the text as individual line to an array. Or if you read it as one text split it using string.split("\n"); and enter that array to the filecontent array.
Comment: I have updated my answer. Check if it works another way
Comment: that all worked, thanks for the help.

Parsing a file into separate strings


Plugin de tradução WordPress

Question: Eai galera, bom a empresa ta querendo traduzir o site para Inglês e eles usam o WordPress. A ideia é ter um flag do reino unido que ao clicar deixe a pagina toda em inglês. (Obvio hahaha).
Pesquisei e vi sobre o wpml, porem acharam muito caro aqui. Alguem sabe algum outro plugin que faça isso?
A, e vale lembrar que temos todo o texto já traduzido, queremos inserir manualmente.
Apenas não queremos ter que refazer toda o container de novo.
Comment: tenta esse aqui https://wordpress.org/plugins/qtranslate-x/
Answer: No seu caso tente instalar o plugin qTranslate, ele é mais simples que outros e vai manter seu site com dois idiomas.

Plugin de tradução WordPress


Create a real taxonomy with drupal taxonomy and pathauto

Question: I'm creating a taxonomy for reptiles in drupal and wish to use pathauto for the term url's. The problem is to find the right tokens (I do have entity token installed). Lets look at an example of the taxonomy-tree for the vocabulary Reptiles:
Lizards
--Family
----Genus
------Species

So far so good:
[term:vocabulary]/[term:parent:parent:parent]/[term:parent:parent]/[term:parent]-[term:name]

result: /reptiles/lizards/family/genus-species
However sometimes there is also a subspecies, thus:
Lizards
--Family
----Genus
------Species
--------Subspecies

then starting at the lowest level and using [term:parent] doesn't work anymore.
Been looking for [term:child] and to generate the path from the opposite direction but I find nothing similar. Another way would be if I could define the term patters with levels in the hierarchy?
something like this:
    [term:vocabulary]/[term:level:1]/[term:level:2]/[term:level:3]-[term:level:4]-[term:level:5]

Maybe someone else knows how to crack this nut?
A better example on the outcome I seek:
/reptiles/lizards/gekkonidae/phelsuma-klemmeri

or as with a subspecies:
/reptiles/lizards/gekkonidae/phelsuma-klemmeri-subsp

Comment: Is the reason it doesn't work that you don't know a priori how many levels of parents you need? I'm not sure I understand why starting at the top would make a difference?
Comment: I added a "something like this" example. The problem when beginning with the lowest term (level 5) is that it may or may not be there. If we began coding from root level we could just skip level 5 if it is missing. Or maybe there is another way of building an taxonomy in drupal. The end result should be that a plant or an animal name is made up of a Genus-Species and maybe also a Subspecies.
Answer: You can configure URL pathauto alias for taxonomy terms as :
[term:vocabulary]/[term:parents:join-path]/[term:name]
for creating url aliases for taxonomy taxonomy hierarchy.
Explore more using replacement patterns for specific taxonomy terms.
Please refer this image for url aliases configuration page
Comment: result:
    'reptiles/lizards/gekkonidae/phelsuma/klemmeri'

This is a pretty good solution that would be ok for the taxonomy, but better would be if Genus and Species where joined with a '-' instead:

    'reptiles/lizards/gekkonidae/phelsuma-klemmeri'

or as with a subspecies:

    'reptiles/lizards/gekkonidae/phelsuma-klemmeri-subsp'
Comment: @HauRuck For that you can use below pattern :                         [term:vocabulary]/[term:parents:join-path]-[term:name] Replace last slash with dash that will result in format you required .
Comment: That works great when there is only a species: 'reptiles/lizards/agamidae/pogona-vitticeps'. But if there is a subspecies it breaks: 'reptiles/lizards/agamidae/pogona/vitticeps-subspecies'. Correct path with subspecies should be: 'reptiles/lizards/agamidae/pogona-vitticeps-subspecies'
Answer: @hitesh's solution using [term:parents:join-path] is good, but it won't create the hyphenated sub-path that you're after. To generate that you could add something like the following to a custom module (not tested):
  //move your module's execution of hook_taxonomy_term_presave to the end of the list,
    //so that it won't be overridden by the pathauto module.
    function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
      if ($hook == 'taxonomy_term_presave') {
        // Move hook to the end of the list.
        $group = $implementations['your_module'];
        unset($implementations['your_module']);
        $implementations['your_module'] = $group;
      }
    }

 // invoke hook_taxonomy_term_presave().
function YOUR_MODULE_taxonomy_term_presave($term) {
  switch ($term->vocabulary_machine_name) {
    case 'reptiles':
      //create the alias
      module_load_include('inc','pathauto','pathauto');
      $vocab = taxonomy_vocabulary_load($term->vid);
      $path = pathauto_cleanstring($vocab->name) . '/';
      $parents = array_reverse(taxonomy_get_parents_all($term->tid));
      foreach ($parents as $key => $parent) {
        // use '-' as glue for the second level down and '/' elsewhere
        $glue = ($key >= 1) ? '-' : '/';
        $path .= pathauto_cleanstring($parent->name) . $glue;
      }
      $path = rtrim($path, "-");
      $path_save('taxonomy/term/'.$term->tid, $path);
  }
}

Comment: This looks interesting, but maybe hook_taxonomy_term_presave($term) is too early? $term->tid is NULL
Comment: ref img of my desktop: http://picoolio.net/images/2014/02/25/Screenshot_from_2014-02-26_072139.png
Comment: Of course... You should be able to use hook_taxonomy_term_insert(), I think, but then, it only works when you create new terms. If you use the ..._update() hook, it will override any attempts to set the alias manually.
Answer: @olyN Big thank you for the code, it works like wonders. I'll post the finished code for future reference below if someone else seeks a php solution when tokens is not enough.

 //move your module's execution of hook_taxonomy_term_presave to the end of the list,
    //so that it won't be overridden by the pathauto module.

function YOUR_MODULE_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'taxonomy_term_insert') {
        // Move hook to the end of the list.
        $group = $implementations['YOUR_MODULE'];
        unset($implementations['YOUR_MODULE']);
        $implementations['YOUR_MODULE'] = $group;
    }
}

function YOUR_MODULE_taxonomy_term_insert($term) {
  switch ($term->vocabulary_machine_name) {
    case 'VOCABULARY_MACHINENAME':
      //create the alias
      module_load_include('inc','pathauto','pathauto');
      $vocab = taxonomy_vocabulary_load($term->vid);
      $path['alias'] = pathauto_cleanstring($vocab->name) . '/';
      $parents = array_reverse(taxonomy_get_parents_all($term->tid));
      foreach ($parents as $key => $parent) {
        // use '-' as glue for the second level down and '/' elsewhere
        $glue = ($key > 1) ? '-' : '/';
        $path['alias'] .= pathauto_cleanstring($parent->name) . $glue;
      }
      $path['alias'] = rtrim($path['alias'], "-");
      $path['source'] = 'taxonomy/term/'.$term->tid;
      path_save($path);
  }
}

function YOUR_MODULE_taxonomy_term_update($term) {
  switch ($term->vocabulary_machine_name) {
    case 'VOCABULARY_MACHINENAME':
      //create the alias
      module_load_include('inc','pathauto','pathauto');
      $vocab = taxonomy_vocabulary_load($term->vid);
      $path['alias'] = pathauto_cleanstring($vocab->name) . '/';
      $parents = array_reverse(taxonomy_get_parents_all($term->tid));
      foreach ($parents as $key => $parent) {
        // use '-' as glue for the second level down and '/' elsewhere
        $glue = ($key > 1) ? '-' : '/';
        $path['alias'] .= pathauto_cleanstring($parent->name) . $glue;
      }
      $path['alias'] = rtrim($path['alias'], "-");
      $path['source'] = 'taxonomy/term/'.$term->tid;
      path_save($path);
  }
}


Criar diretiva para máscara

Question: Quero usar a máscara xx/xx/xxxx em um campo de data e retornar no objeto com a máscara, não somente o valor. Usei uma diretiva ui-mask, porém não retorna com a máscara, já usei o model-view-value="true" mas não funciona, então quero criar uma diretiva que apenas pegue o valor e adicione as barras "//" via javascript com substring, somente isso. Mas como fica para utilizar junto com ui-mask? pela lógica, a diretiva teria que ser executada após a data ser toda digitada?
Segue o que eu fiz:
angular.module("modulo").directive("uiDate", function ($filter) {
    return {
        require: "ngModel",
        link: function (scope, element, attrs, ctrl) {
            var _formatDate = function (date) {
                date = date.replace(/[^0-9]+/g, "");
                if(date.length > 2) {
                    date = date.substring(0,2) + "/" + date.substring(2);
                }
                if(date.length > 5) {
                    date = date.substring(0,5) + "/" + date.substring(5,9);
                }
                return date;
            };
        }
    };
});

Porém ainda não funciona, pois a execução dela não está chamando de acordo, é chamada somente ao carregar a página, teria que ser após o campo já ter a data, para retornar apenas para meu ng-model o valor com a máscara. Como ficaria?
Comment: você precisa usar a diretiva ou teria problema usar um plugin externo? Se não tiver problema, dê uma olhada nesse: https://github.com/candreoliveira/ngMask é bem completo e funciona legal
Answer: Utilize a funcão $watch dentro da função link, onde a mesmo vai observar as mudanças que ocorrem na propriedade, e então você pode aplicar a lógica de máscara no valor de datas.
scope.$watch('propriedade', function (valorAtual, valorAnterior) {
    //código.
});

Documentação para $watch (inglês)
Comment: Utilizar para que? Onde? Como? Quando?
Comment: @CelsomTrindade :)
Answer: Você pode fazer com que a função seja executada sempre que o usuário digitar, ou, colocar um timeout para executar sempre n segundos após ele ter parado de digitar.
Qual utilizar então?
Se você deseja que o usuário veja a alteração em tempo real, utilize sem o timeout. Mas se não tem problema o usuário digitar tudo e só depois formatar a data, pode usar com timeout. Ou como você achar melhor.
Para isso, basta usar o método element.onkeypress = function()..., veja:
return {
    require: "ngModel",
    link: function (scope, element, attrs, ctrl) {

        element.onkeypress = function() { //É aqui que ele executa a função sempre que uma tecla for pressionada
            var _formatDate = function (date) {
                date = date.replace(/[^0-9]+/g, "");
                if(date.length > 2) {
                    date = date.substring(0,2) + "/" + date.substring(2);
                }
                if(date.length > 5) {
                    date = date.substring(0,5) + "/" + date.substring(5,9);
                }
                return date;
            };
        } //finaliza o element.onkeypress

    }
};

Ou, se você for utilizar com timeout, utilize da seguinte maneira:
element.onkeypress = function() {
    $timeout(function(){
        var _formatDate = function(date) {
        //... restante do código aqui
    }, 1000);
}

Por que estou dando essa resposta e no que ela difere da resposta anterior, que utiliza o $watch?
Há muita controvérsia no uso da propriedade $watch quando nos referimos a performance, já que ela está associada ao disparo do $digest, que é o ciclo que atualiza todas as variáveis de $scope de sua página. Então, quanto mais variáveis você possuir, mais pesado sua aplicação ficará com o uso de $watch, já que ele precisará analisar todas as variáveis sempre que o campo sofrer alteração de valor.
O método onkeypress não passa por isso, pois ele independe dos valores de variáveis, ele depende apenas da interação com o campo.
Comment: a função é chamada corretamente, porem não retorna o valor para o ngModel.
Comment: depurando vi que a data fica como quero, porem não ta setando no ngModel
Comment: Tente adicionar `scope:true` antes de iniciar o `link`
Comment: continua retornando sem as barras, porem depurando o return ja ta a data correta, mas não fica no ngmodel
Comment: vou fazer uns testes aqui e daqui a pouco retorno.
Comment: ok, fico no aguardo...
Answer: funcionou de boa pra mim assim:
angular.module("aeronaves").directive("uiDate", function() {
    return {
        require: "ngModel",
        link: function (scope, element, attrs, ctrl){
            var _formatDate = function(date){
                date = date.replace(/[^0-9]+/g, "");
                if(date.length > 2) {
                    date = date.substring(0,2) + "/" + date.substring(2);
                }
                if(date.length > 5){
                    date = date.substring(0,5) + "/" + date.substring(5,9);
                }

                return date;
            };

            element.bind("keyup", function (){
                ctrl.$setViewValue(_formatDate(ctrl.$viewValue));
                ctrl.$render();
            });
        }
    };

});

Criar diretiva para máscara


Getting NSInvalidArgumentsException when deleting uitableviewcells

Question: I implemented the commitEditingStyle method to delete a row from my tableview. If I simply put [timersArray removeObjectAtIndex:indexPath.row] the row deletes just fine. The only problem is that it does not animate so I tried putting this:
[self->tableView beginUpdates];
[self->tableView deleteRowsAtIndexPaths:timersArray withRowAnimation:UITableViewRowAnimationBottom];
[self->tableView endUpdates];

but when I try and delete something it brings up this:
'NSInvalidArgumentException', reason: '-[Timer row]: unrecognized selector sent to instance 0x17ed37b0'

I thought it was because the timersArray is a NSMuttableArray and not a NSArray but that did not change anything. Can someone help me find out how to fix this? Anything will help. Thanks!
Comment: Could you post a little more of the relevant code?
Answer: I fixed the issue by adding [NSArray arrayWithObject:indexPath] in place of timersArray in order for that to work I had to place the [timersArray removeRowAtIndex:indexPath.row] above the [self->tableView beginUpdates] and at that point it worked!


Rails associations and deletion

Question: I was going through Rails association  link. But I am not able to understand how the association works. I am using mysql db.
These are the files I generated:
user.rb
class User < ActiveRecord::Base
    has_many :orders
end

order.rb
class Order < ActiveRecord::Base
    belongs_to :user
end

20150911181301_create_orders.rb
class CreateOrders < ActiveRecord::Migration
  def change
    create_table :orders do |t|
      t.string :content
      t.integer :user_id

      t.timestamps null: false
    end
  end
end

20150911181351_create_users.rb
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps null: false
    end
  end
end

First I was expecting db:migrate will generate some foreign key relationship itself but it did not happen. Then I thought may be rails manages it internally but when I deleted a user through rails c , it did not delete corresponding orders from the order table.
Where is my understanding incorrect? Also give me some links which explains how does this works?
Answer: It's debatable but the traditional 'Rails way' is to manage model-related things like defaults, foreign keys, and triggers is at the ActiveRecord level instead of in the database.
That said, you're free to add a foreign key for referential integrity in a migration using the following:
add_foreign_key :orders, :users

More information is available in the Rails Guides.
The 'Rails way' to automatically destroy child objects when the parent is destroyed is to specify the :dependent strategy on the child collection. There is a great Stackoverflow discussion here going into detail about the two :dependentoptions: :destroy vs :delete_all.
Answer: Everything is in the docs
-You should note that "In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations."
-You should also note that when it comes to associations, Rails needs you to tell it that asides two models being related with belongs_to and has_many, you want the associated model to be deleted when it's parent model is deleted. That is where the dependent: :destroy comes in.
Now all you need to do in your code for orders related to a user to get deleted when the user is:
class User < ActiveRecord::Base
    has_many :orders, dependent: :destroy
end

Source: Rails Guides

Rails associations and deletion


For a bounded linear operator $\phi$, show that $||\phi(x)|| \leq ||\phi|| \cdot ||x||$, where $||\phi|| = sup_{||x|| = 1} ||\phi(x)||$

Question: In the book of Linear Algebra by Wernet Greub, at page 206, it is given that

$\phi$ is bounded iff for any $x\in E$, $\exists M$ s.t $$||\phi(x)||
 \leq M \cdot ||x||$$
  Now let  $\phi : E \to E$ is a bounded linear transformation.Then we denote
  $$||\phi|| = sup_{||x|| = 1} ||\phi(x)||,$$ and it follows that
  $$||\phi(x)|| \leq ||\phi|| \cdot ||x||, \quad x\in E.$$

However, I couldn't figure out how did he arrived to that conclusion. I mean for $||x|| = 1$, we have $||\phi(x)|| \leq M \cdot ||x|| = M$, hence by defition of supremum, we should have
$$sup_{||x|| = 1} ||\phi(x)|| = ||\phi|| \leq M,$$
hence for an arbitrary $y \in E$
$$||\phi|| \cdot ||y|| \leq M \cdot ||y||,$$
so I couldn't derive the same conclusion.
Comment: @GuyFsone I didn't see that question, thanks for pointing out.
Answer: For $x=0$ and for $x$ such that $\|x\|=1$ you agree with the conclusion. So fix an arbitrary $y\neq 0$ and note that
$$
\left\|\frac{y}{\|y\|}\right\|=1.
$$
It follows by the linearity of $\phi$ that
$$
\phi(y)=\|y\|\phi\left(\frac{y}{\|y\|}\right) \le \|y\|\,\|\phi\|.
$$
Comment: I guess you are still editing the answer ?
Comment: No, should I? $\text{ }$
Comment: That fact is already given by our assumption that $\phi$ is bounded.
Comment: See my last edit.
Comment: It seems to me that you assume that the definition that $\phi$ is "bounded" if $M:=\sup_{\|x\|=1}\|\phi(x)\|<\infty$ and you want to prove that $M<\infty$ if and only if $\sup_{x\neq 0}\frac{\|\phi(x)\|}{\|x\|}<\infty$. Now, one direction is obvious. The other one is shown in my answer. Anyway, you can find it in every basic book of functional analysis.
Comment: In the question, supremum of image of unit vectors are denoted as $||\phi||$, that was the problematic part, but I have undertood the logic, thank. If you correct the that notation, I will accept the answer. Otherwise, it will be a wrong answer to another person who will be looking to this question.


Habilitar .htaccess no Ubuntu 14.10, Apache/2.4.10

Question: Estou tentando habilitar o  .htacces no Ubuntu 14.10,mas vi na hora de configurar que a nova versão do Apache/2.4.10 o modo de configurar 'e diferente das anteriores.
Estou colocando os arquivos no /var/www/
Tentei ja mas nao estou conseguindo fazer funcionar.
apache2ctl -S:
VirtualHost configuration:
*:80                   127.0.1.1 (/etc/apache2/sites-enabled/000-default.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex rewrite-map: using_defaults
Mutex default: dir="/var/lock/apache2" mechanism=fcntl
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33

000-default.conf:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/

    <Directory "/var/www/">
        AllowOverride All
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

/etc/apache2/apache2.conf:
<Directory />
    Options FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

<Directory /usr/share>
    AllowOverride All
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Comment: Tentou `sudo a2enmod rewrite && service apache2 restart`?
Comment: ja sim mas nao funciona... @GuilhermeNascimento
Comment: O que aparece nos logs? `sudo a2enmod rewrite` apresenta algum erro?
Comment: parece tudo certo, a única coisa que percebi é que por padrão a pasta raíz é `/var/www/html/`
Comment: O retorno do sudo a2enmod rewrite:
Module rewrite already enabled
Comment: Como está o conteúdo do seu .htaccess?
Answer: Editar:
/etc/apache2/apache2.conf
Remover o comentário "#" da linha:
AccessFileName .htaccess
Reiniciar apache2:
service apache2 restart
Comment: Esta linha estava sem o comentário
Comment: Se você alterar o root da pasta "/var/www/" para outra qualquer (/var/www2 por exemplo) e reiniciar, você recebe erro?
Comment: Quero dizer, separar /var/www/ de **/etc/apache2/apache2.conf** com o /var/www/ de **000-default.conf**, surte algum efeito?
Answer: Solução:
No terminal entrando em /etc/apache2/sites-available/ acessando o arquivo 000-default acrescentei abaixo de: documentroot /var/www
<Directory /var/www/>
  Options Indexes FollowSymLinks
  AllowOverride All
  Order allow,deny
  allow from all

Comment: Não use a área de respostas, para pequenos questionamentos/esclarecimentos use os comentários essa parte aqui mais em baixo. O stack overflow funciona diferente da estrutura de um fórum, veja essas diferenças na [tour] (http://pt.stackoverflow.com/tour)
Comment: Me desculpe quando tentei comenta não me foi permitido dava uma mensagem de que era preciso de 50 pontos para fazer o comentário


Como abrir o app gmail pelo celular

Question: Eu sei que para abrir o maps é assim:
window.location = "geo:?q="+endereco;

Para abrir a discagem de telefone é assim:
 window.location = "tel:"+telefone1;

Para abrir a tela de mensagem(sms):
window.location = "sms:"+telefone;

Agora, como faço para abrir o email?
Comment: Já tentou `window.location.href = "mailto:firstname.lastname@example.com"` isso deve abrir o cliente default de email do usuário...
Answer: O Chrome no Android está bloqueando os redirecionamentos para os aplicativos que não são feitos por meio de um gesto do usuário.
Sendo assim, via javascript não é possível redirecionar o usuário para o aplicativo de e-mail, isso desde o Chrome 40, somente se você colocá-lo por exemplo em um botão href, que funcionará quando o usuário clicar no botão.
Aqui tem uma discussão sobre o assunto no fórum do Chrome.
Se você inspecionar o elemento vera uma mensagem como

Navigation is blocked: mailto:?...

Você pode tentar fazer desta forma, como citei antes que é adicionando um href.
var email = document.createElement('a');
email.style.visibility = 'hidden';
email.style.position = 'absolute';
email.href = 'mailto:email@example.com?subject=subject&body=body';
document.body.appendChild(email);

E após isso quando você for executar pode fazer assim.
email.click();

Comment: Valeu, era isso mesmo!

Como abrir o app gmail pelo celular


How to resize std::string to remove all null terminator characters?

Question: I'm using a std::string to interface with a C-library that requires a char* and a length field:
std::string buffer(MAX_BUFFER_SIZE, '\0');
TheCLibraryFunction(&buffer[0], buffer.size());

However, the size() of the string is the actual size, not the size of the string containing actual valid non-null characters (i.e. the equivalent of strlen()). What is the best method of telling the std::string to reduce its size so that there's only 1 ending null terminator character no explicit null terminator characters? The best solution I can think of is something like:
buffer.resize(strlen(buffer.c_str()));

Or even:
char buffer[MAX_BUFFER_SIZE]{};
TheCLibraryFunction(buffer, sizeof(buffer));
std::string thevalue = buffer;

Hoping for some built-in / "modern C++" way of doing this.
EDIT
I'd like to clarify the "ending null terminator" requirement I mentioned previously. I didn't mean that I want 1 null terminator explicitly in std::string's buffer, I was more or less thinking of the string as it comes out of basic_string::c_str() which has 1 null terminator. However for the purposes of the resize(), I want it to represent the size of actual non-null characters. Sorry for the confusion.
Comment: nothing wrong with `buffer.resize(strlen(buffer.c_str()));`
Comment: Why do you need to resize it? Does your C function get upset if you're passing it more than the length parameter indicates?
Comment: @void: If a C library takes a `char*`+size, then they almost always accept embedded NUL characters. That's *why* C APIs take string lengths. What you want to do is usually unnecessary.
Comment: @void.pointer: Then why do you need to do this? `basic_string::size` will give you the size of the buffer that can be written to. You want to tell the C function how much space it has to write into the buffer. Why do you need to truncate your buffer? If the C function returns how many characters it has written, just `resize` it to that afterwards.
Comment: @NicolBolas Because the size of the string after the call is technically a lie. I want it to be the size of actual characters, not the maximum size. If I use this string in a stream later, it writes out all the null characters as well which I don't want. In a way I'm abusing the size property of a string before the C function call to treat the string as a buffer with a maximum size.
Comment: @NicolBolas This particular C function is writing to the specified buffer I give it, not reading from it. I left that detail out, sorry about that. I won't know exactly how many characters are written until after the function returns.
Comment: Option 3, where you don't make a string until after the call, seems best to me
Comment: @void.pointer as Nicol said: "*If the C function returns how many characters it has written, just resize it to that afterwards*". Does the C function do that? `std::string buffer(MAX_BUFFER_SIZE, '\0'); int size = TheCLibraryFunction(&buffer[0], buffer.size()); buffer.resize(size);` I would find it very odd if a function taking a `char*`+maxsize doesn't return the real size. If not, just use `strlen(c_str())` after the function exits: `std::string buffer(MAX_BUFFER_SIZE, '\0'); TheCLibraryFunction(&buffer[0], buffer.size()); buffer.resize(strlen(buffer.c_str()));`
Answer: Many ways to do this; but probably the one to me that seems to be most "C++" rather than C is:
str.erase(std::find(str.begin(), str.end(), '\0'), str.end());

i.e. Erase everything from the first null to the end.
Comment: [std::string::find](http://en.cppreference.com/w/cpp/string/basic_string/find) doesn't return an iterator.
Comment: What about `str.resize(str.find('\0'));`?
Comment: @O'Neil you're right - would mean we have to add str.begin() (which breaks if not found) to it; or use std::find as liliscent said
Comment: I'm not sure whether I misunderstood OP's question, but this solution is flawed. If the original buffer is not null-terminated, the iterator is out of boundary.
Comment: @O'Neil Yeah that ran though my mind as well. Perhaps `MAX_BUFFER_SIZE+1` on the initial size, and then the previous snippet I gave would be safe.
Comment: I updated my question to clarify a misunderstanding. When I said I only wanted 1 trailing null terminator, I was implying the one that `std::string` manages & expects. So from the outside perspective, I don't want any explicit null terminators. Sorry for the confusion.
Comment: @void.pointer but std:string doesn't expect or require any null terminator
Comment: @UKMonkey From the perspective of `c_str()` it does. Not concerned about the implementation too much. Not disagreeing with you, just stating that I miscommunicated what I intended to ask for.
Comment: @NicolBolas yes - it will - but I answered the question at the time.  It has since changed;  I've updated my answer to match.
Comment: @void.pointer yes; c_str() will ensure that it provides a null terminated string; but this is NOT included in the size() call unless you explcitly add it to the string.  ie `std::string derp("hello")` has a length of 5, not 6
Answer: You can do this:
buffer.erase(std::find(buffer.begin(), buffer.end(), '\0'), buffer.end());

Consider std::basic_string::erase has an overload:
basic_string& erase( size_type index = 0, size_type count = npos );

A more succinct way:
buffer.erase(buffer.find('\0'));

A one-liner may not suffice, however, since you need to check whether the '\0' is actually present, and string::find() returns std::string::npos (equivalent to std::numeric_limits<std::string::size_type>::max()) if not found, so a better bet would be:
if (const auto pos = buffer.find('\0'); pos != std::string::npos)
    buffer.erase(pos);

Comment: This will remove the last '\0', which op said they didn't want.
Comment: This is also missing `#include ` to be able to use `std::find`
Answer: You can use buffer.find('\0') instead of strlen(buffer.c_str())
Answer: Using your
std::string buffer(MAX_BUFFER_SIZE, '\0');
TheCLibraryFunction(&buffer[0], buffer.size());

To remove 0-terminators, simplest is:
buffer = buffer.c_str();
(also possibly fastest? - didn't test)
Answer: I know this question already has some answers, but I also want to contribute with my answer, although this solution works for all null terminators only at the end of the string.
void rtrim_null(std::string& str) {
    str.erase(std::find_if(str.rbegin(), str.rend(), [](int character) {
        return '\0' != character;
    }).base(), str.end());
}

Answer: One Liner using boost::trim_if if you want to trim multiple characters (I wanted to remove \r, \n, \0 and ' ') from the string:
int main()
{
    std::string str("abcd \0 \r\n \0", 12);
    std::cout << "Str: " << str << std::endl;
    std::cout << "Length: " << str.length() << std::endl;

    boost::trim_if(str, boost::is_any_of(std::string("\r\n\0 ", 4)));

    std::cout << "Length: " << str.length() << std::endl;
    return 0;
}

Prints:
Str: abcd

Length: 12
Length: 4

Answer: I'd like to give you a very QUICK and EASY answer. Just do:
yourStringWithNullChars = yourStringWithNullChars.c_str();

then
yourStringWithNullChars.shrink_to_fit();

Done, no need to search and replace, no need for external libraries. Yes, it's tested, I use here on my program. ;)
Bye.


Google scripts : Multiple styles within a line of text in google docs

Question: I am quite new to Google scripts and javascript in general. I am doing the inventory of my grandpa's shop and my goal is to automate the creation of a catalogue (in google docs) with data from a google sheets. All I have done at the moment is fetch the data in the sheet with a script and put that information in a google docs with some simple text around it.
For example in my sheet I have information about an object (category, price, description, id, etc) and I would to like to display it like so in a google docs :
ID : 1
Category : clocks
Price : 1000
Description :
...The first mechanical clocks, employing the verge escapement mechanism with a foliot or balance wheel timekeep...
The problem I have is that I dont know how to put the text in bold but the data from my google sheet in normal text. I guess my question is more how do I style text, that is on the same line, differently ?
The result I want and the result I have
I am using setAttribute but this puts the whole text in bold :
function mailMerging(){
var doc = DocumentApp.create('Surprise document');
var body = doc.getBody();

var sheet = SpreadsheetApp.openById('1V_3KwMQPNYagjJdfbas7VjyjodUt')
var sheet_values = sheet.getDataRange().getValues()
var nb = sheet_values.length;}

// Style pour décrire chaque objet
var style_objet = {};
style_objet[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] =
  DocumentApp.HorizontalAlignment.LEFT;
style_objet[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style_objet[DocumentApp.Attribute.FONT_SIZE] = 12;
style_objet[DocumentApp.Attribute.BOLD] = true;

// On va chercher les infos pour chaque objet 1 à 1
for (var c=1; c<nb; c++){

var categorie = sheet_values[c][0];
var marque = sheet_values[c][1];
var prix = sheet_values[c][2];
var description = sheet_values[c][3];
var id = sheet_values[c][4];

var text = body.appendParagraph("ID : "+ id +"\nCatégorie : "+ categorie +"\nMarque : "+ marque +"\nPrix : "+ prix +"\nDescription : \n"+ description+"\n \n");
text.setAttributes(style_objet);
}

}

Thanks a lot for reading my question and thanks in advance for any responses. This is my first post so I hope I did okay.
Have a good day !
Answer: In your script, text.setAttributes(style_objet) is used to body.appendParagraph. By this, the attribute is reflected to all texts. I think that the reason of your issue is due to this. In order to achieve your goal, in this case, for example, how about putting the values of ID :  and id by separating and giving each attribute?
When your script is modified, how about the following modification?
From:
var style_objet = {};
style_objet[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
style_objet[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style_objet[DocumentApp.Attribute.FONT_SIZE] = 12;
style_objet[DocumentApp.Attribute.BOLD] = true;

// On va chercher les infos pour chaque objet 1 à 1
for (var c=1; c<nb; c++){

var categorie = sheet_values[c][0];
var marque = sheet_values[c][1];
var prix = sheet_values[c][2];
var description = sheet_values[c][3];
var id = sheet_values[c][4];

var text = body.appendParagraph("ID : "+ id +"\nCatégorie : "+ categorie +"\nMarque : "+ marque +"\nPrix : "+ prix +"\nDescription : \n"+ description+"\n \n");
text.setAttributes(style_objet);
}

To:
var style_objet = {};
style_objet[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
style_objet[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
style_objet[DocumentApp.Attribute.FONT_SIZE] = 12;
style_objet[DocumentApp.Attribute.BOLD] = true;

// --- I added below script.
var style_objet2 = {};
style_objet2[DocumentApp.Attribute.BOLD] = false;
// ---

// On va chercher les infos pour chaque objet 1 à 1
for (var c=1; c<nb; c++){
  var categorie = sheet_values[c][0];
  var marque = sheet_values[c][1];
  var prix = sheet_values[c][2];
  var description = sheet_values[c][3];
  var id = sheet_values[c][4];

  // --- I modified below script.
  [
    {title: "ID : ", value: id},
    {title: "Catégorie : ", value: categorie},
    {title: "Marque : ", value: marque},
    {title: "Prix : ", value: prix},
    {title: "Description : ", value: description}
  ].forEach(({title, value}) =>
    body.appendParagraph(title).setAttributes(style_objet).appendText(value).setAttributes(style_objet2)
  );
  body.appendParagraph("");
  // ---
}

Note:

I think that in your script, } of var nb = sheet_values.length;} might occur an error when the script is saved. Please be careful this.


como resolver o problema do modal pegando o ultimo id

Question:

                      Sistema
                      Usuario
                      Label
                      Descrição
                      Atualizar
                      Data Cadastro
                      Situação
                      Ações

                      @if (count($versoes) > 0)
                          @foreach ($versoes as $versao)

                                  {{ $versao->sistema->descricao }}
                                  {{ $versao->usuario->usuario}}
                                  {{ $versao->label }}
                                  {{ $versao->descricao }}
                                  @if($versao->atualiza_db==0){{{'Não'}}}@else{{{'Sim'}}}@endif
                                  {{ $versao->data_versao }}
                                  @if($versao->situacao==0){{{'Inativo'}}}
                                      @elseif($versao->situacao==1){{{'Ativa Para Atualização'}}}
                                      @elseif($versao->situacao==2){{{'Em Desenvolvimento'}}}
                                      @elseif($versao->situacao==3){{{'Aguardando Teste'}}}
                                      @endif

                                  <form action="{{ route('v1.versoes.delete', $versao->id) }}" method="post">
                                  {!! csrf_field() !!}
                                  {!! method_field('delete') !!}
                                   id) }}" data-original-title="Editar" title="Editar" style="float: right;
                                        margin-top: -2px;
                                        margin-right:30px;">

                                  id }}" class="botao"data-toggle="modal" data-target="#myModal">

                                  <button type="submit" data-original-title="Excluir" title="Excluir">

                                  </button>
                              </form>

                          @endforeach
                      @else

Nenhum evento encontrado.

                      @endif

id}} role="dialog" aria-labelledby="myModalLabel">

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Upload da Versão

          {{$versao->id}}

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Upload</button>

Comment: Por favor, [edit] a pergunta e elaborar um [mcve]. Da maneira que está é impossível aferir qualquer coisa sobre o problema, até porque a pergunta consiste apenas de um código HTML aleatório.
Comment: é porque criei o modal só que coloquei ele fora do laço ele pega o ultimo e se colocar dentro do laço pega o primeiro
Comment: Mas nem tem laço na sua pergunta :(
Comment: é pq iria ficar grande de mais o código
Comment: E é por isso que sempre solicitamos um [mcve], não o código completo.
Comment: editei lá, no php puro já usei modal mais com o laravel ta sendo a primeira vez
Comment: Acho que documentação do [bootstrap modal](https://getbootstrap.com/docs/4.3/components/modal/#varying-modal-content) pode te ajudar, você vai precisar trabalhar nos eventos que o componente modal dispara.
Comment: Seria importante tu elaborar a tua pergunta, não sei exatamente onde esta o seu problema, e o que tu pretende fazer. Somente o codigo não me ajudara a entender a sua situação.
Answer: Resposta aqui:
Exemplo 1
Exemplo 2
Vamos ver se agora rola um feedback
HehehehE


IIS7 Application Pool Crash

Question: I am running IIS 7.0 on Windows server 2008 R2 and created 1 Application Pool per site and I have 1 site which is causing the application pool to stop. These are the following errors in the Event Viewer:
This shows several times:
A process serving application pool 'Pilot.Mobile.SyncV2' terminated unexpectedly. The process id was '3620'. The process exit code was '0x80131506'.
Then I get this:
Application pool 'Pilot.Mobile.SyncV2' is being automatically disabled due to a series of failures in the process(es) serving that application pool.
Two Things- How can I findout why this is crashing e.g. tools or scritps, also has anyone get any scripts I can run on a schedule task that will check the application pools and if 1 is down it will restart it and email me.
Answer: You can find why it's crashing only by debugging the application; I'd start with the process exit code and look up what it means, and then enable sending ASP.NET error to clients in order to be able to see something in IE when the crash happens.
Other possible strategies: running the application pool with an attached debugger to see what's actually heppening, and/or modify the code to generate more detailed logs, include exception handlers, and so on.
If you are not one of the site developers, contact them; this is definitely an application issue, not a web server one.

To manage application pools from the command line, you can use the following commands:
appcmd start apppool /apppool.name: PoolName
appcmd stop apppool /apppool.name: PoolName
appcmd recycle apppool /apppool.name: PoolName

("Recycle" means "stop and restart").
Answer: I recommend the command: appcmd recycle apppool DefaultAppPool

IIS7 Application Pool Crash


Limitação no número de itens retornado do Facebook

Question: Tenho uma aplicação que recupera o feed de notícias de um grupo que eu posto.
O problema é que, eu só consigo recuperar os últimos 25 itens cadastrados, Tem alguma forma de recuperar mais do que isso?
Edit:
Meu código atual para recuperar os itens é:
<code>$response = $fb->get(
    $groupId . '/feed?fields=full_picture, message, picture, link, is_published, from'
    , $accessToken
);
</code>
Basicamente faço uma requisição GET na API do Facebook informando os campos que eu preciso que seja retornado via json.
As variaveis <code>$groupId e $accessToken</code>, possuem os valores do Id do grupo cujo qual estou tentando recuparar as informações, e a outra como o próprio nome diz é o access token necessário para realizar a consulta na API.
Comment: Por favor, adicione mais detalhes à sua pergunta e, se possível, o seu código atual. Dessa forma a comunidade poderá ajudá-lo mais rapidamente.
Comment: Olá Paulo, eu atualizei a pergunta com um pouco mais de informações e o código que eu utilizo, espero estar mais claro agora :)
Comment: Reveja a API do Facebook, vê se esse não é o limite da própria Facebook.
Answer: Olá, tente isso em seu código:
<code>$response = $fb->get(
    $groupId . '/feed?fields&limit=10=full_picture, message, picture, link, is_published, from'
    , $accessToken
);
</code>
limit=10 - Números de itens que o Facebook vai retornar.
Comment: Olá Matheus, acabei encontrando essa solução tbm....mas sem esse "limit", vc sabe se teria como retornar um número grande de itens?
Comment: @GuiPab você trocou o 10 pelo o tanto de itens que você quer?
Comment: Sim sim fiz isso e me atendeu a momento.....porém e quando eu quiser recuperar TODOS os itens manja?
Comment: @GuiPab eu acho que o limite é  200-225 posts.


public folder that auto replies only works for internal mail

Question: My Auto reply public folder only replies to internal mail. External mail makes it to the folder, but from an external test account, we do not get a reply. Where can I begin to look to find where this problem is. I wish this public folder to reply to everyone who sends a message to it.
Comment: Do you get external out of office messages to regular mailboxes?
Comment: I'm not sure what you mean by this, we do not have any issues with out of office messages.
Comment: It seems that no!! OOR do not seem to be working?! * completely shocked* Where can I go from here?
Answer: Require sender authentication is ON?
Check setup here:
http://www.bug-man.org/exchange-server-auto-reply-from-distribution-group-via-public-folder/
Comment: Welcome to Server Fault! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: I nuked the exchange box, and rebuilt if from scratch - worked so much faster and better.
Lesson learned: If you know you can build it better, do so!


How to hide arrows on numericUpDown control in win forms?

Question: to hide the arrows I have added numericUpDown.Controls[0].Hide(); and it hides the arrows but leaves white space when form is opened.

How to hide them to be like simple textBox?
Comment: It's more beautiful without them
Comment: I just need several number fields on form for some calculations, if I use textBox I'm not very sure how to convert their values to doubles and do some calculations with them
Comment: I can understand your aim, they are truely ugly and the cursor key work just as well; but I can't hide or remove them visually here. so the best option will be to put it into a label and thereby cover the right part of the nud
Comment: why do you need to hide them..?
Comment: Possible duplicate of [C# WinForms numericUpDown control (removing the spin box)](http://stackoverflow.com/questions/6222601/c-sharp-winforms-numericupdown-control-removing-the-spin-box)
Answer: You can hide the arrows by accessing the numericUpDown's Controls property. You can either hide or remove them:
numericUpDown1.Controls[0].Visible = false;

or
numericUpDown1.Controls.RemoveAt(0);

You can do this right after IntializeComponent().
Comment: It removes the up down buttons but still leaves with an unusable white area.
Answer: This solution also removes the unused space:
public class MyNumericUpDown : NumericUpDown
{
    public MyNumericUpDown()
    {
        Controls[0].Hide();
    }

    protected override void OnTextBoxResize(object source, EventArgs e)
    {
        Controls[1].Width = Width - 4;
    }
}

Comment: just in case anyone uses this, if you specify no border, you will have to add 4 instead.
Answer: NumericUpDownare nice, they bring Min, Max and Increment values for free and hold doubles.
But I can understand your aim, they are truly ugly and the cursor keys work just as well without those pesky little arrows; but I can't even hide or remove them visually here.
So I think the best option will be to put the NUD into a smaller  Label and thereby cover the right part of it..
If you want to you can wrap the following workaround in a NakedNumericUpDown class ;-)
nudLabel.AutoSize = false;
nudLabel.Location = numericUpDown1.Location;
nudLabel.BorderStyle = numericUpDown1.BorderStyle;
numericUpDown1.BorderStyle = BorderStyle.None;
numericUpDown1.Controls.RemoveAt(0);  // optional
numericUpDown1.Parent = nudLabel;
numericUpDown1.Location = Point.Empty;
nudLabel.ClientSize = numericUpDown1.Size;
nudLabel.Width -= 25;  // shrink enough to cover the arrows

You may want to create the Label dynamically, of course..
One problem is that now there is no visual clue that the users can up the arrow keys to change the values, though
Answer: You can use this code.
This code show up&down controllers, but they dont work, you use this code in Form_Load
YourNumericName.Controls[0].Enabled= false;

Answer: Add a custom Paint event to draw the arrows how you want (or draw over them).
E.g.
    NumericUpDown nud = new NumericUpDown();
    nud.Font = new Font(FontFamily.GenericSansSerif, 20f, FontStyle.Regular);
    bool isSet = false;
    NW nw = null;
    nud.Enabled = false;
    nud.VisibleChanged += delegate {
        // NUD children consist of two child windows:
        // 1) TextBox
        // 2) UpDownBase - which uses user draw
        if (!isSet) {
            foreach (Control c in nud.Controls) {
                if (!(c is TextBox)) {
                    // prevent flicker
                    typeof(Control).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, c, new object[] { true });
                    c.Paint += (sender,e) => {
                        var g = e.Graphics;
                        int h = c.Height;
                        int w = c.Width;

                        // cover up the default Up/Down arrows:
                        //g.FillRectangle(SystemBrushes.Control, 3, 3, w - 6, h/2 - 6);
                        //g.FillRectangle(SystemBrushes.Control, 3, h/2 + 3, w - 6, h/2 - 6);

                        // or hide the entire control
                        if (nud.Enabled)
                            g.Clear(nud.BackColor);
                        else
                            g.Clear(SystemColors.Control);
                    };

                    nw = new NW(c.Handle);
                    isSet = true;
                }
            }
        }
    };

To ignore click events:
class NW : NativeWindow {

    public NW(IntPtr hwnd) {
        AssignHandle(hwnd);
    }
    const int WM_NCHITTEST = 0x84;
    protected override void WndProc(ref Message m) {
        if (m.Msg == WM_NCHITTEST)
            return;

        base.WndProc(ref m);
    }
}

Comment: To erase the entire buttons, then use `g.Clear(nud.BackColor);` But then you should also use a `NativeWindow` and override the `WndProc` method to ignore the `HITTEST` message. Otherwise it's possible the user clicks a button and doesn't realize it.
Answer: Create your own numeric class. Numeric controls contains 2 controls. First textbox and second buttons. Hide first one and all your problems will be solved.
 public class MyCustomNumericBox : System.Windows.Forms.NumericUpDown
    {
        public MyCustomNumericBox()
        {
           Controls[0].Visible = false;
        }
    }

Then from toolbox get your numerir control: MyCustomNumericBox.
Or you can delete that control during constructor init and that's all
     public class MyCustomNumericBox : System.Windows.Forms.NumericUpDown
    {
        public MyCustomNumericBox()
        {
           Controls.Remove(Controls[0]);
        }
    }

Full code to fit your request:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Windows.Forms;
namespace yournamespace
{
    class NumericBx: NumericUpDown
    {
        public NumericBx()
        {
            var ctr = Controls[0];
            this.Controls[0].Visible = false;
            this.Controls[0].Enabled = false;
            this.Controls.Remove(ctr);
            // I have tried to rewrite sizes to hide unused area...but visual studio fails to
            //show num control. That is why this part is commented
            //Controls[0].Size = new Size(0, ClientSize.Height);
            //Controls[1].Size = new Size(ClientSize.Width, ClientSize.Height);
        }
    }
}

Comment: But what's the point of doing all this if the unused area is still shown as a hole in the form?
Answer: Aren't the arrows just the reason why anyone would use numericupdown control?
If you want it to be like textbox, then use textbox. Get the functionality for keyboard up or down arrow presses intercepting the keydown event.
Comment: Intercepting the arrow key hits, validating the result. That's not somethign I want to bloat my code with. This data belongs in the UI part of the code, not in the logical part.
Comment: No, `Value`, `Minimum`, `Maximum`, etc. are. I also inherit this thing and add a custom formatter utilizing `String.Format` to add units i.e. "1.23 μW", and custom handling of NaN. When inherited as an *indicator*, the arrows are actually not appropriate.
Answer: It's not the most elegant solution, but you can use a panel in the Form Designer and set the BackColor property to white and cover the arrows.
Of course this creates a white area where the user cannot interact with the control, so I recommend covering the NumericUpDown's borders and drawing a line on the left edge of the panel. (Looks something like this screenshot in the designer).
Then, add a Paint event to the panel:
private void panel1_Paint(object sender, PaintEventArgs e)
{
  using (Pen pen = new Pen(Color.FromArgb(174, 173, 179), 1))
  {
    e.Graphics.DrawLine(pen, 0, 0, 0, panel1.Height);
  }
}

Answer: I know this is an old thread but no one has solved it satisfactorily.
And here is mine solution:

Create a new "CustomControl"

Change CustomControl to NumericUpDown

Add an OnResize overridee
public partial class nNumeric : NumericUpDown
{
    public nNumeric()
    {
        InitializeComponent();
    }
    protected override void OnResize(EventArgs e)
    {
        var buttons = this.Controls[0];
        var edit = this.Controls[1];
        buttons.Visible = false;
        edit.MinimumSize = new Size( Width - edit.Left*2, 0);
        edit.Width = this.Width;
    }
}

done, simple and effective :)

I hope it will help someone :)
Answer: I have a quick-and-dirty 3-line workaround for that:
int widthOfSpinButtons = this.numericUpDown.Controls[0].Width; // store width of spin buttons before removing them
this.numericUpDown.Controls[0].Dispose(); // remove spin buttons; after this, the first item left in the list of controls is the UpDownEdit control (the texbox)
this.numericUpDown.Controls[0].MinimumSize = new Size(this.numericUpDown.Controls[0].Width + widthOfSpinButtons, this.numericUpDown.Controls[0].MinimumSize.Height); // increase the minimum width of the UpDownEdit (the textbox) to its current width plus the width of the removed spin buttons

Answer: Simple solution:change the input type from number to tel
input type="tel"
Comment: Windows Forms, not HTML.


How to use getResources().getIdentifier to get a Button id?

Question: I am trying to make a simple app.
I have a table with one row and seven buttons in that row.
I'm aware I don't need a 2d array, but I would like to use it.
So I can expand that later very easily.
I am using
int resID = getResources().getIdentifier("button" + i + h, "button", getPackageName());

to try and get the resource id from a Button.
My Buttons are named "button00, button01, button02 etc. (that's exactly how there are in R.java).
The numbers represent the row and column respectively.
I've seen people use this before, but for some reason I can never get it to work.
Here is my code for lights class
public class lights extends Activity implements OnClickListener {
public int numRows;
public int numCol;

public lights(int rows, int col) {
    numRows = rows;
    numCol = col;
}

public void createButtonListeners(Button[][] button) {
    for (int i = 0; i < numRows; i++) {
        for (int h = 0; h < numCol; h++) {
            int resID = getResources().getIdentifier("button" + i + h, "button", getPackageName());
            button[i][h] = (Button) findViewById(resID);
            button[i][h].setOnClickListener((View.OnClickListener) this);
            Toast.makeText(getBaseContext(), "Made listener", Toast.LENGTH_LONG).show();
        }
    }
}

public void reset(Array buttons[][]) {
    for (int r = 0; r < numRows; r++) {
        for (int c = 0; c < numCol; c++) {

            //havnt got this far
        }

    }

}

public int wasButtonPressed() {
    for (int row = 0; row < numRows; row++) {

    }

    return 0;
}

@Override
public void onClick(DialogInterface dialog, int which) {

}}

Code for Main_Activity
public class MainActivity extends Activity implements View.OnClickListener {

lights mlights = new lights(1, 7);
Button Button[][] = new Button[mlights.numRows][mlights.numCol];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mlights.createButtonListeners(Button);

}

@Override
public void onClick(View v) {

}}

I have no errors when i type my code but it does not run.
Please correct me in any possible way
Comment: Possible duplicate of [Android, getting resource ID from string?](http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string)
Answer: If you are trying to get an id, the second argument should be "id".
You're trying to get an R.id value, not an R.button value because those don't exist
You also implemented the wrong click listener on your lights Activity (which should not extend Activity anyway, but that's unrelated to your question... Just don't be surprised if your current code doesn't work)
Hint: try this public lights(Context c, int rows, int col) and use c.getResources using that Context to create your resources, or possibly a setButtons(Button[][] buttons) method that you'd call from the Activity (since that's the only place you can call findViewById)
Comment: Sorry I did have R.id as the argument. I changed it to R.button as a possible solution
Comment: I'd suggest you move all code into the MainActivity first , but `getResources().getIdentifier("button" + i + h, "id",` is correct, though I'd be careful to make sure i and h aren't added together to a single number
Comment: Your code doesn't work because `findViewById` cannot be called from the lights class. It's not an Activity because 1) you've not called onCreate 2) there's no setContentView called, so there's no UI
Comment: OK I get it now, I'll try that. Thanks for the help