public function postAudit($entry)
 {
     $entry_name = lcfirst(get_class($entry));
     if ($entry->id) {
         $comment = \Input::get('comment');
         $nextAuditUserIds = \Input::get('audit_users');
         $nextAuditUsers = new \Illuminate\Database\Eloquent\Collection();
         if ($nextAuditUserIds && count($nextAuditUserIds) > 0) {
             foreach ($nextAuditUserIds as $id) {
                 $nextAuditUsers->add(\User::find($id));
             }
         }
         $submit = \Input::get('submit');
         switch ($submit) {
             case 'agree':
                 $result = $entry->agree($comment, $nextAuditUsers, $entry->getLogTitle(), $entry->getLogContent());
                 break;
             case 'discard':
                 $result = $entry->disagree($entry_name . '::discard', $comment, $entry->getLogTitle(), $entry->getLogContent());
                 break;
             case 'gofirst':
                 $result = $entry->disagree($entry_name . '::goFirst', $comment, $entry->getLogTitle(), $entry->getLogContent());
                 break;
         }
         if ($result) {
             return \Redirect::to('admin/' . $this->entryName . '/' . $entry->id . '/edit')->with('success', \Lang::get('workflow::workflow.action') . \Lang::get('workflow::workflow.success'));
         } else {
             return \Redirect::to('admin/' . $this->entryName . '/' . $entry->id . '/edit')->with('error', \Lang::get('workflow::workflow.action') . \Lang::get('workflow::workflow.failed_unknown'));
         }
     }
     return \Redirect::to('admin/' . $this->entryName . '')->with('error', \Lang::get('admin/' . $this->entryName . '/messages.does_not_exist'));
 }
Exemple #2
0
 public function userWords($box = null)
 {
     $groups = Auth::user()->groups;
     $words = new \Illuminate\Database\Eloquent\Collection();
     foreach ($groups as $group) {
         foreach ($group->words as $word) {
             $words->add($word);
         }
     }
     $userWords = Auth::user()->words;
     /* replace all the words, which are already in the list and also in user_word, to get the correct statistic numbers */
     $userWords->each(function ($word) use($words) {
         if ($words->contains($word->id)) {
             $words->find($word->id)->pivot = $word->pivot;
         }
     });
     $words = $this->sortById($words);
     if ($box == null) {
         /* if no box is selected, return all words the user has selected */
         return $words;
     } else {
         $results = new \Illuminate\Database\Eloquent\Collection();
         $words->each(function ($word) use($results, $groups, $box) {
             if ($groups->contains($word->group_id) && $word->box == $box) {
                 $results->add($word);
             }
         });
         return $results;
     }
 }
 protected function makeNewCollection($add = null)
 {
     $collection = new \Illuminate\Database\Eloquent\Collection();
     if (!is_null($add)) {
         $collection->add($add);
     }
     return $collection;
 }
 public function testFilter()
 {
     $this->initDB();
     $exitCode = Artisan::call('ticket:list', ['--filter' => $this->ticketList->get(0)->id]);
     $this->assertEquals($exitCode, 0);
     $output = Artisan::output();
     $this->assertContains($this->ticketList->get(0)->ip, $output);
     $this->assertNotContains($this->ticketList->get(1)->domain, $output);
 }
 /**
  * @param array $overrides
  * @param int $amount
  *
  * @return \Hootlex\Moderation\Tests\Post
  */
 function createPost($overrides = [], $amount = 1)
 {
     $posts = new \Illuminate\Database\Eloquent\Collection();
     for ($i = 0; $i < $amount; $i++) {
         $post = Post::create(array_merge(['moderated_at' => 0], $overrides));
         $posts->push($post);
     }
     return count($posts) > 1 ? $posts : $posts[0];
 }
Exemple #6
0
 /**
  * Get suites for a set of runs. /
  */
 public function getSuites($runs)
 {
     // Get all the test suites
     $results = new \Illuminate\Database\Eloquent\Collection();
     foreach ($runs as $run) {
         $results->add();
     }
     return $runs->getRunsWithinXDays(90);
 }
 public function testWithValidIdFilter()
 {
     $this->initDB();
     $exitCode = Artisan::call('note:show', ['note' => $this->noteList->get(0)->id]);
     $this->assertEquals($exitCode, 0);
     $output = Artisan::output();
     foreach (['Id', 'Ticket id', 'Submitter', 'Text', 'Hidden', 'Viewed'] as $el) {
         $this->assertContains($el, $output);
     }
 }
Exemple #8
0
 /**
  * Display the specified game.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     $game = Game::withTrashed()->findOrfail($id);
     $seats = new \Illuminate\Database\Eloquent\Collection();
     foreach (range(1, $game->seats) as $index) {
         $player = $game->players()->where('seat', $index)->first();
         $seats->add($player);
     }
     return View::make('games.show', compact('game', 'seats'));
 }
 /**
  * Create billets.
  *
  * @param  Illuminate\Database\Eloquent\Collection $students
  * @param  string $refer YYYYMM
  *
  * @return void
  */
 public function createBillets($students, $refer)
 {
     $students->each(function ($student) use($refer) {
         $exists = $student->whereHas('billets', function ($q) use($refer, $student) {
             $q->where('refer', $refer)->where('student_id', $student->id)->select('id');
         })->exists();
         if (!$exists) {
             $this->createBillet($student, $refer);
         }
     });
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $trips = Auth::user()->TripPlans()->get();
     //instantiate as a Collection so that I don't have to use array notation in the view
     $activeTrips = new \Illuminate\Database\Eloquent\Collection();
     foreach ($trips as $trip) {
         if ($trip->active == 1) {
             $activeTrips->add($trip);
         }
     }
     return view('trips.index', compact(['trips', 'activeTrips']));
 }
Exemple #11
0
 /**
  * Return any question id's and warnings if a question does not have exactly 1 correct answer
  *
  * @return collection
  */
 public function warnings()
 {
     $warnings = new \Illuminate\Database\Eloquent\Collection();
     $questions = Question::where('quiz_id', '=', $this->id)->get();
     foreach ($questions as $question) {
         $number_of_correct_answers = $question->numberOfCorrectAnswers();
         if ($number_of_correct_answers != 1) {
             $warning = 'Question has ' . $number_of_correct_answers . ' correct answers!';
             $warnings->put($question->id, $warning);
         }
     }
     return $warnings;
 }
 /**
  * return an Authentificate User with role(s)
  * @param  string|array $rolesNames Role(s) to add to the user
  * @return UserInterface
  */
 protected function getUserWithRole($rolesNames = null)
 {
     $rolesNames = (array) $rolesNames;
     $roles = new \Illuminate\Database\Eloquent\Collection();
     foreach ($rolesNames as $index => $roleName) {
         $role = m::mock('Eloquent', 'AcRole')->makePartial();
         $roleAttributes = ['id' => $index + 1, 'name' => $roleName];
         foreach ($roleAttributes as $key => $value) {
             $role->{$key} = $value;
         }
         $roles->add($role);
     }
     return $this->getUser($roles);
 }
Exemple #13
0
 public function buildForm()
 {
     $this->add('name', 'text', ['label' => trans('front.domain.domain_name'), 'required' => true, 'attr' => ['class' => 'form-control col-md-4']])->add('zone_id', 'entity', ['label' => trans('front.domain.domain_extension'), 'class' => 'DomainProvider\\Models\\Zone', 'property' => 'name', 'property_key' => 'id', 'query_builder' => function (Zone $zone) {
         $dbZones = Cache::remember('enabled_zones', env('CACHE_REMEMBER', 10), function () use($zone) {
             return $zone::where('enabled', true)->get();
         });
         $zones = new \Illuminate\Database\Eloquent\Collection();
         foreach ($dbZones as $zone) {
             $zone->name = '.' . $zone->name;
             $zones->add($zone);
         }
         return $zones;
     }, 'attr' => ['class' => 'selectpicker form-control']])->add('submit', 'submit', ['label' => trans('button.register'), 'attr' => ['class' => 'btn btn-action btn-lg-normal']]);
 }
 public function postSearchUser(Request $request)
 {
     $keywords = $request->input('keywords');
     $users = User::all();
     $searchUsers = new \Illuminate\Database\Eloquent\Collection();
     if ($keywords == null) {
         return view::make('admin.searchedUsers')->with('searchUsers', $users);
     }
     foreach ($users as $user) {
         if (Str_contains(Strtolower($user->username), Strtolower($keywords))) {
             $searchUsers->add($user);
         }
     }
     return view::make('admin.searchedUsers')->with('searchUsers', $searchUsers);
 }
Exemple #15
0
 /**
  * Get time line by event ID
  *
  * @param int $id
  *
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function getByEventId($id)
 {
     $time_line = new \Illuminate\Database\Eloquent\Collection();
     $get = self::where('events_time_line.event_id', (int) $id)->select('events_messages.message', 'events_comments.comment', 'events_comments.user_id', \DB::raw('concat(profiles.firstname, " ", profiles.lastname) as user_name'), 'profiles.avatar_url', 'events_time_line.id as time_line_id', 'events_time_line.time as time', 'events_time_line.type as type')->leftjoin('events_messages', 'events_messages.id', '=', 'events_time_line.message_id')->leftjoin('events_comments', 'events_comments.id', '=', 'events_time_line.comment_id')->leftjoin('profiles', 'profiles.user_id', '=', 'events_comments.user_id')->groupBy('events_time_line.id')->orderBy('events_time_line.id', 'desc')->get();
     foreach ($get as $row) {
         switch ($row->type) {
             case 'message':
                 $time_line->push(new Message($row));
                 break;
             case 'comment':
                 $time_line->push(new Comment($row));
                 break;
         }
     }
     return $time_line;
 }
 public function postSearch(Request $request)
 {
     $keywords = \Request::input('keywords');
     $tag = Tag::findOrFail($request->tag);
     $courses = $tag->courses()->published()->done()->latest('published_at')->get();
     $searchCourses = new \Illuminate\Database\Eloquent\Collection();
     if ($keywords == null) {
         return view::make('courses.searchedCourses')->with('searchCourses', $courses);
     }
     foreach ($courses as $course) {
         if (Str_contains(Strtolower($course->title), Strtolower($keywords))) {
             $searchCourses->add($course);
         }
     }
     return View::make('courses.searchedCourses')->with('searchCourses', $searchCourses);
 }
    public function mostrar_status()
    {
        //$solicitud_status = Status_Solicitud::all()->max('solicitud_status_fecha');
        /*$solicitud_status = DB::table('solicitud_status')
        		->whereIn('id', function($query)
        		    {
        		        $query->select(DB::raw(1))
        		              ->from('orders')
        		              ->whereRaw('orders.user_id = users.id');
        		    })
        		    ->get();*/
        //$query = select(DB::raw('pk_fk_solicitud_informacion from solicitud_status where pk_fk_solicitud_informacion = 9'));
        $solicitud_status = Status_Solicitud::select(array(DB::raw('max(solicitud_status_fecha) as fecha'), 'pk_fk_solicitud_informacion as si'))->groupBy('pk_fk_solicitud_informacion')->get();
        // Eloquent Builder instance
        //$solicitud_status = array($solicitud_status);
        $raw_result = DB::select('SELECT te.* FROM (select max(ss.solicitud_status_fecha)as FECHA , 
		    			ss.pk_fk_solicitud_informacion from solicitud_status as ss, solicitud_informacion as si , 
		    			status as s where ss.pk_fk_solicitud_informacion = si.id and ss.pk_fk_status = s.id group by ss.pk_fk_solicitud_informacion) AS t, solicitud_status AS te
		    		WHERE te.pk_fk_solicitud_informacion = t.pk_fk_solicitud_informacion AND te.solicitud_status_fecha = t.FECHA
		    		ORDER BY te.solicitud_status_fecha desc;');
        $collection = new \Illuminate\Database\Eloquent\Collection();
        foreach ($raw_result as $raw_obj) {
            $model = new Status_Solicitud();
            $collection->add($model->newFromBuilder($raw_obj));
        }
        //$new = Status_Solicitud::where('id','=',$collection->id);
        /*				$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
        				    ->mergeBindings($sub->getQuery()) // you need to get underlying Query Builder
        				    ->count();
        */
        /*
        				    DB::table('solicitud_status')
        						  ->select(
        						      array('id',DB::raw('concat(SUBSTRING_INDEX(description, " ",25),"...") AS description'),'category'))
        						  ->order_by(\DB::raw('RAND()'))
        						  ->get();*/
        /* SELECT te.* 
        
        FROM (select max(ss.solicitud_status_fecha)as FECHA , ss.pk_fk_solicitud_informacion from solicitud_status as ss, solicitud_informacion as si , status as s
        where ss.pk_fk_solicitud_informacion = si.id and ss.pk_fk_status = s.id
        group by ss.pk_fk_solicitud_informacion) AS t, solicitud_status AS te
        
        WHERE te.pk_fk_solicitud_informacion = t.pk_fk_solicitud_informacion AND te.solicitud_status_fecha = t.FECHA
        */
        return View::make('solicitud_status.listaSolicitudStatus', array('collection' => $collection));
    }
 /**
  * Admin view
  */
 public function index()
 {
     $initialCategories = Category::whereNull('parent_id')->with(['categories' => function ($query) {
         $query->orderBy('weight', 'desc')->orderBy('id');
     }])->orderBy('weight', 'desc')->orderBy('id')->paginate();
     $links = $initialCategories->links();
     $result = new \Illuminate\Database\Eloquent\Collection();
     $initialCategories->each(function ($category) use($result) {
         $result->push($category);
         $category->categories->each(function ($category) use($result) {
             $result->push($category);
         });
     });
     $result->load('parent');
     //		dd($result);
     return View::make('admin.dicts.list', ['title' => 'Категории', 'columns' => ['ID', 'Родитель', 'Вес', 'Заголовок', 'Описание', 'Под', 'Посты', 'Ком', 'посты', '', ''], 'data' => $result->transform(function ($category) use($links) {
         return ['id' => $category->id, 'parent_id' => $category->parent_id ? "{$category->parent->title} ({$category->parent_id})" : '', 'weight' => $category->weight . ' ' . link_to("admin/categories/{$category->id}/up", "&uarr;") . ' ' . link_to("admin/categories/{$category->id}/down", "&darr;"), 'title' => $category->title, 'description' => $category->description, 'subscriptions' => $category->subscriptions_count, 'posts_count' => $category->posts_count, 'comments' => $category->comments_count, 'posts' => link_to("/admin/categories/{$category->id}/posts", 'посты &rarr;'), 'edit' => link_to("/admin/categories/{$category->id}/edit", 'редактировать'), 'delete' => link_to("/admin/categories/{$category->id}/delete", 'удалить')];
     }), 'links' => $links, 'actions' => [['link' => '/admin/categories/create', 'text' => 'Добавить']]]);
 }
 /**
  * Interactively ask the user to enter currencies
  *
  * @return array
  */
 protected function askCurrencies()
 {
     $this->showCurrenciesList();
     $answer = $this->ask("Enter 'all' or a space separated list of ids/codes to enable: ");
     if (trim($answer) === 'all') {
         return $this->allCurrencies->pluck('id')->all();
     }
     // Filter input
     $answer = array_map('strtoupper', array_filter(array_map('trim', explode(' ', $answer))));
     // Loop until the user enters something
     if (!$answer) {
         return $this->askCurrencies();
     }
     return $answer;
 }
 public function testFilterProductsReturnsProductsSortedPerIndexResponse()
 {
     $index_response_stub = ['meta' => ['total_hits' => 2], 'results' => [['_id' => 2], ['_id' => 1]], 'facets' => ['foobar']];
     $find_many_params_stub = [2, 1];
     $product_suite_response = new \Illuminate\Database\Eloquent\Collection();
     $product_suite_response->add(Factory::make('Giftertipster\\Entity\\Eloquent\\Product', ['id' => 2, 'title' => 'foobar title']));
     $product_suite_response->add(Factory::make('Giftertipster\\Entity\\Eloquent\\Product', ['id' => 1, 'title' => 'foobar title']));
     $expected_response = ['meta' => ['total_hits' => 2], 'results' => [['is_refreshed' => 1, 'id' => 2, 'title' => 'foobar title'], ['is_refreshed' => 1, 'id' => 1, 'title' => 'foobar title']], 'facets' => ['foobar']];
     $index_repo_mock = Mockery::mock('Giftertipster\\Repository\\ProductsIndex\\Product\\ProductsIndexProductRepositoryInterface');
     $index_repo_mock->shouldReceive('filterProducts')->with(0, 2, ['FilterName' => ['filter params' => 'foobar']])->once()->andReturn($index_response_stub);
     $this->app->instance('Giftertipster\\Repository\\ProductsIndex\\Product\\ProductsIndexProductRepositoryInterface', $index_repo_mock);
     $product_suite_mock = Mockery::mock('Giftertipster\\Repository\\ProductSuite\\ProductSuiteRepositoryInterface');
     $product_suite_mock->shouldReceive('findMany')->with($find_many_params_stub, true)->andReturn($product_suite_response);
     $this->app->instance('Giftertipster\\Repository\\ProductSuite\\ProductSuiteRepositoryInterface', $product_suite_mock);
     $this->service = $this->app->make('Giftertipster\\Service\\ProductSuite\\ProductSuiteFromIndexFetcher');
     //offset, limit, array of filters
     $response = $this->service->filterProducts(0, 2, ['FilterName' => ['filter params' => 'foobar']]);
     assertThat($response, identicalTo($expected_response));
 }
 protected function buildModel($modelAttributes = null)
 {
     $modelAttributes = $modelAttributes ?: $this->modelAttributes;
     $mock = $this->mock($this->modelName);
     $model = $this->fillMock($mock, $modelAttributes);
     $mock->shouldReceive('where->firstOrFail')->andReturn($model);
     $mock->shouldReceive('save')->andReturn(true);
     $models = new Illuminate\Database\Eloquent\Collection();
     $models->add($model);
     $mock->shouldReceive('get')->andReturn($models);
     $mock->shouldReceive('all')->andReturn($models);
     return $model;
 }
 /**
  * Show a list with all available languages
  *
  * @return void
  */
 protected function showLanguagesList()
 {
     $this->table(['Id', 'Code', 'Default', 'Name'], $this->allLanguages->toArray(), 'compact');
 }
Exemple #23
0
 /**
  * Get TestTypes that support prevalence counts
  *
  * @return Collection TestTypes
  */
 public static function supportPrevalenceCounts()
 {
     $testTypes = new Illuminate\Database\Eloquent\Collection();
     // Get ALPHANUMERIC measures whose possible results (or their interpretation) can be
     // reduced to either Positive or Negative
     $measures = DB::table('measures')->select(DB::raw('measures.id, measures.name'))->join('measure_ranges', 'measures.id', '=', 'measure_ranges.measure_id')->where('measures.measure_type_id', '=', Measure::ALPHANUMERIC)->where(function ($query) {
         $query->where('measure_ranges.alphanumeric', '=', 'Positive')->orWhere('measure_ranges.alphanumeric', '=', 'Negative')->orWhere('measure_ranges.interpretation', '=', 'Positive')->orWhere('measure_ranges.interpretation', '=', 'Negative');
     })->get();
     foreach ($measures as $measure) {
         $measureORM = Measure::find($measure->id);
         $objArray = $measureORM->testTypes()->first();
         if (!empty($objArray)) {
             foreach ($measureORM->testTypes()->get() as $tType) {
                 if ($tType->measures()->count() == 1) {
                     $testTypes->add($tType);
                 }
             }
         }
     }
     return $testTypes->unique()->sortBy('name');
 }
Exemple #24
0
 public function newRelationsCollector($name, $data)
 {
     $model = $this->getRelatedModel($name);
     $newRelations = new \Illuminate\Database\Eloquent\Collection();
     $createKey = mitterFindNestedArrayKey($this->structure['relations'][$name], 'create');
     foreach ($data as $item) {
         if (is_array($item)) {
             $item = array_filter($item);
             if (isset($item['id'])) {
                 // @Bug: new model createKey cannot be a number! It would be misunderstood as an ID. At least one non-numeric character is needed.
                 if ($item['id'] == preg_replace('/[^0-9]/', '', $item['id'])) {
                     $relation = $model::find((int) $item['id']);
                 } else {
                     $relation = new $model();
                     $relation->{$createKey} = $item['id'];
                 }
                 unset($item['id']);
                 foreach ($item as $key => $value) {
                     if (strlen($value) > 0) {
                         $relation->{$key} = $value;
                     } else {
                         unset($relation->{$key});
                     }
                 }
             }
         } else {
             if ($item == preg_replace('/[^0-9]/', '', $item)) {
                 $relation = $model::find((int) $item);
             } elseif ($createKey) {
                 $relation = new $model();
                 $relation->{$createKey} = $item;
             }
         }
         if (isset($relation)) {
             $newRelations->add($relation);
         }
     }
     return $newRelations;
 }
 public function getResource($resource)
 {
     if (is_string($resource)) {
         if ('amount' == $resource) {
             $country_code = Input::get('country_code');
             $mem_period = Input::get('mem_period');
             // hard coding the currency ID to query payment-heads
             if ('IND' == $country_code) {
                 $currency_id = 1;
             } else {
                 $currency_id = 2;
             }
             Log::info('In getResource: ' . $country_code . $mem_period);
             $head = PaymentHead::getHead($mem_period, $currency_id)->first();
             $data = ['amount' => $head->amount, 'service_tax' => ServiceTaxClass::find($head->service_tax_class_id)->tax_rate];
         } else {
             if ('states' == $resource) {
                 $country_code = Input::get('code');
                 Log::info('In getResource for states: ' . $country_code);
                 // querying with states of india and not regions > states;
                 $states = State::where('country_code', 'like', $country_code)->orderBy('name', 'asc')->get(['state_code', 'name'])->toarray();
                 Log::info('In getResource for states: typeof ' . gettype($states));
                 $data = $states;
             } else {
                 if ('branches' == $resource) {
                     $state_code = Input::get('code');
                     Log::info('In getResource for branches: ' . $state_code);
                     $chapters = CsiChapter::where('csi_state_code', $state_code)->get();
                     $collection = new \Illuminate\Database\Eloquent\Collection();
                     $result = new \Illuminate\Database\Eloquent\Collection();
                     foreach ($chapters as $chapter) {
                         $members = Member::where('csi_chapter_id', $chapter->id)->get();
                         if (!$members->isEmpty()) {
                             $collection = $members->filter(function ($item) {
                                 $curr = $item->subType;
                                 if ($curr->membership_type_id == 1) {
                                     if ($curr->subType->is_student_branch) {
                                         return $item;
                                     }
                                 }
                             });
                         }
                     }
                     foreach ($collection as $member) {
                         $arr = [];
                         $arr['member_id'] = $member->subType->id;
                         $arr['name'] = $member->subType->name;
                         $result->add($arr);
                     }
                     $data = $result->sortBy('name')->toarray();
                 } else {
                     if ('chapters' == $resource) {
                         $state_code = Input::get('code');
                         Log::info('In getResource for chapters: ' . $state_code);
                         $chapters = CsiChapter::where('csi_state_code', $state_code)->orderBy('name', 'asc')->get(['id', 'name'])->toarray();
                         Log::info('In getResource for chapters: typeof ' . gettype($chapters));
                         $data = $chapters;
                     } else {
                         if ('institutions' == $resource) {
                         }
                     }
                 }
             }
         }
         $response = Response::json($data, 200);
     } else {
         $response = Response::json(array('errors' => $e->getMessage()), 500);
     }
     return $response;
 }
Exemple #26
0
 public function index()
 {
     $advertises = Advertise::where('expired_at', '>=', Carbon::now())->where('expired_at', '<=', Carbon::now()->addDays(1))->active()->groupBy('user_id')->get();
     $advertises_list = Advertise::where('expired_at', '>=', Carbon::now())->where('expired_at', '<=', Carbon::now()->addDays(1))->active()->groupBy('user_id')->get();
     $result = [];
     while (count($advertises) > 0) {
         $gold = 0;
         $silver = 0;
         $bronze = 0;
         $cumulative = [];
         $cumulant = 0;
         foreach ($advertises as $advertise) {
             if ($advertise->type == 1) {
                 $gold++;
             } elseif ($advertise->type == 2) {
                 $silver++;
             } elseif ($advertise->type == 3) {
                 $bronze++;
             }
         }
         foreach ($advertises as $key => $advertise) {
             if ($advertise->type == 1) {
                 $coff = 4;
             } elseif ($advertise->type == 2) {
                 $coff = 2;
             } elseif ($advertise->type == 3) {
                 $coff = 1;
             }
             $probability = $coff / (4 * $gold + 2 * $silver + $bronze);
             $advertise->probability = $probability;
             $cumulant += $probability;
             $cumulative[] = ['user_id' => $advertise->user_id, 'cumulant' => $cumulant];
         }
         $rand = rand(0, 10000) / 10000;
         $cumulative[-1] = 0;
         for ($i = 0; $i < count($cumulative); $i++) {
             if ($rand > $cumulative[$i - 1]['cumulant'] and $rand <= $cumulative[$i]['cumulant']) {
                 $result[] = ['user_id' => $cumulative[$i]['user_id']];
                 $user_id = $cumulative[$i]['user_id'];
                 $advertise_id = $advertises->search(function ($item, $key) use($user_id) {
                     return $item->user_id = $user_id;
                 });
                 $advertises->forget($advertise_id);
                 break;
             }
         }
     }
     $sorted_advertises = new \Illuminate\Database\Eloquent\Collection();
     foreach ($result as $item) {
         $sorted_advertises->add($advertises_list->where('user_id', $item['user_id'])->first());
     }
     //        dd($sorted_advertises);
     //        $users = [];
     //        $users [] = ['id'=>1, 'name'=>'emad', 'type'=>1];
     //        $users [] = ['id'=>2, 'name'=>'jafar', 'type'=>3];
     //        $users [] = ['id'=>3, 'name'=>'ekarim', 'type'=>3];
     //        $users [] = ['id'=>4, 'name'=>'ahmad', 'type'=>2];
     //        $users [] = ['id'=>5, 'name'=>'gholam', 'type'=>2];
     //        $users [] = ['id'=>6, 'name'=>'kazem', 'type'=>3];
     //        $users [] = ['id'=>7, 'name'=>'saeed', 'type'=>3];
     //        $users [] = ['id'=>8, 'name'=>'sepehr', 'type'=>3];
     //        $users [] = ['id'=>9, 'name'=>'karamali', 'type'=>2];
     //        $users [] = ['id'=>10, 'name'=>'abas', 'type'=>3];
     //        $users [] = ['id'=>11, 'name'=>'kambiz', 'type'=>2];
     //        $users [] = ['id'=>12, 'name'=>'asghar', 'type'=>1];
     //        $users [] = ['id'=>13, 'name'=>'homayoon', 'type'=>3];
     //        $users [] = ['id'=>14, 'name'=>'iraj', 'type'=>2];
     //        $users [] = ['id'=>15, 'name'=>'mojtaba', 'type'=>3];
     //        $users [] = ['id'=>16, 'name'=>'javid', 'type'=>1];
     //
     //
     //        $result=[];
     //
     //        while(count($users) > 0){
     //
     //            $gold = 0;
     //            $silver = 0;
     //            $bronze = 0;
     //            $cumulative = [];
     //            $cumulant = 0;
     //
     //            foreach($users as $user){
     //                if($user['type'] == 1){
     //                    $gold++;
     //                }elseif($user['type'] == 2){
     //                    $silver++;
     //                }elseif($user['type'] == 3){
     //                    $bronze++;
     //                }
     //            }
     //
     //            foreach($users as $key=>$user){
     //                if($user['type'] == 1){
     //                    $coff = 4;
     //                }elseif($user['type'] == 2){
     //                    $coff = 2;
     //                }elseif($user['type'] == 3){
     //                    $coff = 1;
     //                }
     //                $probability = ($coff)/(4*$gold+2*$silver+$bronze);
     //                $users[$key]['probability'] = $probability;
     //                $cumulant+=$probability;
     //                $cumulative[] = ['user_id'=> $user['id'], 'cumulant'=>$cumulant];
     //            }
     //
     //            $rand = rand(0,1000)/1000;
     //            $cumulative[-1] = 0;
     //            for($i=0; $i<count($cumulative) ; $i++){
     //                if($rand > $cumulative[$i-1]['cumulant'] and $rand <= $cumulative[$i]['cumulant']){
     //                    $result [] = [$cumulative[$i]['user_id']];
     //                    array_forget($users, $i);
     //                    $users = array_values($users);
     //                    break;
     //                }
     //            }
     //
     //        }
     //
     //        dd([$result, $users]);
     return view('index.index', compact('sorted_advertises'));
 }
 /**
  * @param $ids
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function findByIds($ids)
 {
     $pages = new \Illuminate\Database\Eloquent\Collection();
     if (!is_array($ids)) {
         return $pages;
     }
     foreach ($ids as $id) {
         $page = $this->page_model->find($id);
         if ($page) {
             $pages->add($page);
         }
     }
     return $pages;
 }
 public function anyInlineUpload()
 {
     //$setting = array();
     $setting = new \Illuminate\Database\Eloquent\Collection();
     $setting->add(new \Contentsetting());
     $setting[0]->field_parameters = \Contentsetting::DEFAULT_UPLOAD_JSON;
     $setting[0]->name = '_inline';
     $setting[0]->field_type = '_inline';
     $setting[0]->id = 0;
     return $this->render('contents.inline-upload', compact('setting'));
 }
Exemple #29
0
 /**
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function unassigned_groups()
 {
     $unassigned_groups = new \Illuminate\Database\Eloquent\Collection();
     $groups = UserGroup::get();
     $current_groups = $this->groups->lists('id');
     foreach ($groups as $group) {
         if (!in_array($group->id, $current_groups)) {
             $unassigned_groups->add($group);
         }
     }
     return $unassigned_groups;
 }
Exemple #30
0
 /**
  * Return the total cost for all calls given.
  * @param  Illuminate\Database\Eloquent\Collection $collection
  * @return String
  */
 private static function calculateTotalCost($collection)
 {
     $calls = $collection->all();
     $seconds = 0;
     foreach ($calls as $call) {
         $seconds = $seconds + $call->totaltime;
     }
     $minutes = $seconds / 60;
     // convert billing seconds to minutes.
     $totalCost = $minutes * env('AVG_COST_PER_MIN');
     return number_format($totalCost, 2);
 }