logo
down
shadow

Is it necessary to set values to a variable two times?


Is it necessary to set values to a variable two times?

By : terateratera
Date : November 22 2020, 02:42 PM
around this issue Nope, absolutely not. In fact, if I were to come across the snippet you posted, I'd probably replace it with:
code :
echo 'hello';
$output = '';
$output = 'hello';
echo $output;
$string = '';
foreach ($arr  as $k => $v) {
    //concatenate
    $string .= $k . ' => ' . $v;
}
$doesNotExist += 123;//evaluates to null + 123 => 0 + 123
$newVar++;//is the same as $newVar = null + 1;
//$i is initialized, ++$i is safe here
for ($i=0;$i<10;++$i)
    echo $i;
function doubleInt($x)
{
    $x *= 2;//safe, $x is argument, so will exist
    echo $x;//use the variable safely
    return $x;
}
class Foo
{
    /**
     * @var int
     */
    protected $foo = 0;

    /**
     * @var array
     */
    public $bar = [];
}
public function __set($name, $val)
{
    throw new \RuntimeException(
        sprintf(
            '%s does not have a property %s',
            __CLASS__,
            $name
        )
    );
}
//some code
if ($someVar === true) {
    $newVar = 123;
}
//more code
$x *= $newVar;//if $someVar !== true, $newVar is null here
$newVar = 1;//default value
if ($someVar === true) {
    $newVar = 123;
}


Share : facebook icon twitter icon
How can I alter the values of a variable with onclick multiple times?

How can I alter the values of a variable with onclick multiple times?


By : PJ S.
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , If you make a new function like the scaleModel() function that multiplies the scale by an amount instead of setting it:
code :
function scaleModelBy(amount) {
    model.scale.x = model.scale.x * amount;
    model.scale.y = model.scale.y * amount;
    model.scale.z = model.scale.z * amount;
}
<button onclick="scaleModelBy(2);">Scale up</button>
<button onclick="scaleModelBy(0.5);">Scale down</button>
Function is called too many times and retains old variable values

Function is called too many times and retains old variable values


By : Shai
Date : March 29 2020, 07:55 AM
like below fixes the issue Why oh why are you passing data using a global current_deck variable?
Each time you enter the updateCurrentDeckTable branch of your add method:
code :
if($(ev.target).data("card-id")) {
    this.card_array.push($(ev.target).data("card-id"));
    current_deck.push($(ev.target).data("card-id"));
    updateCurrentDeckTable();
}
$.each(current_deck, function(i, cardId) { ...
Print array values a variable number of times

Print array values a variable number of times


By : mousne
Date : March 29 2020, 07:55 AM
Number of times pair has matching variable values

Number of times pair has matching variable values


By : Zayy
Date : March 29 2020, 07:55 AM
around this issue Say I have a data frame with an id variable, a date variable, and another variable x (e.g. df below). For each pair of values of x, I want to know how many times they share the same value for both id and date. So, the results should look something like those shown below. a and b are "together" 2 times, and a and c are "together" 1 time (where together means sharing same id and date). Speed is somewhat important. , Your data
code :
df <- data.frame(id = c(1,1,2,2,1,1), 
                 date = c(rep(1,4),2,2), 
                 x = c('a','b','a','c','a','b'))
myfun <- function(df) {
            require(tidyverse)
            df1 <- tibble(id=paste(df$id, df$date), x=df$x)
            df2 <- split(df1, df1$id)
            grp <- map_df(df2, ~as.data.frame(matrix(combn(.x$x,2), ncol=2, byrow=TRUE), stringsAsFactors=F)) %>%
                       count(V1,V2)
            return(grp)
         }    
ans <- myfun(df)

     V1    V2     n
1     a     b     2
2     a     c     1
newdf <- data.frame(id = c(1,1,2,2,1,1,1), 
                    date = c(rep(1,4),2,2,1), 
                    x = c('a','b','a','c','a','b','c'))
ans <- myfun(newdf)

     V1    V2     n
1     a     b     2
2     a     c     2
3     b     c     1
bouncy <- function(df) {
            require(dplyr)
            newdf %>%
              group_by(id, date) %>%
              summarise(x_list = list(sort(x))) %>% # list of x values
              ungroup() %>% 
              select(x_list) %>% # only select the list
              rowwise() %>% # by each row
              mutate(var1 = x_list[1], var2 = x_list[2]) %>% # extract components of list
              select(-x_list) %>% # remove list
              count(var1, var2) # count the vars
          }

ans <- bouncy(newdf)

    var1   var2     n
1      a      b     2
2      a      c     1
library(microbenchmark)
microbenchmark(myfun(newdf), bouncy(newdf))

              expr      min       lq     mean   median       uq      max neval
      myfun(newdf) 31.72188 32.23807 34.32655 32.70342 34.22985 112.5996   100
     bouncy(newdf) 58.55471 59.41472 61.37818 60.59873 61.60430  78.5788   100
Counting the number of times a variable has changed values

Counting the number of times a variable has changed values


By : Rochak Agrawal
Date : March 29 2020, 07:55 AM
I hope this helps you . This answer supposes that you try to count a transitions only and don't try to plot values (last paragraph of the question).
If you deal with only a {-1, 0, 1} set, perhaps you can sum a values from a list. It's a little faster than add them to counter and gives you a transition info.
code :
more_ones = True if sum(my_list) > 0 else False
transition_counter = 0
transitions_history = []
for x in range(0, 100): 
    # some rules, which change mylist
    # you can place a transition counter logic right here
    current_sum = sum(my_list)  # one more time, counting inside the logic is faster
    if current_sum < 0 and more_ones:
        transition_counter  += 1
        more_ones = False
        transitions_history.append(x)
    elif current_sum > 0 and not more_ones:  
        transition_counter  += 1
        more_ones = True
        transitions_history.append(x)
my_list = [0, 1, -1, -1]  # sample data

factor = 1.5  # some factor
pos_count = my_list.count(1)
neg_count = my_list.count(-1)
more_ones = True if pos_count > factor * neg_count else False  # unclear part - don't know what you plan to do with zeroes
transition_counter = 0
transitions_history = []
for x in range(0, 100):
    # I provide a test logic
    ### CROP HERE ###
    try:
        if x < 3:
            my_list.remove(-1)  # better to decrement/increment pos. and neg. counts here
        elif x >= 3 and x < 5:
            my_list.append(1)
        elif x >= 5 and x < 10:
            my_list.append(-1)
        else:
            my_list.append(1)
    except ValueError:
        pass
    ### CROP HERE ###
    pos_count = my_list.count(1)
    neg_count = my_list.count(-1)
    if neg_count > pos_count * factor and more_ones:
        transition_counter  += 1
        more_ones = False
        # you couldn't store list and need a copy, otherwise it will change values by pointer
        transitions_history.append((x, 'pos_to_neg', [i for i in my_list]))
    elif pos_count > neg_count * factor and not more_ones:
        transition_counter += 1
        more_ones = True
        transitions_history.append((x, 'neg_to_pos', [i for i in my_list]))
transitions_history
Out:
    [(1, 'neg_to_pos', [0, 1]),
     (9, 'pos_to_neg', [0, 1, 1, 1, -1, -1, -1, -1, -1]),
     (14, 'neg_to_pos', [0, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1])]
transition_counter
Out:
3
Related Posts Related Posts :
  • How to implement this json feed into a database structure?
  • Codeigniter, windows, xampp, how to use htaccess to get rid of trailing slash?
  • How to disable Navbar and footer in Yii2 other layouts
  • Json not encode my Special Character
  • echo if POST length is low
  • Warning: require_once error
  • What is this code meaning...?
  • Send to /dev/null a PHP function "echo" output
  • How to store post details and timestamp in database?
  • php mysql - search a row and concatenate values of every columns to variable string
  • Write a program to get N number of positive non-zero integers, so that the sum and product of these numbers are equal
  • Running two multi line queries in PHP
  • PHP/ASP Trouble understanding
  • Strict standards notices View/Layout class
  • how to have backwards reference on PHP's regex?
  • Uncaught exception 'RuntimeException' with message 'Unable to load ZF2. Run `php composer.phar install` or define a ZF2_
  • phpDocumentor: DocBlock with @var tags duplicates descriptions
  • how to push an object to an array within an object with PHP
  • Undefined offset error in for loop
  • mysql query logic for fetching data from 3 related tables on certain condition
  • Saving blob video with php
  • SpeckPaypal ZF2 How to edit the CURRENCY CODE?
  • How to filter associated HABTM data with FriendsOfCake Search for CakePHP 3
  • Check ALL $_POST lengths
  • PHP - Recursively set each array element's key to the value of a child element when given the childs key name
  • How to disable the user from entering wrong passwords
  • SilverStripe Custom Email Form - jQuery.ajax not passing variables to server
  • Regular expression to extract Facebook URL's inc vanity
  • Show Calculated Field on SuiteCRM Dashlet
  • Class 'NumberFormatter' not found error in simple PHP program
  • Scan Barcode - Save Code in SQL Database
  • Fetch MySQLi with custom database (aka, column names for array keys)
  • Symfony2 PagerFantaBundle
  • Wordpress: Restrict file uploads by MIME type
  • Find key in array in a foreach
  • pdo select query wont works with string of letters
  • Check if atleast one character is in mysql row, using php
  • Php method not being called
  • Display dates in a HTML table for each month with PHP
  • VBA Submit Button Clicking
  • Can a namespace start with a number in PHP?
  • Regex not matching regex in PHP
  • Injecting Artisan into Service class
  • Create and transfert array php
  • How do I query MongoDB from PHP with IFNULL() expression inside WHERE?
  • How to download a view block as PDF in drupal 7?
  • PHP - Where should mysql_close() be put in if-else clause?
  • "php comment" within an echo statement
  • Replacing string by boolean in a JSON string?
  • What is the limit in size of a Php variable when storing string?
  • Trouble checking the date range in PHP
  • nginx simple .htm to .php rewrite rule does not work
  • How to propertly comment a PHP file based on GNU/GPL source
  • Change locale param in current URL in a ZF2 application
  • PHP shortcut for if stament
  • Implode sorted number array to string by commas and merge intervals
  • PHP Datepicker data doesn't go into mySQL
  • Is there a way to limit a dropdown box size
  • How to Redirect to Another Page in PHP based on drop down selected value/text?
  • Unable to use wp_mail
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co