How to truncate filename from end with limit - php

Let's say we have three file names:
var a = "01704_0047a_05a_canvas.jpg";
var b = "101704_0047a_05a_canvas.jpg";
var c = "foo.jpg";
Obviously the three are 1 character different, this is just to illustrate that the filenames will vary in length, what I'm aiming to do, is only display the last 10 characters from the end, regardless of the length of the filename, Results:
var a = "canvas.jpg";
var b = "canvas.jpg";
var c = "foo.jpg";
here's what I've tried:
a.substring(a.length, 10);
This seems to give me different results thought, ideas?
I also need to mimic the same result in php if someone feels generous!

Javascript
var a = "01704_0047a_05a_canvas.jpg";
console.log(a.substr(-10)); // OR a.substring(a.length - 10, a.length);
PHP
$a = "01704_0047a_05a_canvas.jpg";
echo substr($a, -10);
References:
Javascript
[substr] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
[substring] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
PHP
[substr] http://php.net/substr

Related

creating unique random string

I am working in php and I am trying to create 1000 tickets in a database. Each ticket needs it's own unique code that consists of letters and numbers about 6 characters long.
EXP.
Tbl_Tickets
ID code
1 3F2jk7
2 2HGUF1
3 9FJDNJ
4 MFJEY9
5 23988D
I was wondering is there a simple way of doing this with php, or excel, or any other way for that matter. I know that i can use a random number generator, but the check for the Unique would have a large BigO notation and the check would get messy.
Unique is not compatible with random, but the following might suit:
=CHOOSE(RANDBETWEEN(1,2),RANDBETWEEN(0,9),CHAR(RANDBETWEEN(65,90)))
copied across to populate six columns (say A to F) with, in G:
=A1&B1&C1&D1&E1&F1
and both copied down to say row 1100. Then select G, copy Paste Special Values, and Remove Duplicates on ColumnG and select first 1000 entries.
You could easily create an array of strings in php and write it to a database:
function generateRandomString($length = 6, $letters = '1234567890QWERTYUIOPASDFGHJKLZXCVBNM'){
$s = '';
$lettersLength = strlen($letters)-1;
for($i = 0 ; $i < $length ; $i++){
$s .= $letters[rand(0,$lettersLength)];
}
return $s;
}
// Create an array with random strings
for ($i=0; $i<1000; $i++){
$ticket_numbers = array();
$ticket_number = generateRandomString();
while (in_array($ticket_number,$ticket_numbers))
$ticket_number = generateRandomString();
$ticket_numbers[] = $ticket_number;
}
// Write the array to a database
$con = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error");
foreach ($ticket_numbers as $number){
mysqli_query($con,"Your insert query using the value $number");
}
mysqli_close($con);
This should help you in the right direction though there are probably better ways to do this.
The function generateRandomString() was taken from How to generate random numbers/letters with PHP/Javascript
And another option. Encryption is guaranteed to be unique, so encrypting the numbers 0, 1, 2, ... will give you guaranteed unique random-seeming output. Six characters is 30 bits using Base32, or 36 bits using Base64. You will need a 30 (or 36 bit) cypher. Unless you have a library that includes Hasty Pudding cypher (unlikely) then just implement a simple four round Feistel cypher with the appropriate block size. It will not be completely secure, but it will be enough to defeat casual attacks.
This will produce random strings in column B with no repeats from B1 thru B1001
Sub Lottery()
Dim i As Long, j As Long, c As Collection
Set c = New Collection
v = Split("0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z", ",")
For i = 1 To 5000
can = ""
For j = 1 To 6
can = can & v(Application.RandBetween(0, 35))
Next j
On Error Resume Next
c.Add can, CStr(can)
On Error GoTo 0
If c.Count = 1000 Then Exit For
Next i
For i = 1 To 1000
Cells(i + 1, 2).Value = c(i)
Next i
End Sub

Jquery replace number in fixed location

I am writing a function which is used to replace the class of div in certain conditions, for example,
condition A - the div class is e_new_hazard_frame_2_1_4_7, I want to replace the 2 to 1, outcome should be like this - e_new_hazard_frame_1_1_4_7
condition B - the div class is the same with above, I want to replace the 1 to 4, outcome should be like this - e_new_hazard_frame_2_4_4_7
condition C - the div class is the same with above, I want to replace the 4 to 6, outcome should be like this - e_new_hazard_frame_2_1_6_7
condition D - the div class is the same with above, I want to replace the 7 to 3, outcome should be like this - e_new_hazard_frame_2_1_4_3
these 4 numbers might be the same, like 1_1_1_1, my demo coding is like
var str = 'e_new_hazard_frame_2_1';
str = str.replace(/_[_0-9]*)$/,'1');
it seems not correct can anyone teach me how to do it? thank you so much!
Try this one.It may help you.
<div class="e_new_hazard_frame_2_1_4_7">click to change value</div>
<script type="text/javascript">
$(".e_new_hazard_frame_2_1_4_7").on('click',function(){
change_class(7); //change the value from here i.e 2,4,1,7
});
function change_class(p)
{
var number_change=p;
switch (number_change)
{
case 2:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[2]/g,'1');
break;
case 1:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[1]/g,'4');
break;
case 4:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[4]/g,'6');
break;
case 7:
var str='e_new_hazard_frame_2_1_4_7';
str = str.replace(/[7]/g,'3');
break;
}
$(".e_new_hazard_frame_2_1_4_7").html(str);
}
</script>
Please let me know if you face any problem.
Maybe use a function to handle the numbers however you want?
replace Javascript | MDN
function replacer(match, p1, p2, p3, p4, offset, string){
// p1-4 are your numbers
// (they are strings right now, sto make +p1 to convert them to int)
p1= +p1 + 1;
p2= +p2 + 1;
p3= +p3 + 1;
p4= +p4 + 1;
// fixed a small bug here
return ['', p1, p2, p3, p4].join('_');
};
var str = "asdasdasd_1_2_3_4";
str = str.replace(/_(\d)_(\d)_(\d)_(\d)/, replacer);
This will replace all occurrence of 2 to 1 in str:
var str = 'e_new_hazard_frame_2_1_2_4';
str = str.replace(/2/g,'1');
To replace the class of your div:
var target_class = 'e_new_hazard_frame_2_1_4_7';
$('.'+target_class).removeClass(target_class).addClass(target_class.replace(/2/g,'1'))
In PHP
echo str_replace("2","1","e_new_hazard_frame_2_1_4_7");
For more reference visit this. Hope this will help you.
In JavaScript
str.replace("e_new_hazard_frame_2_1_2_4","e_new_hazard_frame_1_1_2_4");
For more reference visit this
I think it might be useful to you
`str='e_new_hazard_frame_2_1';
if(conditin1)
{
pattern = /[2]/g;
str = str.replace(pattern,'1');
}
if(conditin2)
{
pattern = /[1]/g;
str = str.replace(pattern,'4');
}
if(conditin3)
{
pattern = /[4]/g;
str = str.replace(pattern,'6');
}
if(conditin4)
{
pattern = /[7]/g;
str = str.replace(pattern,'3');
}`

Build 2D Array of Canvas RGB values

I'm trying to send a 2D array of RGB values to PHP from the array of values from the getImageData().data method:
for (var i=0;i<imgData.data.length;i+=4){
// If you want to know the values of the pixel
var r = imgData.data[i + 0];
var g = imgData.data[i + 1];
var b = imgData.data[i + 2];
var a = imgData.data[i + 3];
//[...] do what you want with these values
}
From this, how would I create a 2D array of RGB values of an entire canvas?
var rgb = [];
for (var i=0;i<imgData.data.length;i+=4){
// If you want to know the values of the pixel
var r = imgData.data[i + 0];
var g = imgData.data[i + 1];
var b = imgData.data[i + 2];
var a = imgData.data[i + 3];
var x = Math.floor((i/4) % imageData.width);
var y = Math.floor((i/4) / imageData.width);
rgb[x] ? (rgb[x][y] = [r,b,g,a]) : (rgb[x] = [[r,b,g,a]]);
}
This may not be what you want, but if your concern is transferring the image data (not necessarily building an array on the client side), toDataURL() might be an even simpler way to transfer your image data...
The HTML5 canvas.toDataURL('image/png') method will produce a data URI for your image data - i.e. a really long, text-encoded version of the PNG. No need to grab the image data manually. Likewise, you could use a JPEG encoding if that's preferable.
If you send this string to the server, PHP can decoded back to binary form directly by passing it as the first argument to file_get_contents() (i.e. $binary = file_get_contents($dataURL)). You can then save this to disk or do whatever you want with the binary PNG data as you would with a file you had just loaded off disk.

Unidentified Error in Program: Unfriendly Numbers

There is a problem in Interview Street challange. Maybe the most easiest of all challenges. "Unfriendly Numbers", is the name and question goes like this.
There is one friendly number and N unfriendly numbers. We want to find how many numbers are there which exactly divide the friendly number, but does not divide any of the unfriendly numbers.
Input Format:
The first line of input contains two numbers N and K seperated by spaces. N is the number of unfriendly numbers, K is the friendly number.
The second line of input contains N space separated unfriendly numbers.
Output Format:
Output the answer in a single line.
I did a PHP programming like this:
<?php
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$handle = fopen ("php://stdin","r");
$input = fgets($handle);
$num_unfriendly_number=substr($input,0,1);
$friendly_number=substr($input,2,1);
$input2=fgets($handle);
for($i=0;$i<=($num_unfriendly_number); $i=$i+2){
$unfriendly_numbers[$i]=substr($input2,$i,1);
}
//truncates additional input
//now getting divisiors of given friendly numbers
$check_num=1;
//one is always a divisor of any number
$divisior[0]=1;
$arrayindex=1;
for($check_num; $check_num<=$friendly_number; $check_num++){
$hold_var=$friendly_number%$check_num;
if($hold_var==0){
$divisor[$arrayindex]=$check_num;
$arrayindex++;
}
}
$index=0;
foreach($divisor as $test_div){
$output=true;
foreach($unfriendly_numbers as $test_unfrnd){
if($test_unfrnd%$test_div){
$output=false;
}
}
if ($output){
$outputarray[$index]=$test_div;
$index++; //edited afterwards after #Boris's suggestion but didn't work :(
}
}
$num_of_output=count($outputarray);
define('STDOUT',fopen("php://stout","r"));
fwrite(STDOUT,$num_of_output);
?>
The above programme worked fine for 2 testcases but did not applied for other tests. I did some research but did not found any errors. Any helps please. Thanks in advance.
Fist of all I would like to mention that I do not know php. However, I think this is simple enough I can try to help.
Several errors I see:
for($i=0;$i<=($num_unfriendly_number); $i=$i+2){
$unfriendly_numbers[$i]=substr($input2,$i,1);
}
Here you use substr($input2,$i,1);, this however assumes all your unfriendly numbers are digits, which might not always be the case. Better use the split function in php. Replace the whole while with the following:
$unfriendly_numbers = explode(" ", $input2);
After that:
$index=0;
foreach($divisor as $test_div){
$output=true;
foreach($unfriendly_numbers as $test_unfrnd){
if($test_unfrnd%$test_div){
$output=false;
}
}
if ($output){
$outputarray[$index]=$test_div;
}
}
Here you never increase the $index variable. Isn't this meaning that you will override the divisors one with other? USe the operator []=. It appends to an array in php:
if ($output){
$outputarray []= $test_div;
}
EDIT One more error I see is that you count on the friendly number to be a digit too. You can fix this too:
$friendly_number=substr($input,2,1);
->
$friendly_number=explode(" ", $input)[0];
I have the same problem I can't understand why this code can't finish in less than 16 seconds!
I would like to hear your tricks
a = raw_input()# this will read this line: 8 16
b = raw_input()# this will read this line: 2 5 7 4 3 8 3 18
al = a.split()
bl = b.split()
blint = []
fn = int(al[1])
fnlist = [fn]
half_fn = fn / 2 # only I go to half the number to save some time
k = 1
while k <= half_fn:
if fn % k == 0:
fnlist.append(k)
k += 1
plist = []
for j in bl:
blint.append(int(j)) # here I changed the bl list elements which are string to int
for i in fnlist:
for j in blint: #I have the int elements so I don't need every time bring the string and change it to int
if j % i == 0:
plist.append(i)
break
counter = len(fnlist) - len(plist)
print counter

Listing by alphabet, groups letters with few entries together (PHP or JS)

I am working on a Web Application that includes long listings of names. The client originally wanted to have the names split up into divs by letter so it is easy to jump to a particular name on the list.
Now, looking at the list, the client pointed out several letters that have only one or two names associated with them. He now wants to know if we can combine several consecutive letters if there are only a few names in each.
(Note that letters with no names are not displayed at all.)
What I do right now is have the database server return a sorted list, then keep a variable containing the current character. I run through the list of names, incrementing the character and printing the opening and closing div and ul tags as I get to each letter. I know how to adapt this code to combine some letters, however, the one thing I'm not sure about how to handle is whether a particular combination of letters is the best-possible one. In other words, say that I have:
A - 12 names
B - 2 names
C - 1 name
D - 1 name
E - 1 name
F - 23 names
I know how to end up with a group A-C and then have D by itself. What I'm looking for is an efficient way to realize that A should be by itself and then B-D should be together.
I am not really sure where to start looking at this.
If it makes any difference, this code will be used in a Kohana Framework module.
UPDATE 2012-04-04:
Here is a clarification of what I need:
Say the minimum number of items I want in a group is 30. Now say that letter A has 25 items, letters B, C, and D, have 10 items each, and letter E has 32 items. I want to leave A alone because it will be better to combine B+C+D. The simple way to combine them is A+B, C+D+E - which is not what I want.
In other words, I need the best fit that comes closest to the minimum per group.
If a letter contains more than 10 names, or whatever reasonable limit you set, do not combine it with the next one. However, if you start combining letters, you might have it run until 15 or so names are collected if you want, as long as no individual letter has more than 10. That's not a universal solution, but it's how I'd solve it.
I came up with this function using PHP.
It groups letters that combined have over $ammount names in it.
function split_by_initials($names,$ammount,$tollerance = 0) {
$total = count($names);
foreach($names as $name) {
$filtered[$name[0]][] = $name;
}
$count = 0;
$key = '';
$temp = array();
foreach ($filtered as $initial => $split) {
$count += count($split);
$temp = array_merge($split,$temp);
$key .= $initial.'-';
if ($count >= $ammount || $count >= $ammount - $tollerance) {
$result[$key] = $temp;
$count = 0;
$key = '';
$temp = array();
}
}
return $result;
}
the 3rd parameter is used for when you want to limit the group to a single letter that doesn't have the ammount specified but is close enough.
Something like
i want to split in groups of 30
but a has 25
to so, if you set a tollerance of 5, A will be left alone and the other letters will be grouped.
I forgot to mention but it returns a multi dimensional array with the letters it contains as key then the names it contains.
Something like
Array
(
[A-B-C-] => Array
(
[0] => Bandice Bergen
[1] => Arey Lowell
[2] => Carmen Miranda
)
)
It is not exactly what you needed but i think it's close enough.
Using the jsfiddle that mrsherman put, I came up with something that could work: http://jsfiddle.net/F2Ahh/
Obviously that is to be used as a pseudocode, some techniques to make it more efficient could be applied. But that gets the job done.
Javascrip Version: enhanced version with sort and symbols grouping
function group_by_initials(names,ammount,tollerance) {
tolerance=tollerance||0;
total = names.length;
var filtered={}
var result={};
$.each(names,function(key,value){
val=value.trim();
var pattern = /[a-zA-Z0-9&_\.-]/
if(val[0].match(pattern)) {
intial=val[0];
}
else
{
intial='sym';
}
if(!(intial in filtered))
filtered[intial]=[];
filtered[intial].push(val);
})
var count = 0;
var key = '';
var temp = [];
$.each(Object.keys(filtered).sort(),function(ky,value){
count += filtered[value].length;
temp = temp.concat(filtered[value])
key += value+'-';
if (count >= ammount || count >= ammount - tollerance) {
key = key.substring(0, key.length - 1);
result[key] = temp;
count = 0;
key = '';
temp = [];
}
})
return result;
}

Categories