How can i make a generated code using fpdf [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code was made by other, but i want to change it for my own purposes.
The code is giving 13 numbers, but only want the numbers of the ID(from database).
Example of what i need:
ID = 908
EAN13 = 000000908
My real question is how can i remove the 0000 from the BARS, then after scanning the SCANNER wil read the correct ID.
This is fora study guys!
class PDF_BARCODE extends FPDF
{
function EAN13($x, $y, $barcode, $h=16, $w=.35, $fSize=9)
{
$this->Barcode($x,$y,$barcode,$h,$w,$fSize,13);
}
function UPC_A($x, $y, $barcode, $h=16, $w=.35, $fSize=9)
{
$this->Barcode($x,$y,$barcode,$h,$w,$fSize,12);
}
function GetCheckDigit($barcode)
{
//Compute the check digit
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode[$i];
for($i=0;$i<=10;$i+=2)
$sum+=$barcode[$i];
$r=$sum%10;
if($r>0)
$r=10-$r;
return $r;
}
function TestCheckDigit($barcode)
{
//Test validity of check digit
$sum=0;
for($i=1;$i<=11;$i+=2)
$sum+=3*$barcode[$i];
for($i=0;$i<=10;$i+=2)
$sum+=$barcode[$i];
return ($sum+$barcode[12])%10==0;
}
function Barcode($x, $y, $barcode, $h, $w, $fSize, $len)
{
//Padding
$barcode=str_pad($barcode,$len-1,'0',STR_PAD_LEFT);
if($len==12)
$barcode='0'.$barcode;
//Add or control the check digit
if(strlen($barcode)==12)
$barcode.=$this->GetCheckDigit($barcode);
elseif(!$this->TestCheckDigit($barcode))
$this->Error('Incorrect check digit');
//Convert digits to bars
$codes=array(
'A'=>array(
'0'=>'0001101','1'=>'0011001','2'=>'0010011','3'=>'0111101','4'=>'0100011',
'5'=>'0110001','6'=>'0101111','7'=>'0111011','8'=>'0110111','9'=>'0001011'),
'B'=>array(
'0'=>'0100111','1'=>'0110011','2'=>'0011011','3'=>'0100001','4'=>'0011101',
'5'=>'0111001','6'=>'0000101','7'=>'0010001','8'=>'0001001','9'=>'0010111'),
'C'=>array(
'0'=>'1110010','1'=>'1100110','2'=>'1101100','3'=>'1000010','4'=>'1011100',
'5'=>'1001110','6'=>'1010000','7'=>'1000100','8'=>'1001000','9'=>'1110100')
);
$parities=array(
'0'=>array('A','A','A','A','A','A'),
'1'=>array('A','A','B','A','B','B'),
'2'=>array('A','A','B','B','A','B'),
'3'=>array('A','A','B','B','B','A'),
'4'=>array('A','B','A','A','B','B'),
'5'=>array('A','B','B','A','A','B'),
'6'=>array('A','B','B','B','A','A'),
'7'=>array('A','B','A','B','A','B'),
'8'=>array('A','B','A','B','B','A'),
'9'=>array('A','B','B','A','B','A')
);
$code='101';
$p=$parities[$barcode[0]];
for($i=1;$i<=6;$i++)
$code.=$codes[$p[$i-1]][$barcode[$i]];
$code.='01010';
for($i=7;$i<=12;$i++)
$code.=$codes['C'][$barcode[$i]];
$code.='101';
//Draw bars
for($i=0;$i<strlen($code);$i++)
{
if($code[$i]=='1')
$this->Rect($x+$i*$w,$y,$w,$h,'F');
}
//Print text uder barcode
$this->SetFont('Arial','',$fSize);
$this->Text($x,$y+$h+11/$this->k,substr($barcode,-$len));
}
}

The EAN-13 barcode format inherently encodes 13 digits. If you mess with it so it encodes fewer digits, the barcode will no longer be EAN-13, and many barcode readers will not recognize it.
You're using leading zeros on your codes in your nonstandard application. I say nonstandard because EAN-13 has a registry of prefixes. Whatever you use to read your barcodes will need to remove the leading zeros.
If you must avoid leading zeros in your barcode, you may want to switch to another more flexible barcode format, Code 39, Codabar, or even QR codes. Or you might choose EAN-8 or EAN-5. You can look up all these.

Related

PHP - if int reached to n [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Take these levels:
level1 = 0days
level2 = 30days
level3 = 90days
All these levels are totally dynamic. Admin can alter number of levels and duration of levels at any time.
I am recording numberOfDailyLogin in a series, so if user not login even for 1 day meter reset to 0.
I am trying to give user a special level tag on basis of numberOfDailyLogin
I have a solution already by running a while loop from 0 to numberOfDailyLogin and update variable once >= daysRequired for login.
But I don't want it this way, want something easy
I am totally clueless at this point, I can't hardcode any of the
value, so please if you are interest please give some suggestion.
#Edit1
// json response for levels
{
"status": 200,
"body": [
{
"name": "level1",
"after_days": 0,
},
{
"name": "level2",
"after_days": 50,
},
{
"name": "level3",
"after_days": 180,
}
]
}
function getLevel($allLevels, $numberOfDailyLogins) {
foreach ($allLevels as $l) {
if ($numberOfDailyLogins > $l['after_days']) {
return $l['name'];
}
}
}
Problem is if numberOfDailyLogins=51.. so it should show level2... cause after 50 days userLevel reached to level2.. but my code return level1 which is totally wrong.
#brombeer suggestion works for me, Thanks mate
function getLevel($allLevels, $numberOfDailyLogins) {
$level = null;
foreach ($allLevels as $l) {
if ($numberOfDailyLogins> $l['after_days']) {
$level = $l;
}
}
// TO-DO... do whatever you want
}
It's a simple logic error - your code returns after the first iteration because the value is already greater than 0 (the first level in the list).
One simple solution is to search the array in reverse instead:
function getLevel($allLevels, $numberOfDailyLogins) {
for ($i = count($allLevels) -1; $i >= 0; $i--) {
if ($numberOfDailyLogins > $allLevels[$i]['after_days']) {
return $allLevels[$i]['name'];
}
}
}
Demo: http://sandbox.onlinephpfunctions.com/code/3b00c6d182676411915cae1fbb21a1afba2548e8

How do I use functions in my php code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm learning about functions in my programming class and no matter what I do I just cant get this to work. Here is the problem that needs fixing:
What's wrong here?
The getWage() function is supposed to calculate overtime (time and a half) for any hours worked above 40. The function is working just fine but when we send the $hoursWorked and $hourlyWage from THIS program the function does not calculate the overtime as time and a half!
Can you fix it? The wage should be $605.63 not $573.75
Here is my function:
<?php
function getWage($hourlyWage, $hoursWorked) {
if ($hoursWorked <= 40)
return round(($hourlyWage * $hoursWorked), 2);
else
return round((($hourlyWage * 40) +
($hourlyWage * 1.5 * ($hoursWorked - 40))), 2);
}
?>
and here is where I try to call it to my program:
<?php
include("incWageFunctions.php");
$hourlyWage = 12.75;
$hoursWorked = 45;
$wage = getWage($hoursWorked, $hourlyWage);
print("<p>Your hourly wage is $$hourlyWage and you worked
$hoursWorked hours.</p>");
print("<p>Your wages are $$wage.</p>");
?>
Its not calculating the overtime no matter what... Where am I going wrong?! Also, how would you call multiple functions to the same program to calculate different things? Can I just call it with the name after the include statement? Or do I have to have it written out with the { } like my first function in this question??
You interchanged $hoursWorked and $hourlyWage
Change $wage = getWage($hoursWorked, $hourlyWage);
To $wage = getWage($hourlyWage, $hoursWorked);
You have mixed up the arguments. In php-file you have coded:
$wage = getWage($hoursWorked, $hourlyWage);
However, in incWageFunctions.php you have written:
function getWage($hourlyWage, $hoursWorked)

How to find divergent coordinates? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list of coordinates (longitude and latitude) in a csv-file. The coordinates are representing a store. There are almost a hundred files over stores, one per country. But some coordinates are wrong (Manually written in by employees).
There are about 100 stores (in average) in each country.
I could sent the coordinates to the google api to check if it is the same country as the rest but the google maps api will only recieved 2500 request for free.
How could I code a method that will just test some divergent coordinates instead of every coordinate?
Here we have a example of coordinates of stores in france. But one coordinate is located in Ghana.
latitude longitude
42,82377 0,316521
46,180742 6,7042473
45,0144927 6,1242264
42,6281 9,4206
46,0259861 6,6388244
47,9622395 1,8441825
5,623027 -1,043182
44.773491 6.03283
48,2814547 7,4579305
50.726231 1.60238
45,751175 3,110678
46,1875023  5.2071938
44,944816 4,841903
45,1484023 5,7223511
44,556944 4,749496
45,467654 4,352633
45,564601 5,917781
45,556935 5,971688
47,312494 5,117044
45,93813 6,090965
Maybe making an average value of coordinates :
$average = array('latitude' => 0, 'longitude' => 0);
// determine the total of coordinates values
foreach($coordinates as $coord){
$average['latitude'] += $coord['latitude'];
$average['longitude'] += $coord['longitude'];
}
// Divide by the number of coordinates to get an average value of the lat/long
$average['latitude'] /= count($coordinates);
$average['longitude'] /= count($coordinates);
// max distance to considere the measure is bad
$maxDistance = 5.0; // YOU SHOULD CONFIGURE THIS VARIABLE
// then, we determinate strangers :p
$strangers = array();
foreach($coordinates as $coord){
if($coord['latitude'] > $average['latitude'] + $maxDistance
OR $coord['latitude'] < $average['latitude'] - $maxDistance
OR $coord['longitude'] > $average['longitude'] + $maxDistance
OR $coord['longitude'] < $average['longitude'] - $maxDistance){
$strangers[] = $coord;
}
}
// you get your list, and you can use it
foreach($strangers as $strange){
echo $strange['latitude'] . " : " . $strange['longitude'];
}
I think there are many algorithmes outhere which are better than this one by the way...

Point in Polygon algorithm giving wrong results sometimes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I saw on StackOverflow a "point in polygon" raytracing algorithm that I implemented in my PHP Code. Most of the time, it works well, but in some complicated cases, with complex polygons and vicious points, it fails and it says that point in not in polygon when it is.
For example:
You will find here my Polygon and Point classes: pointInPolygon method is in Polygon class. At the end of the file, there are two points that are supposed to lie inside the given polygon (True on Google Earth). The second one works well, but the first one is buggy :( .
You can easily check the polygon on Google Earth using this KML file.
Have been there :-) I also travelled through Stackoverflow's PiP-suggestions, including your reference and this thread. Unfortunately, none of the suggestions (at least those I tried) were flawless and sufficient for a real-life scenario: like users plotting complex polygons on a Google map in freehand, "vicious" right vs left issues, negative numbers and so on.
The PiP-algorithm must work in all cases, even if the polygon consists of hundreds of thousands of points (like a county-border, nature park and so on) - no matter how "crazy" the polygon is.
So I ended up building a new algorithm, based on some source from an astronomy-app:
//Point class, storage of lat/long-pairs
class Point {
public $lat;
public $long;
function Point($lat, $long) {
$this->lat = $lat;
$this->long = $long;
}
}
//the Point in Polygon function
function pointInPolygon($p, $polygon) {
//if you operates with (hundred)thousands of points
set_time_limit(60);
$c = 0;
$p1 = $polygon[0];
$n = count($polygon);
for ($i=1; $i<=$n; $i++) {
$p2 = $polygon[$i % $n];
if ($p->long > min($p1->long, $p2->long)
&& $p->long <= max($p1->long, $p2->long)
&& $p->lat <= max($p1->lat, $p2->lat)
&& $p1->long != $p2->long) {
$xinters = ($p->long - $p1->long) * ($p2->lat - $p1->lat) / ($p2->long - $p1->long) + $p1->lat;
if ($p1->lat == $p2->lat || $p->lat <= $xinters) {
$c++;
}
}
$p1 = $p2;
}
// if the number of edges we passed through is even, then it's not in the poly.
return $c%2!=0;
}
Illustrative test :
$polygon = array(
new Point(1,1),
new Point(1,4),
new Point(4,4),
new Point(4,1)
);
function test($lat, $long) {
global $polygon;
$ll=$lat.','.$long;
echo (pointInPolygon(new Point($lat,$long), $polygon)) ? $ll .' is inside polygon<br>' : $ll.' is outside<br>';
}
test(2, 2);
test(1, 1);
test(1.5333, 2.3434);
test(400, -100);
test(1.01, 1.01);
Outputs :
2,2 is inside polygon
1,1 is outside
1.5333,2.3434 is inside polygon
400,-100 is outside
1.01,1.01 is inside polygon
It is now more than a year since I switched to the above algorithm on several sites. Unlike the "SO-algorithms" there have not been any complaints so far. See it in action here (national mycological database, sorry for the Danish). You can plot a polygon, or select a "kommune" (a county) - ultimately compare a polygon with thousands of points to thousands of records).
Update
Note, this algorithm is targeting geodata / lat,lngs which can be very precise (n'th decimal), therefore considering "in polygon" as inside polygon - not on border of polygon. 1,1 is considered outside, since it is on the border. 1.0000000001,1.01 is not.

Converting Python Code to PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
Is there a software converter out there that can automatically convert this python code to PHP?
#!/usr/bin/python
import math
def calcNumEntropyBits(s):
if len(s) <= 0: return 0.0
symCount = {}
for c in s:
if c not in symCount: symCount[c] = 1
else: symCount[c] += 1
entropy = 0.0
for c,n in symCount.iteritems():
prob = n / float(len(s))
entropy += prob * (math.log(prob)/math.log(2))
if entropy >= 0.0: return 0.0
else: return -(entropy*len(s))
def testEntropy(s):
print "Bits of entropy in '%s' is %.2f" % (s, calcNumEntropyBits(s))
testEntropy('hello world')
testEntropy('bubba dubba')
testEntropy('aaaaaaaaaaa')
testEntropy('aaaaabaaaaa')
testEntropy('abcdefghijk')
I'm not aware of any Python-to-PHP converter in the wild, but it should be a trivial task to port and the similarities are quite easy to spot:
function calcNumEntropyBits($s) {
if (strlen($s) <= 0) return 0.0;
$symCount = array();
foreach (str_split($s) as $c) {
if (!in_array($c,$symCount)) $symCount[$c] = 1;
else $symCount[$c] ++;
}
$entropy = 0.0;
foreach ($symCount as $c=>$n) {
$prob = $n / (float)strlen($s);
$entropy += $prob * log($prob)/log(2);
}
if ($entropy >= 0.0) return 0.0;
else return -($entropy*strlen($s));
}
function testEntropy($s):
printf("Bits of entropy in '%s' is %.2f",$s,calcNumEntropyBits($s));
testEntropy('hello world');
testEntropy('bubba dubba');
testEntropy('aaaaaaaaaaa');
testEntropy('aaaaabaaaaa');
testEntropy('abcdefghijk');
The last few lines in the first function could have also been written as a standard PHP ternary expression:
return ($entropy >= 0.0)? 0.0: -($entropy*strlen($s));
I created a python-to-php converter called py2php. It can auto-translate the basic logic and then you will need to tweak library calls, etc. Still experimental.
Here is auto-generated PHP from the python provided by the OP.
<?php
require_once('py2phplib.php');
require_once( 'math.php');
function calcNumEntropyBits($s) {
if ((count($s) <= 0)) {
return 0.0;
}
$symCount = array();
foreach( $s as $c ) {
if (!$symCount.__contains__($c)) {
$symCount[$c] = 1;
}
else {
$symCount[$c] += 1;
}
}
$entropy = 0.0;
foreach( $symCount->iteritems() as $temp_c ) {
$prob = ($n / float(count($s)));
$entropy += ($prob * (math::log($prob) / math::log(2)));
}
if (($entropy >= 0.0)) {
return 0.0;
}
else {
return -($entropy * count($s));
}
}
function testEntropy($s) {
pyjslib_printFunc(sprintf('Bits of entropy in \'%s\' is %.2f', new pyjslib_Tuple([$s, calcNumEntropyBits($s)])));
}
testEntropy('hello world');
testEntropy('bubba dubba');
testEntropy('aaaaaaaaaaa');
testEntropy('aaaaabaaaaa');
testEntropy('abcdefghijk');
It would not run correctly due to the math import and __contains__, but those would be easy enough to fix by hand.
I am about 1/2 way done making a PHP interpreter in Python and I can tell you flat out that there are literally dozens of major edge cases that play out to thousands of possibilities that would make it almost impossible to port Python to PHP. Python has a much more robust grammar then PHP while further foward in the language, Python's stdlib is probably one of the most advanced in comparison to any other language in it's class.
My recommendation is to take your question one step further back, to why do you need a set of Python based logic in PHP. Alternatives to attempting to port/translate your code could include subprocessing from PHP to Python, using Gearman to have Python do work in the backend while PHP handles view logic, or a much more involved solution would be to implement a service bus or message queue between a PHP application and Python services.
PS. Apologies for any readability issues, finishing a 2 day sprint just now.
No such tool exists, you'll have to port the code yourself
I changed the library py2php from https://github.com/dan-da/py2php and forked it into a new repository at https://github.com/bunkahle/py2php
You now can also use the python math library which is translated to PHP code. Still you have to do adaptations to your code in order to get it to work.
I wondered myself that same question, and I found this PyToPhp.py file in the GitHubGist site. It is simple, and seem an start point for the begining.
I'm going to take a look to it!!!

Categories