limit foreach results - foreach

I am working on a facebook app and I try to get user's friend list by zodiacal sign. However some of users have 20 friends on the same sign.. others 50 etc. and I want to limit the result to 10. I need some advices from an expert.
foreach($all_friends_profile as $profile)
{
$frzodie = star_sign($birthday);
$frname = $profile->name;
$frid = $profile->uid;
$comp = "<div class=\"mod_frm mod_frm_margin clearfix\">
<div class=\"pic\"><img src=\"https://graph.facebook.com/".$frid."/picture/\"></div>
<div class=\"meta\">".$frname."</div>
<div class=\"uiButton uiButtonSpecial\">Share</div></div>";
if (strpos($frzodie,$randZodie) !== false)
{
echo $comp; // **This must be limited to 10.**
}
}

$count = 0;
foreach(...) {
...
$count++;
if($count >= 10) {
break;
}
}

Related

Angular 11 Custom ISBN Validator Reactive Forms

I'm doing a custom validation for an ISBN number, I already have the function that checks the number and works perfect giving me the response by console, but I need to do the custom validator to get the error in the view with the form control and in this step this error is showing in console when I write an ISBN number, It's like it checks the errors but it doesn't know when its right and it should take the null response as a right ISBN number, at least thats what I saw in some examples.
core.js:6210 ERROR TypeError: Cannot read properties of null (reading 'CheckDigit')
at LibrosComponent_Template (libros.component.html:22)
at executeTemplate (core.js:9600)
at refreshView (core.js:9466)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
at refreshView (core.js:9516)
at refreshEmbeddedViews (core.js:10591)
at refreshView (core.js:9490)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
This is my typescript,
export class LibrosComponent implements OnInit {
//ISBN Validator
isbnValue: string = ""
firstFormGroup: FormGroup;
secondFormGroup: FormGroup;
constructor(
private _formBuilder: FormBuilder,
) {}
ngOnInit() {
this.firstFormGroup = this._formBuilder.group({
tituloControl: ['', Validators.required],
isbnControl: ['', Validators.required],
},
{ validator: this.isbnValidate });
}
isbnValidate(g: FormGroup) {
var isbnValue = g.get('isbnControl').value
var subject = isbnValue;
// Checks for ISBN-10 or ISBN-13 format
var regex = /^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$/;
if (regex.test(subject)) {
// Remove non ISBN digits, then split into an array
var chars = subject.replace(/[- ]|^ISBN(?:-1[03])?:?/g, "").split("");
// Remove the final ISBN digit from `chars`, and assign it to `last`
var last = chars.pop();
var sum = 0;
var check, i;
if (chars.length == 9) {
// Compute the ISBN-10 check digit
chars.reverse();
for (i = 0; i < chars.length; i++) {
sum += (i + 2) * parseInt(chars[i], 10);
}
check = 11 - (sum % 11);
if (check == 10) {
check = "X";
} else if (check == 11) {
check = "0";
}
} else {
// Compute the ISBN-13 check digit
for (i = 0; i < chars.length; i++) {
sum += (i % 2 * 2 + 1) * parseInt(chars[i], 10);
}
check = 10 - (sum % 10);
if (check == 10) {
check = "0";
}
}
if (check != last) {
return null;
} else {
return g.get('isbnControl').setErrors( {CheckDigit: true} )
}
} else {
return g.get('isbnControl').setErrors( {Invalid: true} );
}
}
}
In my HTML I have some inputs that are included in the form:
<form class="form" [formGroup]="firstFormGroup">
<div class="container-1">
<mat-form-field class="width">
<mat-label>Título</mat-label>
<input matInput formControlName="tituloControl" required>
</mat-form-field>
<mat-form-field class="width">
<mat-label>ISBN</mat-label>
<input matInput formControlName="isbnControl" required>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['CheckDigit']">Invalid ISBN check digit</mat-error>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['Invalid']">Invalid ISBN</mat-error>
</mat-form-field>
</form>
I already found the solution to the error, replacing the .errors [''] with hasError (''), the .errors[] is to read the property of the object that contains the validation error. But first I have to evaluate with the hasError () method if that property exists to access it.

Laravel share variable

I have a a few views: mobilepage1, mobilepage2, mobilepage3, mobilepage4 en 5.
First you go to mobilepage1 then hit button "next" and go to mobilepage2 etc.
In mobilepage2 i have a form where the user has to select a few options. Then a controller does a calculation and some variables are shared:
View::share('waarschijnlijkheid',$waarschijnlijkheid);
View::share('effect',$effect);
View::share('blootstellingsfreq',$blootstellingsfreq);
View::share('risico',$risico);
In mobilepage3 then these variables are displayed and that is done correctly.
After that you get mobilepage 4 and 5. In mobilepage5 i also want to show the same variables again. I get the error:
{"error":{"type":"ErrorException","message":"Undefined variable: waarschijnlijkheid (View: C:\\Google Drive\\htdocs\\laravel4_test4\\app\\views\\mobilepages\\mobilepage5.blade.php)","file":"C:\\Google Drive\\htdocs\\laravel4_test4\\app\\storage\\views\\49e12d376740da5fc90b17627351022b","line":25}}
I read here: Laravel 4 - understanding View::share()
that shared variables are accessable troughout the whole application. So why not in my final mobilepage5? Just to test this i made both views exactly the same.
This is the mobilepage5 and 3 snippet.
<td>{{$effect}}</td>
<td>x</td>
<td>{{$blootstellingsfreq}}</td>
<td>x</td>
<td>{{$waarschijnlijkheid}}</td>
<td>=</td>
<td>{{$risico}}</td>
<td>{{ '->'}}</td>
<td>{{$risicoklasse}}</td>
This is my route file:
Route::get('/', function(){
return View::make('mobilepages.login');
});
Route::post('login','MobileController#login');
Route::get('gotomobilepage1', function()
{
return View::make('mobilepages.mobilepage1', array('errormessages' => 'no messages'));
});
Route::get('mobilepage2', 'MobileController#save_firstpageform');
Route::post('gotomobilepage3', 'MobileController#save_andcalculaterisc');
Route::post('gotomobilepage4', function(){
return View::make('mobilepages.mobilepage4');
});
Route::post('gotomobilepage5', 'MobileController#gotomobilepage5function');
In my "save_andcalculaterisc" function calculate i share the variables.
public function save_andcalculaterisc()
{
$input = Input::all();
$waarschijnlijkheid = $input['radio_waarschijnlijkheid'];
$blootstellingsfreq = $input['radio_blootstellingsfreq'];
$effect = $input['radio_effect'];
$risico = $blootstellingsfreq*$effect*$waarschijnlijkheid;
View::share('waarschijnlijkheid',$waarschijnlijkheid);
View::share('effect',$effect);
View::share('blootstellingsfreq',$blootstellingsfreq);
View::share('risico',$risico);
//$safetyreport = Users::find(1)->safetyreports;
if($risico<=20){
$risicoklasse = "Risico wellicht aanvaardbaar: Aandacht dagelijks overleg";
} else if ($risico>20 && $risico <= 70){
$risicoklasse = "Mogelijk risico: Aandacht vereist";
} else if ($risico>70 && $risico <= 200) {
$risicoklasse = "Belangrijk risico: Maatregelen vereist";
}else if ($risico>200 && $risico <= 400) {
$risicoklasse = "Hoog risico: Direct verbetering vereist";
}else if ($risico >= 400) {
$risicoklasse = "Zeer hoog risico: Werkzaamheden stoppen";
}
else {
$risicoklasse = "Error risicoklasse";
}
View::share('risicoklasse',$risicoklasse);
// }
return View::make('mobilepages.mobilepage3');
}
Change this
View::share('waarschijnlijkheid',$waarschijnlijkheid);
View::share('effect',$effect);
View::share('blootstellingsfreq',$blootstellingsfreq);
View::share('risico',$risico);
To:
View::share(array('risico' => $risico, 'waarschijnlijkheid' => $waarschijnlijkheid, 'effect' => $effect, 'blootstellingsfreq' => $blootstellingsfreq ));
I think the issue is that you're using , instead of =>

Razor Escaping my html even if I use Html.Raw

I'm having a problem where my dynamically generated html is getting escaped and outputed on the screen. heres what I have:
#{
string TrialMessage = string.Empty;
if ((bool)ViewBag.msd.IsOnTrial == true)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var daysToTrialExpiation = expDate.AddDays(1) - System.DateTime.UtcNow;
TrialMessage = "<b>Trial Ends in: <span style=\"color:[Color];\">" + (daysToTrialExpiation.Days) + "</span> Days</b>";
if (daysToTrialExpiation.Days > 5)
{
TrialMessage = TrialMessage.Replace("[Color]", "green");
}
else if (daysToTrialExpiation.Days > 2)
{
TrialMessage = TrialMessage.Replace("[Color]", "orange");
}
else if (daysToTrialExpiation.Days > 0)
{
TrialMessage = TrialMessage.Replace("[Color]", "red");
}
else
{
TrialMessage = "<b style=\"color: red;\"> Trial Ended " + Math.Abs(daysToTrialExpiation.Days) + " Days Ago</b>";
}
}
}
When I use the TrialMessage in the View, I'm getting the escaped version of it outputted on the screen:
<b>Trial Ends in: <span style="color:green;">15</span> Days</b>
I have tried to use Html.Raw(TrialMessage) I've even tried to manually create an HTMLString with the same result. What am I missing?
Update: The way I'm outputting it on the view is:
#Html.Raw(TrialMessage)
In an effort to just get it working (it seems you're pressed for time) what if you removed html from the variable?
Perhaps something like this could work for you:
#{
string trialColor = string.Empty;
int trialDays = 0;
if ((bool)ViewBag.msd.IsOnTrial)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var trialDays = (expDate.AddDays(1) - System.DateTime.UtcNow).Days;
if (trialDays > 5)
{
trialColor = "green";
}
else if (trialDays > 2)
{
trialColor = "orange";
}
else
{
trialColor = "red";
}
}
}
...
#if((bool)ViewBag.msd.IsOnTrial && trialDays > 0)
{
<strong>Trial Ends in: <span style="color:#trialColor;">#trialDays </span> Days</strong>
} else if((bool)ViewBag.msd.IsOnTrial) {
<strong style="color: red;">Trial Ended #Math.Abs(trialDays) Days Ago</strong>
}
Note: untested code. It's been a bit since I've written razor.

Refresh tweets frequently in my site homepage without reaching to the rate limit

I am working on the site which needs real time tweets to be displayed to users. I have used Tweet Sharp library to fetch tweets.
My site needs tweets to be refreshed frequently, but sometimes I get {"The remote server returned an error: (429) Too Many Requests."} error.
As my site needs real time information, I have to fetch tweets frequently. How can I achieve this? How to get newest tweets without hitting to the Rate Limits?
TwitterService service=new TwitterService(AppSetting.objTwitterClientInfo.ConsumerKey, AppSetting.objTwitterClientInfo.ConsumerSecret, AppSetting.objTwitterModerateInfo.ModerateAccessToken, AppSetting.objTwitterModerateInfo.ModerateAccessTokenSecret);
var options = new ListTweetsOnHomeTimelineOptions();
options.ExcludeReplies = false;
options.Count = intTotalRec;
var lstTwitterStatus = service.ListTweetsOnHomeTimeline(options);
You can use the streaming api like this:-
public void Can_stream_from_user_stream() {
const int maxStreamEvents = 5;
var block = new AutoResetEvent(false);
var count = 0;
service.StreamUser((streamEvent, response) =>
{
if (streamEvent is TwitterUserStreamEnd)
{
block.Set();
}
if (response.StatusCode == 0)
{
if (streamEvent is TwitterUserStreamFriends)
{
var friends = (TwitterUserStreamFriends)streamEvent;
Assert.IsNotNull(friends);
Assert.IsNotNull(friends.RawSource);
Assert.IsTrue(friends.Ids.Any());
}
if (streamEvent is TwitterUserStreamEvent)
{
var #event = (TwitterUserStreamEvent)streamEvent;
Assert.IsNotNull(#event);
Assert.IsNotNull(#event.TargetObject);
Assert.IsNotNull(#event.RawSource);
Console.Write(#event.Event + "\n" + #event.Source + "\n" + #event.Target);
}
if (streamEvent is TwitterUserStreamStatus)
{
var tweet = ((TwitterUserStreamStatus)streamEvent).Status;
Assert.IsNotNull(tweet);
Assert.IsNotNull(tweet.Id);
Assert.IsNotNull(tweet.User);
Assert.IsNotNull(tweet.RawSource);
Assert.IsNotNull(tweet.User.ScreenName);
Console.WriteLine(tweet.User.ScreenName + "\n" + tweet.Text);
}
if (streamEvent is TwitterUserStreamDirectMessage)
{
var dm = ((TwitterUserStreamDirectMessage)streamEvent).DirectMessage;
Assert.IsNotNull(dm);
Assert.IsNotNull(dm.Id);
Assert.IsNotNull(dm.Sender);
Assert.IsNotNull(dm.Recipient);
Assert.IsNotNull(dm.RawSource);
Console.WriteLine(dm.SenderScreenName + "\n" + dm.RecipientScreenName + "\n" + dm.Text);
}
if (streamEvent is TwitterUserStreamDeleteStatus)
{
var deleted = (TwitterUserStreamDeleteStatus)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.StatusId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
if (streamEvent is TwitterUserStreamDeleteDirectMessage)
{
var deleted = (TwitterUserStreamDeleteDirectMessage)streamEvent;
Assert.IsNotNull(deleted);
Assert.IsTrue(deleted.DirectMessageId > 0);
Assert.IsTrue(deleted.UserId > 0);
}
count++;
if (count == maxStreamEvents)
{
block.Set();
}
}
else
{
Assert.Ignore("Stream responsed with status code: {0}", response.StatusCode);
}
});
block.WaitOne();
service.CancelStreaming();
}

gmaps4rails show hide functionality

I'm hoping to get a little bit of insight on show / hide functionality in gmaps4rails.
example functionality
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
makeSidebar();
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = html;
}
So, in my controller, I'm building a list of markers, and including their categories as json.
#markersLoc = #locSearch.to_gmaps4rails do |loc, marker|
letter.next!
marker_image = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=#{letter}|82ABDD|000000"
marker.infowindow render_to_string(partial: '/events/info',
locals: {object: loc})
marker.picture({picture: marker_image,
width: 32,
height: 32,
marker_anchor: [11,30],
shadow_picture: "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
shadow_width: 110,
shadow_height: 110,
shadow_anchor: [12,34]})
marker.title loc.what
marker.sidebar render_to_string(partial: '/events/sidebar',
locals: {object: loc, letter: marker_image})
marker.json({cat: loc.category})
end
I'm kind of stuck, here. I know the :cat string is available (ex: 1,3,4), but I'm not sure how to use it to achieve what I'm after.
Was able to pretty much use what was there, with some modification. This gave me functionality to have 9 categories (could be more or less), and only view what I want. Awesome.
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
var regEx = new RegExp("[" + category + "]")
for (var i=0; i<Gmaps.map.markers.length; i++) {
if (Gmaps.map.markers[i].cat) {
if (Gmaps.map.markers[i].cat.match(regEx)) {
Gmaps.map.showMarker(Gmaps.map.markers[i]);
}
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
var regEx = new RegExp("[" + category + "]")
for (var i=0; i<Gmaps.map.markers.length; i++) {
if (Gmaps.map.markers[i].cat) {
if (Gmaps.map.markers[i].cat.match(regEx)) {
Gmaps.map.hideMarker(Gmaps.map.markers[i]);
}
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
// Gmaps.map.infowindow.close();
}
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
}

Resources