Hi,
I have the following files in a directory called content: index.php, page1.php, page2.php and page3.php ONLY.
Then I have this code:
$column = scandir("content");
foreach ($column as $value) {
$stvalue = str_replace(".php", "", $value);
echo "<div>$stvalue</div>";
}
Nevertheless, this is what I get:
<div>.</div>
<div>..</div>
<div>index</div>
<div>page1</div>
<div>page2</div>
<div>page3</div>
Whats with the first 2 elements? I dont have files named like that so I dont get it.
Thank you.
. - is a special directory referencing the current directory.
.. - is also a special directory and its referencing the parent directory.
To remove the special directories I can think of some options:
1.
foreach(glob("*.php") as $filename) {
echo "<div>$filename</div>";
}
2.
$files = array_diff(scandir("content"), array('..', '.'));
foreach($files as $file) { ... }
3.
foreach ($files as $file) {
if($file != '.' and $file != '..') { ... }
}
All of the above are alternatives. You don't need to use scandir() if you use glob() and vice versa. glob() - expects a pattern. It is possible to also provide it with the path like this:
glob("[path]/*.php") - this will list any php file located in path. glob() documentation can be found here PHP - glob()
$column = scandir("content");
foreach ($column as $value) {
$stvalue = str_replace(".php", "", $value);
if($stvalue != '.' || $stvalue != '..') {
echo "<div>$stvalue</div>";
}
}
. refers to the current directory. .. refers to the parent directory.
This is why typing cd .. on a command prompt will change to the parent directory. It's been this way in DOS, every version of Windows, Mac OS X, it's not just Linux and UNIX variants.
If you don't want to display them on your page, just skip the first two entries using array_slice.
Related
I have recently started working in C++ and came across this situation when I have to create a directory while executing my code. The code is working fine when I have to create a single folder but it fails when I have to create another folder withing this newly created folder.
Suppose, I am in C: and want to store my file in C:/A/B/ .The following piece of code using mkdir() works fine if I have to store my file in C:/A/ but fails when I am adding another folder B.
Following is my code snippet:
#include <sys/stat.h>
#include <string>
using namespace std;
int main()
{
string stringpath = "C:/A/B/";
int status = mkdir(stringpath.c_str(),0777);
if(status!=0)
{
//.....
}
else
{
//....
}
}
Can someone help me in creating this directory where I can have any number of folders inside the parent directory? (P.S:I have added the header files sys/stat.h,iostream and string)
This is how you do it in C++17:
#include <filesystem>
namespace fs = std::filesystem;
fs::create_directories("./a/b/c")
mkdir() creates only the last component of the specified path. In your example, it will create only B. If any of the parent directories do not exist (ie, if A does not exist), the function fails with ENOENT. You need to split up the path and call mkdir() for every intermediate directory in the path, ignoring EEXIST errors as you go.
status = mkdir("C:/A/", 0777);
if ((status < 0) && (errno != EEXIST)) ...
status = mkdir("C:/A/B/", 0777);
if ((status < 0) && (errno != EEXIST)) ...
If you don't want to handle this manually, use a wrapper that handles it for you, such as Boost's create_directories() function:
bool create_directories(const path& p);
bool create_directories(const path& p, system::error_code& ec);
Effects: Establishes the postcondition by calling create_directory() for any element of p that does not exist.
Postcondition: is_directory(p)
Returns: true if a new directory was created, otherwise false.
Throws: As specified in Error reporting.
Complexity: O(n+1)where n is the number of elements of p that do not exist.
You can call the following:
string stringpath = "C:/A/B/";
int status = mkdir(stringpath.c_str(),0777);
If
C:/A/ directory exists. If its not exists, then do the following:
string stringpath = "C:/A/";
int status = mkdir(stringpath.c_str(),0777);
stringpath = "C:/A/B/";
int status = mkdir(stringpath.c_str(),0777);
In C++11 you can use the experimental functios:
#include <experimental/filesystem>
...
std::stringstream bufH;
bufH << dirName << fName;
if (!std::experimental::filesystem::exists(bufH.str()))
{
std::experimental::filesystem::create_directories(bufH.str());
}
Try the octal flag 7777 like this to have all the rights necessary to create this folder.
int status = mkdir(stringpath.c_str(), 7777);
Or do a chmod in the A folder like that :
chmod -r 7777 *
Got a weird question for you. Recently upleveled my old project from java 7(jdk1.7.0_10) to java 8(1.8.0.91.x86_64). In java 7 it printed the post script file with no issues and now it is printing the postscript file as plain text instead of converting the file. This is on a redhat linux environment. Simply I am trying to print a string containing a post script file of a file itself.
Here is my original code
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintService pService = PrintServiceLookup.lookupDefaultPrintService();
// In a field environment, send to the printer
if (System.getenv("USER_DEFINED_RELTOP") == null || pfr.exists()) {
if (pService.getName().isEmpty()) {
LOGGER.error("No printer selected");
} else {
LOGGER.info("Printing to " + pService.getName());
DocPrintJob pj = pService.createPrintJob();
try {
InputStream is = new ByteArrayInputStream(data.getBytes("UTF8"));
Doc doc = new SimpleDoc(is, flavor, null);
PrintJobWatcher pjw = new PrintJobWatcher(pj);
pj.print(doc, null);
pjw.waitForDone();
is.close();
} catch (PrintException | IOException e) {
LOGGER.error(e);
} // try block
} // no printer selected
// Otherwise, send to a file
} else {
That worked fine in java 7, I updated it to the oracle spec found here for java 8.
https://docs.oracle.com/javase/8/docs/api/javax/print/PrintService.html#createPrintJob--
https://docs.oracle.com/javase/8/docs/technotes/guides/jps/spec/printing.fm6.html
DocFlavor psFlavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
attrs.add(MediaSizeName.ISO_A4);
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(psFlavor,
attrs);
File pfr = new File(PFR_INDICATOR);
// In a field environment, send to the printer
if (System.getenv("USER_DEFINED_RELTOP") == null || pfr.exists()) {
//Check we have a printer capable of post script
if (pservices.length > 0) {
LOGGER.info("Printing to " + pservices[0].getName());
DocPrintJob pj = pservices[0].createPrintJob();
try {
InputStream fis = new ByteArrayInputStream(data.getBytes("UTF8"));
//byte[] ba =data.getBytes("UTF8");
Doc doc = new SimpleDoc(fis, psFlavor, null);
LOGGER.info("Doc Flavor " + doc.getDocFlavor());
PrintJobWatcher pjw = new PrintJobWatcher(pj);
LOGGER.info("PrintJob Attributes : " + pj.getAttributes());
pj.print(doc, attrs);
pjw.waitForDone();
fis.close();
} catch (IOException e) {
LOGGER.error(e);
NotificationDialog.show(NotificationDialog.NOTICE_TYPE.ERROR, PRINT_ERROR);
} catch (PrintException e) {
LOGGER.error(e);
}
} else { // no printer selected
This gives me an error java.awt.print.PrinterIOException: java.io.IOException: /usr/bin/lpr: where it looks to not find lpr.
If I keep it the way it was originally (not write to file) it prints the postscript as plain text even if adding the check to check if the printer is post script capable. If I use the new way of printing file I get a lpr not found error. If I print the PS document using the command lpr it converts it as expected and prints fine. If I use lpr -l that doesn't format it prints it document as plain text as well.
Any suggestion/help would be great. I am lost on what to do. I really don't want to convert it to an image and print that.
At a guess I'd say that your printer is an HP or at least PCL + PS printer, not a pure PostScript-only printer.
In that case you generally need to prepend the PostScript with a language selection PJL string. If you don't do this then it usually defaults to PCL and if you don't send any PCL commands (which all begin with 0x1B) then everything is treated as plain ASCII text. That would explain why both your application and lpr -l end up writing text, but lpr itself doesn't (presumably it adds the PJL).
You could try prepending the PostScript file with something like:
%-12345X#PJL JOB
#PJL ENTER LANGUAGE=POSTSCRIPT
NB the first byte there, before the % should be a 0x1b ESC character, but I can't readily paste binary....
Try sending the file with lpr -l if that works then you could try your old printing method.
sergiotapia at Macbook-Air in ~/Work/go/src/github.com/sergiotapia/gophers on master [!]
$ go build && go install && gophers -github_url=https://github.com/search?utf8=%E2%9C%93&q=location%3A%22San+Fransisco%22+location%3ACA+followers%3A%3E100&type=Users&ref=advsearch&l=
[1] 51873
[2] 51874
[3] 51875
[4] 51877
[2] Done q=location%3A%22San+Fransisco%22+location%3ACA+followers%3A%3E100
[3] Done type=Users
[4]+ Done ref=advsearch
I'm trying to use the long github url as a parameter in my code for Gophers. It works fine for all other url types such as organisations or stargazers. However when I try to use the search results page I get the strange output above.
https://github.com/search?utf8=%E2%9C%93&q=location%3A%22San+Fransisco%22+location%3ACA+followers%3A%3E100&type=Users&ref=advsearch&l=
package main
import (
"flag"
"log"
"strings"
"github.com/PuerkitoBio/goquery"
)
type user struct {
name string
email string
url string
username string
}
func main() {
url := flag.String("github_url", "", "github url you want to scrape")
flag.Parse()
githubURL := *url
doc, err := goquery.NewDocument(githubURL)
if err != nil {
log.Fatal(err)
}
if strings.Contains(githubURL, "/orgs/") {
scrapeOrganization(doc, githubURL)
} else if strings.Contains(githubURL, "/search?") {
scrapeSearch(doc, githubURL)
} else if strings.Contains(githubURL, "/stargazers") {
scrapeStarGazers(doc, githubURL)
} else {
scrapeProfile(doc)
}
}
It's a bash command line (or whatever the mac uses). & and ? are shell metacharacters that you MUST escape. The shell has absolutely no idea what a URL is, nor should it ever have to.
go 'http://....'
^-----------^
Adding quotes will prevent the shell from parsing the metacharacters. The alternative is to manually escape each and ever metachar yourself:
go http://example.com/script.php\?foo=bar\&baz=qux
^--------^
which quickly gets tedious, and error prone.
I would like to redirect urls that are using the wrong url alias.
Example, in my site I have:
English -> /prices/high-school -> node/112
Spanish -> (/es)/precios/high-school -> node/115
When a person or search engine reaches /es/prices/high-school a 404 is returned. What I would like is to redirect /es/prices/high-school to node/115.
I would like to do this in a general form, writing a module or using an existing one if possbile.
Thanks.
I already figured it out.
In the preprocess hook I need to check the page, strip the prefix and get the node id from the original id.
See code below:
if(current_path()=="search404")
{
$url = request_path();
if (startsWith($url,'es/') ||
startsWith($url,'de/') ||
startsWith($url,'it/') ||
startsWith($url,'fr/') )
{
$originalPath = substr($url,3,strlen($url)-3);
$path = drupal_lookup_path("source", $originalPath,"en");
if (isset($path))
{
$node = menu_get_object("node", 1, $path);
if (isset($node))
{
$prefix = substr($url,0,2);
$translated_paths = translation_path_get_translations('node/' . $node->nid);
if (isset($translated_paths) && array_key_exists ($prefix,$translated_paths))
{
if (isset($_GET['destination'])) {
unset($_GET['destination']);
}
$new_path = $translated_paths[$prefix];
drupal_goto($new_path, array(),301);
}
}
}
}
}
It won't be a solution to add different url aliases for the language versions? I mean:
node/112 -> /prices/high-school
node/115 -> /es/precios/escuela-secundaria
i18n module handles language based paths and redirects too.
I installed MediaWiki locally. Everything worked but I needed a functionality to link files from our file server. I stumbled upon an extension called Extension:NetworkLink which provides this functionality. You just have to add filepath in your wikipage and it should work. My problem is that I the path of my local wiki installation "http://localhost/w/index.php/" is addedd to filepath and then the link does not work. I tried to edit the url manipulation in the PHP file to cut it out but it does not work. Here is the edited code:
<?php
function linkExtension() {
global $wgParser;
$wgParser->setHook( "link", "renderlink" );
}
# The callback function for converting the input text to HTML output
function renderlink( $loc='', $argv=array() ) {
global $wgOut, $wgTitle, $wgParser;
$loc = htmlspecialchars($loc);
$pos = strrpos($loc, "/");
if ($pos != false)
{
$loc = substr($loc, $pos + 1);
}
switch( strtoupper( $argv['TARGET'] ) ) {
case "SELF":
$out = "$loc";
break;
case "TOP":
$out = "$loc";
break;
case "PARENT":
$out = "$loc";
break;
default:
$out = "$loc";
}
return $out;
}
I found another better solution. First install the FF-plugin LocalLink. Then add the MediaWiki Extension:FileProtocolLinks. After this you can add links in your wiki to local files or shares on your network like this:
LAN: <file>\\Fileserver\Directory1\Directory2\MyFile.zip</file>
Local: <file>C:/Directory1/Directory2/MyFile.zip</file>