NUnit with Windows Phone 7

Question: I'd like to unit test my Windows Phone 7 libraries with NUnit.
Is there a version of NUnit compatible with Windows Phone 7?
Answer: You might also look at http://unitdriven.codeplex.com - it is a Silverlight and WP7 unit test framework/runner, that also has an add-in DLL for nunit/mstest so you can write tests and have the same test code run in .NET, Silverlight and WP7.
As long as you are testing non-async behaviors, UnitDriven is pretty compatible with nunit (we built it to run a few hundred pre-existing nunit tests). It does have its own model for async tests - again specifically designed so the same test code runs in .NET, SL and WP7.
Answer: What you are searching for is nunit-silverlight. You need to reference "NUnit.Silverlight.Framework.dll" and "NUnit.Silverlight.Compatibility.dll" (SilverLight 3 versions), and make all references "local copy", even the .NET framework.
If you use Visual Studio Express Edition, there is still some obstacles that I detailed a bit more on my blog. In short: Express Edition doesn't include tests or add-ins, and it should work fine with external test runners but for my part I've got an exception in NUnit's GUI, so one may need something else to run his tests (NUnit-Console, Gallio, Autotest.NET, ...). I use TddBarForPhone (available on codeplex), a tool I made which runs NUnit-Console after each build and color the results in red or green.
Comment: Works like a charm for my Windows Phone project(s) - thanks a lot for this hint!
Answer: As Windows Phone 7 is basically just Silverlight 3 I suspect that it will be fine.
There are multiple posts about using NUnit with Silverlight, so give them a try and you will probably have lots of success.
Here is one on using TestDriven.Net and NUnit with Silverlight: http://weblogs.asp.net/nunitaddin/archive/2008/05/01/silverlight-nunit-projects.aspx
Comment: it looks like the Silverlight NUnit Project template is the easiest solution to start writing NUnit tests against WP7 assembly. Direct link to download: http://www.testdriven.net/downloads/SilverlightNUnitProject.zip
Answer: I have recently discoverted the following tools which can be additionaly helpful for CI-Integration.
http://justinangel.net/WindowsPhone7EmulatorAutomation
and more on that (which is a series of articles having 5 parts actually):
http://blogs.msdn.com/b/vsdteam/archive/2007/11/20/corecon-api-part-1.aspx
Answer: I found a great screencast recently that shows how to wire up NUnit so you can tdd on the Windows Phone 7 platform.
It's not using any silverlight templates/etc just a plain WP7 class library and NUnit
Answer: I've had a port of this ready for a while and finally uploaded it to NuGet.org
<code>Install-Package NUnit.WP
</code>
NuGet package:
http://www.nuget.org/packages/NUnit.WP
Source: http://bitbucket.org/jesperll/nunit-silverlight

NUnit with Windows Phone 7


Rails password validation fails misteriously while writing unrelated tests

Question: I'm doing Michael Hartl's Rails Tutorial, I'm at chapter 14
Basically I'm building a Twitter clone, to learn Rails.
In this chapter, Users can follow each other.
After writing the first test to check those relationship:
user_test.rb
test "should follow and unfollow a user" do
    michael = users(:michael)
    archer  = users(:archer)
    assert_not michael.following?(archer)
    michael.follow(archer)                    # LINE OF THE ERROR (rb:100)
    assert michael.following?(archer)
    michael.unfollow(archer)
    assert_not michael.following?(archer)
end

this error popped up:
error
ERROR["test_should_follow_and_unfollow_a_user", UserTest, .192215816000044]
test_should_follow_and_unfollow_a_user#UserTest (6.19s)
ActiveRecord::RecordInvalid:
ActiveRecord::RecordInvalid: Validation failed:
  Password can't be blank,
  Password is too short (minimum is 6 characters)
        app/models/user.rb:102:in `follow'
        test/models/user_test.rb:100:in `block in <class:UserTest>'

it is quite weird because validations were working fine till now, there were even some tests to check their correct behavior (and if I remove the validation on the User model, those tests correctly fire up, but the error in test/models/user_test.rb disappears)
head of models/user.rb
class User < ApplicationRecord
has_many :microposts, dependent: :destroy
has_many :active_relationships,  class_name:    "Relationship",
                                 foreign_key:   "follower_id",
                                 dependent:     :destroy
has_many :following,  through:   :active_relationships,
                      source:    :followed

attr_accessor :remember_token, :activation_token, :reset_token
before_save     :downcase_email
before_create :create_activation_digest

VALID_EMAIL_REGEX = /\A[\d\+\.a-z_-]+@[a-z]+\.[a-z.]+\z/i
validates(:name,     presence: true, length: { maximum: 50 } )
validates :email,    presence: true, length: { maximum: 255 },
                     format: { with: VALID_EMAIL_REGEX },
                     uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 6 }
has_secure_password

method in model/user.rb that triggered the error
# follows a user
def follow(other_user)
    following << other_user    # LINE OF THE ERROR (rb:102)
end

head of fixtures/users.yml
michael:
  name:             Michael Example
  email:            email@example.com
  password_digest:  <%= User.digest('password') %>
  admin:            true
  activated:        true
  activated_at:     <%= Time.zone.now %>

archer:
  name:             Sterling Archer
  email:            email@example.com
  password_digest:  <%= User.digest('password') %>
  activated:        true
  activated_at:     <%= Time.zone.now %>

other files
all other files can be found on my github page
Answer: I finished the same tutorial and in my User model I validated for the password to be as the following:
  validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

Perhaps add allow_nil: true.


How to extend a union type in another module?

Question: Is there a way to extend another module's union type?  Below is a contrived example illustrating the need, but I got a ts(3200) duplicate identifier error with the approach.
In the Core module @org/core, there is a union type OptionType:
<code>// In Core module @org/core

export type OptionType = OptionAType | OptionBType;

</code>
In another module, I want to extend the core module's OptionType to include a new type MyListOptionType.
So when anyone uses <code>@org/list</code>, they can use the extended OptionType.
<code>// In ListModule of another package @org/list

import type { OptionType as OriginalOptionType } from '@org/core';

type MyListOptionType = { foo: string; bar: number };

declare module '@org/core' {
  type OptionType = OriginalOptionType | MyListOptionType;
}
</code>
However, my current approach causes a duplicate identifier error (ts(3200)).
Comment: Even if you *could* do this, it would likely make code in the original module incorrect. The code will be written to handle the union members the module itself defines, not your third union member. Continuing with your example where there are just two members of the union, module could could easily be doing `if (isOptionTypeA(optionType)) { /* ... */ } else { /* ... */ }`. Adding a third member makes the `else` branch problematic in that example.
Answer: Type aliases don't merge like interfaces for example. There is no way to extend the union in another module. You can only define a union in your module and use that as needed.


javascript little algorithm to calculate prices

Question: I am developing a little website and I have 20 product selling.
Each week I want to calculate new prices for every product taking into account the number of sells done of each product but following two rules:

The sum of the 20 products' prices must always be 100€
I want every product to be integer (no decimal) or to be .5, I mean, one product's price can be 7 or 8 or 9 or 7.5 or 8.5 but not 8.3 or 7.1.

Lets' make an example but simplifying with 4 products:
Sells this week:
product_id  sells
----------  ------
     1       45
     2       31
     3       12
     4       62

ok, total sells then are 150.
If i divide those 100€ by 150 sells I get 0.667€/sell. So If I multiply every product by this value I am getting:
product_id  sells  raw_price_next_week
----------  ------  -------------------
     1       45             30.015
     2       31             20.677
     3       12             8.004
     4       62             41.354

Then I need to normalize those raw_prices taking into account the second rule I mentioned before, getting the closest 0.5 multiple of each raw_value...
product_id  sells  raw_price_next_week    final_price
----------  ------  -------------------    ------------
     1       45             30.015             30
     2       31             20.677             20.5
     3       12             8.004              8
     4       62             41.354             41.5

I've been thinking on how to code this little algo but the fact is that I don't even know how to start. I need some expert help...
Comment: That's a very unusual store you're running. It's almost as though this were a homework problem.
Comment: What have you tried? I have a solution, but I'm not going to post it until I've seen what you've attempted.
Comment: i thought of an array to store sellscount name for example as sellscount. Then add all sells on the array and store it in var totalsells. Then var coef=100/totalsells. Then for each cell in sellscount I multiply it with coef. Here is where i don't know how to adjust the output numbers to 0.5 multiples.
Answer: Not sure if you need to actually display the finished results or not but this should provide the correct calculations.

// Start with the raw product data (array of object - from database likely)
    var
        products = [
            {
                product_id: 1,
                sells: 45
            },
            {
                product_id: 2,
                sells: 31
            },
            {
                product_id: 3,
                sells: 12
            },
            {
                product_id: 4,
                sells: 62
            }
        ]
    ;

    // ###############################################################

    window.Pricing = {

        total_sum: 100, // This represents the 100€
        sales : 0,

        init: function( products ) {
            return this.calculate_final_price( products );
        },

        get_price_per_sale: function( products ) {

            for( x in products ) {
                this.sales += products[x].sells;
            }

            return this.total_sum / this.sales;
        },

        calculate_final_price: function( products ) {

            var price_per_sale = this.get_price_per_sale( products );

            for( x in products ) {
                products[x].raw_price_next_week = +( products[x].sells * price_per_sale );
                products[x].final_price = +( Math.round( products[x].raw_price_next_week * 2 ) / 2 ).toFixed(1);
            }

            return products;
        }

    };

    // ###############################################################

    // Init the pricing calculations and get the final objects with updated pricing.
    Pricing.init( products );

Fiddle here: http://jsfiddle.net/0nbbojp9/1/
Answer: Ok so here's what I came up with in javascript like you asked for. Also you can test it out here.
// 1.) Set array for product prices... I just put a random number of products
var productPrices = [10,20,20,30,30,30,25,10];

// 2.) Get initial total price to calculate price change
var productPriceSum = 0;
for (var i = 0; i < productPrices.length; i++) {
    productPriceSum += productPrices[i];
}
var priceChange = (100/productPriceSum);

// 3.) Change prices rounding to the nearest .5
productPriceSum = 0;
for (var i = 0; i < productPrices.length; i++) {
    var newPrice = Math.round((productPrices[i]*priceChange)*10)/10
    var npDecimal = (newPrice - Math.floor(newPrice))
    if(npDecimal < 0.5){
        newPrice = Math.floor(newPrice)
    }else{
        newPrice = Math.floor(newPrice) + .5
    }
    productPrices[i] = newPrice;
    productPriceSum += newPrice;
}

// 4.) Account for any missing or excess of numbers to get the total back to 100
var makeEvenHundred = (100 - productPriceSum)
for(var i = 0; i < (makeEvenHundred*2); i ++){
    if(makeEvenHundred < 0){
        productPrices[i] -= .5
    }else{
        productPrices[i] += .5
    }
}

// Proof it all worked!
productPriceSum = 0;
for (var i = 0; i < productPrices.length; i++) {
    alert('Product # ' + (i+1) + ' Price: ' + productPrices[i]);
    productPriceSum += productPrices[i];
}
alert('Total: ' + productPriceSum);

Also note that section #4 will probably need to be tweaked however you want the logic to work there. The way I threw it together, it will add or remove the values to the first prices until the total has gotten back to 100. Also it assumes that there will in fact be enough products to add or remove .5 at a time (You said 20, so I assume this would work).
So if this website is any success, just know I did all the work for you ;)
Answer: Solution
The trick is to break the problem into small pieces and deal with each one separately. Here's the breakdown:

Round the value down to the nearest integer.
Capture the decimal value.
Divide the decimal value to see how many '0.5's make up this value.
Multiple the number of 0.5's to get the closest 0.5 value.
Sum the value from 1. with the value from 4.

You can adjust the closest variable to round to different values as well.
Below is the implementation of this. You can use the map function to execute the normalization on all values in the data array. In your case, it would be the result of some ajax call.
Implementation

var data = [30.015, 20.677, 8.004, 41.354];

function normalize(value) {
  var closest = 0.5;
  var significand = Math.floor(value);
  var mantissa = (value % 1).toFixed(2);
  var normalized = Math.round(mantissa / closest) * closest;
  return significand + normalized;
}

var normalized = data.map(normalize);

console.log(normalized);

Resources

Array Map Function


Linux use binary or decimal prefix?

Question: How does Linux deal with Units? Does it use decimal or binary?
Decimal Prefix
name      base 10 exp   base 1000 exp     digits
kilo      10^3          1000^1            1000
mega      10^6          1000^2            1000000
giga      10^9          1000^3            1000000000

Binary Prefix
name      base 2 exp    base 1024 exp     digits
kibi      2^10          1024^1            1024
mibi      2^20          1024^2            1048576
gibi      2^30          1024^3            1073741824

Now if you take a look for two commands for example du and fdisk you could see the difference:
Here an example for 1TB external HDD mine:
$ du -sh
956G    .

While running fdisk:
$ sudo fdisk -l

Disk /dev/sdc: 1000.2 GB, 1000204886016 bytes

So Which apps use decimal and which use binary?
How to apply one method to the whole system and apps inside?
Comment: I'm voting to close as too broad since this is very much app-dependent.
Comment: forget about app. what about Linux itself?!
Answer: The kernel documentation doesn't say a word about SI prefixes. Where prefixes do appear in documentation, they appear without the silly i (k, M, etc., instead of ki, Mi) (see man 5 proc, for example). Since GNU tools didn't gain SI prefix support until well after Linux was released, and Linus doesn't look like someone who changes kernel code simply because a standards organization prefers different prefixes, I speculate that Linux, when it does use these prefixes, uses binary prefixes.

The manpages developed as part of the kernel documentation, however, does discuss this. See man 7 units:
Thus, today, MB = 1000000B and MiB = 1048576B.

In the free software world programs are slowly being changed to con‐
form.  When the Linux kernel boots and says

      hda: 120064896 sectors (61473 MB) w/2048KiB Cache

the MB are megabytes and the KiB are kibibytes.

Wikipedia references this, and mailing list posts by ESR (aka Eric S. Raymond, a well-known kernel developer)  ([1], [2], [3], [4]) show that a patch changing kB to KiB, etc. in one part of the documentation, was accepted, but part of it continued to use the older variants. Thus, prefixes are binary (or are intended to be binary).
Comment: I think same as you, but still searching for some official announce...
Comment: @Maythux you could ask on the kernel mailing list for confirmation, but AFAICT, [discussions on the list](https://www.google.co.in/search?q=site%3Alkml.org+si+prefix&oq=site%3Alkml.org+si+prefix) indicate its binary.
Comment: Thanks for helping, just keeping open for sometime  seeking for more details else i'm going to mark it as asnwer
Comment: @Maythux see update.
Comment: nice work, I think i have now suitable view

Linux use binary or decimal prefix?


Image Accordion controlled by scroll

Question: I need to create an image accordion where it will be controlled by page scroll, like when you scroll your page and the accordion start it start to open and close horizontally while you still 'scrolling down' the page, after all, images open it continues to scroll vertically the page.
on the image you can see like when you scroll down the images should open one by one until finish.
If anyone has a solution for that and could share. Thanks!
The accordion should look like this
Comment: Hello, this isn't a code-assignment solution website but this is where you got the reason why for the question.
Comment: Please add more details,or executable code to know were ur stuck
Answer: You can play around with slick.js https://kenwheeler.github.io/slick/ it's open source and has custom events. Here is working codepen demo: https://codepen.io/webisora/pen/EwQoMR

Image Accordion controlled by scroll


How do I turn off a command that's on repeat on Switch Bedrock?

Question: I put a command block that would teleport "@p" so when i get close it teleports me back to another place, its Always Active and its a Repeat Command Block, I've tried lots of commands but none work, I've been trying for hours
Comment: Possible duplicate of [I'm stuck in a teleporting loop. What can I do?](https://gaming.stackexchange.com/questions/170185/im-stuck-in-a-teleporting-loop-what-can-i-do)
Comment: Possible duplicate of [How do you add NBT tags to commands in Minecraft Pocket/Bedrock Edition?](https://gaming.stackexchange.com/questions/334102/how-do-you-add-nbt-tags-to-commands-in-minecraft-pocket-bedrock-edition)
Comment: This is not a duplicate of either of the linked questions (especially the first).  Solutions that apply to the Java Edition for this type of problem do not necessarily apply to the Bedrock Edition.
Answer: You can disable command blocks temporarily using the command, /gamerule commandBlocksEnabled false. You can then re-enable them by changing false to true.
Comment: thank you, it really helped me, i thought i lost my world, i wonder why this wasn't in any video!!
Comment: @user232135 Don't forget you can accept the answer by clicking the check on it, notifying that this answer worked for you.
Answer: You can disable command blocks via the settings menu, fix it up, then re-enable command blocks.

Go into your world settings. Scroll down to the cheats section and you should see "Command Blocks enabled" or something like that. Flick that off and the command block should stop. If you don't want your chat to be spammed like that, type /gamerule commandblockoutput false. That will disable the output of the commands. After you fix your command block, you can go back into your settings and turn the "Command Blocks Enabled" setting back on.

Source: darthvader1925's answer at "What can I do to get out of a command block teleporting loop?"
Answer: You could set the block coordinate it's in to air, or fill a region it's in to air.
Comment: ive tried that and it said it filled it but i still can't get close


SQL: find records in Column A with duplicates in Column B

Question: I'm wondering if you could help me on an sql problem I have.
my table looks like
ID    ColumnA     ColumnB
1       123          A
2       123          A
3       123          B
4       456          A
5       456          B
6       456          B
7       789          A
8       789          B
9       789          C

I'd like to identify all records of ColumnA which have duplicates in ColumnB, so the query should return
ID    ColumnA     ColumnB
1       123          A
2       123          A
5       456          B
6       456          B

Thanks a lot in advance.
Cheers
Comment: Which version of SQL are you using?
Comment: Hi Tim, I'm using MySQL 5.7.21
Answer: If you have analytic functions available (MySQL 8.x and later), then use them:
SELECT ID, ColumnA, ColumnB
FROM
(
    SELECT *, COUNT(*) OVER (PARTITION BY ColumnA, ColumnB) cnt
    FROM yourTable
) t
WHERE cnt > 1;

If you don't have analytic functions, then we have to do a bit more work:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT ColumnA, ColumnB, COUNT(*) AS cnt
    FROM yourTable
    GROUP BY ColumnA, ColumnB
) t2
    ON t1.ColumnA = t2.ColumnA AND t1.ColumnB = t2.ColumnB AND t2.cnt > 1;

Answer: You could use EXISTS:
SELECT *
FROM tab t1
WHERE EXISTS (SELECT 1
             FROM tab t2
             WHERE t1.ColumnA=t2.ColumnA AND t1.ColumnB = t2.ColumnB
               AND t1.id <> t2.id);


PHP call is not returning all of the values

Question: I am trying to use some PHP to access a database I created and load it into text boxes.  Currently, the code below loads a list of text boxes and populates the 'name' field, but loads empty text boxes for all the other sections.
I have made sure that the $row['query'] parameters are correct.
Here is what I am seeing:

    $sql = "SELECT * from salesmen";
    $stmt = $conn->query($sql);

    echo '
';
    echo '

        Name
        User ID
        Password
        Commission
        Address

';

    while($row = $stmt->fetch(PDO::FETCH_ASSOC))
    {
        echo '
';
        echo '<input type="text" name="name" value="' .$row['name']. '">	';
        echo '<input type="text" name="id" value"' .$row['id']. '">	';
        echo '<input type="text" name="password" value"' .$row['password']. '">	';
        echo '<input type="text" naem="commission" value"' .$row['commission']. '">	';
        echo '<input type="text" name="address" value"' .$row['address']. '">	';
        echo '
';
    }
    echo '
'

Comment: you are missing = after value , do it just like the name line

        echo '';
Comment: That was embarrassingly obvious. Thank you.
Comment: Add error reporting to the top of your file(s) right after your opening PHP tag
for example `'` which I edited both answers for. Least, for what you posted. I take posted code literally ;-)
Comment: @user3264455 was `echo ''` a bad paste and you didn't put in the missing semi-colon? there's a suggested pending edit in your OP about it to add it.
Answer: You are missing the = sign on all of the other 4 columns, and name was misspelled on the commission column(Thanks Fred)!
echo '<input type="text" name="id" value="' .$row['id']. '">	';
echo '<input type="text" name="password" value="' .$row['password']. '">	';
echo '<input type="text" name="commission" value="' .$row['commission']. '">	';
echo '<input type="text" name="address" value="' .$row['address']. '">	';

You also missed a semi-colon for echo '
'
Answer: why not try the right way, you are missing = in input after value.
You also mispelled "name" in naem="commission" and will fail if $_POST['commission'] is used in a POST call. (or GET, depending on how it's used).
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
    echo '
';
    echo '<input type="text" name="name" value="' .$row['name']. '">	';
    echo '<input type="text" name="id" value="' .$row['id']. '">	';
    echo '<input type="text" name="password" value="' .$row['password']. '">	';
    echo '<input type="text" name="commission" value="' .$row['commission']. '">	';
    echo '<input type="text" name="address" value="' .$row['address']. '">	';
    echo '
';
}

You also missed a semi-colon for echo '
' unless that was just a bad paste and it is in fact part of your actual code in your originally posted question.
Comment: you missed something too
Comment: @Fred-ii- found n sorted
Comment: you should add the fact that it was mispelled ;-)
Comment: i'm too tired thinking to del the answer, already spent hours with another op sorting his problem :)


Memory address (reference) not being displayed in terminal

Question: I am trying to output a simple char address on the display, but using & is not working:
#include <iostream>
using namespace std;
typedef int no;
typedef char nose;
typedef void laps;
laps noname(nose &boogers);
no main(no args, nose**LOC[])
{
cout << "Try ";
nose boogers = 't';
noname(boogers);
}
laps noname(nose &boogers)
{
cout << &boogers;
}

I have tried it by removing the ampersand of the parameter of laps, but the &boogers datum is not working either way because on the console it just shows the "t" character instead of an address.
Am I doing something wrong here?
JSYK: It compiles fine, no warnings at all. I just want to know why I am not getting an address instead of a value.
Comment: You're sending effectively `char*` to std::cout. there is an operator override for that (the string dump, if you want to call it that). If you want the address, `static_cast(&boogers)`
Comment: why redefine these POD types? It makes the code unreadable.
Comment: `#define eat (void*)` and then `cout << eat &boogers`.
Comment: @Matt I like to be unique.
Comment: @jrok I would do that, but #define is obsolete.
Comment: @LastLifeHump well unique or not, its *not* a good practice. Just imagine co-workers being equally "unique". Your combined code would look like utter chaos.
Comment: @WhozCraig My code is more readable than your comment. What co-workers? I write this code individually. I would not adopt a habit of writing code like this on a team.
Comment: @LastLifeHump yeah, alright then. If you want to flame-troll there are better sites than this one.
Comment: @WhozCraig Why use `const void*` for? I don't get what you wrote. I am not trolling, just genuinely wondering what's the issue with a character memory address. Why can't it be displayed normally?
Comment: I have never understood operator overriding/overloading. And I tried the code provided and it still is an error.
Comment: Read my comment again. The one that has more upticks than any other in this list. It is correct. There exists an override `operator <<` for sending a `char const *` to a `std::ostream&`. That override treats said variable as a nil-char terminated string, and attempts to send it as-such to the target stream. Sending the `&var` where `var` is of type `char`, `char&`, etc.. will invoke that override. If you want to send it as a raw address it can't be one that already has a formatted operator. See [the operators of `std::ostream`](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2).
Answer: After a reference is defined, it is not possible to refer to the reference itself, only the object it references. This is just how c++ operates. I suspect this is because references are not meant to be changed, this is one of their aspects which distinguishes them from pointers. Changing the memory address is prevented by not allowing you to access it.
Comment: A char by default is a pointer to, not an address of.


How many bits strings are there of length n consisting entirely of 1's?

Question: I've seen this question in a discrete maths text book :

How many bits strings are there of length n consisting entirely of 1's
  ? and the answer is :

Answer for that question is :

n+1 (including empty string )

What is empty string here? Why isn't 'n' is the answer?
And for another question :

How many bit strings of length n, where n is a positive integer, start
  and end with 1?

The answer is :

2^(n-2)

Why the answer is not 2^(n-2) +1 ? ( As said in previous question about adding empty string )
Comment: I might be missing something, but I think there is only one bit string of given length consisting entirely of 1's.
Comment: Yes. I think the Q is missing something.
Answer: The book probably thinks:

Every bit in an empty string is a $1$
The empty string does not start (or end) with a $1$

The first question may have been about strings of length up to $n$.  It is certainly true that the empty string has no bits which are not $1$.
For the second I would give the answer $0$ for $n=0$ and the answer $1$ for $n=1$, as I would argue that the single bit string 1  both starts and ends with a $1$ and so should be counted.


How to read #(A1 x ... x Ak) = n1 * n2 ... nk?

Question: I found this paragraph and I'm having trouble reading it, I understand that the total of all possible arrangments equal to A1*A2*A3...An but I don't understand how we get there from this:

If A1, A2...Ak are sets so that #Ai=ni>=1 for i=1...k, so cartesian product o A1 x A2 x ... x Ak, consisting of all vectors form (a1, a2...ak) with ai E Ai, has a total of n1*n2...nk elements, meaning:
(A1 x ... x Ak) = n1 * n2 ... nk
Answer: The paragraph explains the meaning.
The operator "$\#$" means "number of elements of" so if $\#(A)= 3$ (say) and $\#(B)= 5$ then
$$
\#(A \times B)= 3 \times 5 = 15.
$$
To see why, suppose $A = \{a,b,c,d,e\}$ and $B = \{1,2,3\}$ and convince yourself that there are $15$ (letter,number) pairs.


How can I push a specific branch of Git to my server?

Question: I'm working to deploy a Django app.
The app built on a Github OS project. I have this stored locally as the Master branch.
$ git branch
* master
  customized - customized with local dev settings
  webfaction_customized - with production server settings

The customizations for this project are stored in 2 separate branches.
My plan was to perform my customization locally in 'customized', then merge those changes into 'webfaction_customized'
Then push these changes to a bare repository on the production_server:
I would then clone this bare repository on the production_server, change the settings in the cloned repository and restart the fcgi process.
The first problem was that I found this if I tried to push a branch to the server that wasn't master, I could not clone from the bare repository.
So I tried to push the master branch to the server.
git push webfaction_server master

But now I'm finding that none of my branches are uploaded.
Is there some way to push a specific branch to a bare repository and be able to clone that branch?
OR
Do I need to restructure my project so that Master branch is my customizations and the Github project would be in a github branch?
Comment: Are there any error messages?  You said that you couldn't clone the bare repository when you pushed a non-master branch.  What was  the error?  And is there any error when you push the master branch?
Comment: Is 'webfaction_server' actually configured as a remote? What does 'git remote show' say?
Comment: This is the error when you try to clone a non-master branch

warning: remote HEAD refers to nonexistent ref, unable to checkout.
Answer: You would simply do:
git push origin webfaction_customized

Where origin is your remote name and webfaction_customized is your custom branch.
Hence, when you work on the master branch, you are pushing via:
git push origin master

Answer: You would simply do:
git push origin localBranchName:remoteBranchName

Answer: The message Warning: Remote HEAD refers to nonexistent ref, unable to checkout. only tells you that the HEAD link does not exist and thus Git does not know which revision to check out to your local working directory.
Chances are that the branches on production_server themselves are created correctly. Just do a git checkout <whatever-branch-you-want> and start hacking away.
If it doesn't solve the issue, paste here the output of git branch -a and cat .git/config run n both repos.
Comment: I guess `git br` is a specific command from https://github.com/larsbrinkhoff/git-scripts/blob/master/git-br
Comment: @tashuhka fixed, thanks. No, for me it is just an alias to 'git branch'.
Answer: Your push-command seems right, assuming webfaction_server is the name of a remote and not just the server address. Run git help remote to learn more about pushing and pulling to/from multiple remotes.
Answer: you may need to update the server information with git-update-server-info. This tool will update the HEAD information on the server with the recent commit hashes, updating old branches and making new branches visible. In particular, it will update the info/refs file in your git repository. You will need to run this on the server, so, perhaps something like the following could be useful:
ssh webserver "cd /path/to/your/repository.git/ && git-update-server-info"

It might be possible to trigger that update, possibly with a post-commit hook, but have not tried that yet.
Comment: Hi Egon. What does update-server-info actually do? Can you please explain it a bit?


(Vue+Express) Server side rendering failed because of hydration mismatches

Question: On Vue's official site, it gives a good and short example to show how to do ssr by vue.
(https://stackblitz.com/edit/vue-ssr-example-qaztqn?file=package.json)
I copied this example to my local machine and ran it successfully.
However, after I tried to bundle vue locally by vite, I got the hydration mismatch error:
index.0977acf5.js:2980 Hydration completed but contains mismatches.
Before my change, the official example imports vue from CDN in it's index.html. The only change I made is to bundle vue locally, then reference the whole bundled js file.
I uploaded my failed example to github: https://github.com/yangjiang3973/vue-ssr-demo
Can anyone take a look and tell me why this hydration error happen?
Thanks!
Comment: Please give a read to that one: https://stackoverflow.com/a/67978474/8816585 It's based on Nuxt is still relevant as of what is happening regarding the hydration issue. Simple debugging would be to toggle JS on and off to see what is different.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Hydration node mismatch may appear also if you have invalid html, e.g.

or

In the example above the nesting is illegal, you can't nest p inside p, or p inside span.
Browser corrects this error that's where SSR rendered piece of template diverges from what you have finally rendered in the browser.
Comment: As explained in depth here: https://stackoverflow.com/q/47862591/8816585


How to store JSON data array database if this data come from API in Laravel?

Question: I am working on online examination system on laravel when users get exam I want to receive some data from API and store in a database.
Data will be something like this.
{
    "user_id": [
        "420"
    ],
    "test_id": [
        "12"
    ],
    "question_id": [
        "1",
        "2",
        "3",
        "4"
    ]
}

My Controller
$fbres       = new Testapp;
$json        = $request->all();
$data        = $json;

$user_id     = $request->user_id;
$question_id = $request->question_id;
$test_id     = $request->test_id;

foreach ($data as $key)
{
    $user_id     = $key['user_id'];
    $test_id     = $key['test_id'];
    $question_id = $key['question_id'];

    $data1 = array(
        array('user_id'=> $user_id, 'question_id'=> $question_id, 'test_id'=> $test_id)
    );

    $fbres::insert($data1);
}

Comment: how is the database structure. how should questions store? is there any many to many relationship?
Comment: Possible duplicate of [Store array in Laravel 5.6](https://stackoverflow.com/questions/51981405/store-array-in-laravel-5-6)
Answer: Encode the array using json_encode() php method. and no need to call insert into loop. It's time consuming and may blast your DB.
$fbres       = new Testapp;
$json        = $request->all();
$data        = $json;
$data        = $request->ques;
$user_id     = $request->user_id;
$question_id = $request->question_id;
$test_id     = $request->test_id;

$finalData = array();
$blankArr = array();
//Check for array 1-d or 2-d
if(isset($data["user_id"])){
  array_push($blankArr, $data);
}else{
 $blankArr = $data;
}
foreach ($blankArr as $key => $value)
{
    $usr_id     = $value['user_id']['0'];
    $test_id     = $value['test_id']['0'];
    foreach($value['question_id'] as $k => $v){
         $finalData = array('user_id'=> $usr_id, 'question_id'=> $v, 'test_id'=> $test_id);

         $fbres::insert($finalData);
    }
}

Hope it will help you.
Comment: Error "Undefined index: user_id" in Loop
Comment: When i use print_r($data) it return "Array ( [user_id] => Array ( [0] => 420 ) [test_id] => Array ( [0] => 12 ) [question_id] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) )"
Comment: Check in your array user_id is coming or not? If not then use isset() method on $key[''] and let me know is it helping or not?
Comment: @brij try this. I have edited the code and let me know
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178678/discussion-between-amku91-and-brij).
Comment: Hey amku91 i need your help
Comment: What kind of help ?
Comment: Now, I want to store answers to the question same as  question_id
Comment: @brij It would be good if you create a new question with whole script whatever you have done till. I ll answer there.
Comment: https://stackoverflow.com/questions/52252896/how-to-store-json-multiple-array-data-database-in-laravel
Answer: Convert arrays to json string using json_encode function and then store it
$fbres = new Testapp;
$json = $request->all();
$data = $json;

$data = $request->ques;

$user_id = $request->user_id;
$question_id = $request->question_id;
$test_id     = $request->test_id;

 $data1 = array(
        array('user_id'=> json_encode($user_id), 'question_id'=> json_encode($question_id), 'test_id'=> json_encode($test_id))
    );
    $fbres::insert($data1);

Comment: It's throw error "Undefined index: user_id" in foreach loop
Comment: why u r using foreach ?
i have updated my answer, check now.


How to change import functions source spreadsheet

Question: I created a script to automatically create a new sheet daily. So every day the sheet is created and moved to the second position(code 1). My problem is that I need to update the corresponding import formulas connected to different sheets. This is the import formula: =IMPORTRANGE("1X2wkyMOpafUbcV7BBW0ZyFYL0vSFyehqy0IEzEUa9Zg","Today!2:9") The sheet "Today" needs to switch to the day previous as an archive list.
Code 1:
function NewDay() {
  var numberOfDaysForwardForNextTab = -1
  var numberOfDaysBackwardForDeleteTab = 60
  var rangeToClear = 'A3:M19'

  var ss = SpreadsheetApp.getActiveSpreadsheet();   // get the spreadsheet object
  SpreadsheetApp.setActiveSheet(ss.getSheets()[0]); // set the first sheet as active

  // Sets date for add tab & date for delete tab
  var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
  var today = new Date();
  var addWeek = Utilities.formatDate(new Date(today.getTime() + (numberOfDaysForwardForNextTab * MILLIS_PER_DAY)), "GMT+1", "MM-dd-yy");
  var deleteWeek = Utilities.formatDate(new Date(today.getTime() - (numberOfDaysBackwardForDeleteTab * MILLIS_PER_DAY)), "GMT+1", "MM-dd-yy");

  // Adds tab
  ss.duplicateActiveSheet(); //Copies current sheet
  ss.renameActiveSheet(addWeek); //Renames sheet to date from above
  ss.moveActiveSheet(2); //Moves sheet to the first position
}

Code 2:
function Example() {
  var numberOfDaysForwardForNextTab = -1
  var ss = SpreadsheetApp.getActiveSpreadsheet();   // get the spreadsheet object
  SpreadsheetApp.setActiveSheet(ss.getSheets()[0]); // set the first sheet as active

  // Sets date for add tab & date for delete tab
  var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
  var today = new Date();
  var addWeek = Utilities.formatDate(new Date(today.getTime() + (numberOfDaysForwardForNextTab * MILLIS_PER_DAY)), "GMT+1", "MM-dd-yy");
  var deleteWeek = Utilities.formatDate(new Date(today.getTime() - (numberOfDaysBackwardForDeleteTab * MILLIS_PER_DAY)), "GMT+1", "MM-dd-yy");

  var newformula = ('importrange ')
   var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A6').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName(addWeek), true);
  spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1X2wkyMOpafUbcV7BBW0ZyFYL0vSFyehqy0IEzEUa9Zg","'addWeek'!2:9")');
  spreadsheet.getRange('A18').activate();
  spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("157YxQP5waUniWPT8x-dbqzsqWP1-wlQWEpg9Z8See-c","'addWeek'!2:8")');
  spreadsheet.getRange('A30').activate();
  spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1Y75DWBCSnLzFH-YWukTPROmUu7tCmNRG68Lx2rpwTls","'addWeek'!2:8")');
  spreadsheet.getRange('A42').activate();
  spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1D8FA96acJbWmwVcN9lHE_pddtTdaCkCx3mXIdaN061k","'addWeek'!2:15")');
  spreadsheet.getRange('A61').activate();
  spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1cHI1arXkCOICuLEWydN_UEnmDw2ilXfzkT_Hs7ugU4I","'addWeek'!2:8")');
  spreadsheet.getRange('A73').activate();
  spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1vmTpOmnqGVY3zvD9ogzfDZKBHsx02MtJPbPHRU98paQ","'addWeek'!2:8")');
  spreadsheet.getRange('A74').activate();
}

Please Help Me, I'm so confused
Comment: This is not CSS related question. :D
Comment: Try it this way: `spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1X2wkyMOpafUbcV7BBW0ZyFYL0vSFyehqy0IEzEUa9Zg","' + addWeek + '!2:9")');
`
Comment: You might also have to escape the double quotes.  I'm not sure because I never use formulas.
Comment: What is the problem with the code? Are you getting any errors? Why is it not behaving in the way you want? What is the purpose of this line ` var newformula = ('importrange ')` ?
Comment: This worked perfectly. Thank you
Answer: To concatenate strings you need the + operator
Instead of:
spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1X2wkyMOpafUbcV7BBW0ZyFYL0vSFyehqy0IEzEUa9Zg","'addWeek'!2:9")');

You would need to do this:
spreadsheet.getCurrentCell().setFormula('=IMPORTRANGE("1X2wkyMOpafUbcV7BBW0ZyFYL0vSFyehqy0IEzEUa9Zg","' + addWeek + '!2:9")');


I want to open gmail inbox through my app

Question: How to open inbox in our apps.
final String ACCOUNT_TYPE_GOOGLE = "com.google";
final String[] FEATURES_MAIL = {
        "service_mail"
};
AccountManager.get(this).getAccountsByTypeAndFeatures(ACCOUNT_TYPE_GOOGLE, FEATURES_MAIL,
        new AccountManagerCallback() {
            @Override
            public void run(AccountManagerFuture future) {
                Account[] accounts = null;
                try {
                    accounts = future.getResult();
                    if (accounts != null && accounts.length > 0) {
                        String selectedAccount = accounts[0].name;
                        queryLabels(selectedAccount);
                    }

Comment: Does it have to be GMail? The usual way would be to use the SEND intent and then pick Gmail out of the list.
Comment: Welcome to SO. Please read the [FAQ] about how to ask good questions. Tell us your link you mentioned plus what you mean by "not working". Do you get any error? If so show them to us by editing your question and paste the stack trace there.
Answer: If you always want to open gmail, and sure that client has gmail application, you can use this to start gmail application, which has inbox as opening activity.
PackageManager manager = getPackageManager();
Intent i = manager.getLaunchIntentForPackage("com.google.android.gmail");
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);

Comment: thanks sir , but i want open inbox in app and with notification. send me proper code to this programm   by sandeep kushwah


looping over a list with multiple and selected the selected ones

Question: I'm working on code where I am getting two lists. I'm trying to use those lists to pre-select items in select box having the "multiple" attribute. However, I am unable to maintain the selections.
Code:
<select name="sbbox" id="sbbox" class="can" multiple>
  <cfloop list="#lstFinds#" index="k" delimiters=",">
    <option value="#k#" <cfif #listfindnocase(k,getproducts.ptype)#>selected</cfif>>#k#</option>
  </cfloop>
</select>

Sample values:

lstFinds = abc,xyz
getproducts.ptype also contains values like abc,xyz

I want to keep both selected, if both values exists for the user. If one exists, keep one selected. If none are selected, keep none.
I also tried using listContains, but it did not work.
Transferred from pastebin linkL
The ptype values are coming as comma separated in the database ie "abc,wed,mon,def". Whatever those values are, I need to match and selected the ones which have the same value in the listFind. I hope I made it clearer.
<cfset lstFinds = 'abc,xyz,def,www,kkr,mon,tue,wed'>

<cfquery name="getproducts" datasource="cdfg">
        select ptype
         from
        mytable
        where
        ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
</cfquery>

<select name="sbbox" id="sbbox" class="can" multiple>
  <cfloop list="#lstFinds#" index="k" delimiters=",">
    <option value="#k#" <cfif #listfindnocase(k,getproducts.ptype)#>selected</cfif>>#k#</option>
  </cfloop>
</select>

Comment: Switch your arguments around for listFind. The list is the first argument. When in doubt check the documentation
Comment: Your listFind function should have the list as the first argument and the value to find as the second
Comment: *getproducts.ptype also value like this: "abc,xyz"* If at all possible, do not store delimited lists. That kind of denormalized structure [suffers from a number of weaknesses](http://stackoverflow.com/questions/25437697/sql-query-multiple-tables-with-multiple-joins-and-column-field-with-comma-seper/25437961#25437961) (error prone, difficult to query, does not scale well) and makes it difficult for the db to do it's job effectively. A better structure is to store the related values in a junction table.
Comment: i did not get what exactly you trying to say, can you please clarify
Comment: changed it, but that does not solve the issue, i am facing
Comment: What is the value of K in each iteration?
Comment: k is the value of the first loop items - abc,xyz,def -
Comment: both can have the same values depending upon suppose lstFinds has [abc,xyz,def] and the getproducts.ptype has [def,abc], so i want the two to be selected
Comment: Could you please elaborate the question then? Show us some real data from the ptype field and what lstFinds would really contain for the same row. Something like http://pastebin.com/XrhDjCEv (I do understand that lstFinds isn't a column name), but this would still be a good way to present a snapshot of real data to us. You don't need to put it in a pastebin, I merely did because comments don't support formatting.
Comment: i am editing my question: Please check #update1
Comment: here is the pasbin : http://pastebin.com/tQHVp4yh
Comment: @MattBusche is right. Switch the arguments in listFind(). `selected>#k#`  or you can do it like `#k#` will work for cf9 and above.
Comment: no dude, it is still not working, no it does not show even selected .
Comment: Is the `Listlen(getproducts.ptype)` before the selectbox giving you the expected result?
Comment: As @MattBusche suggested, `listfindnocase(getproducts.ptype,k)` will work. Also, include `cfoutput` tags around the selectbox for displaying the `#k#` values.
Answer: There are three things wrong with this:
<cfloop list="#lstFinds#" index="k" delimiters=",">
<option value="#k#" <cfif #listfindnocase(k,getproducts.ptype)#>selected</cfif>>#k#</option>
</cfloop>

First, as others have mentioned, in the listfindnocase function, the list comes first.
Next, the reason you are not getting the desired results after sorting out the first problem, is that getproducts.ptype is not a list.  It is the value from the first row of the query.  To get all the values in a list, use the valuelist() function.
Finally, the correct syntax for having an option selected is selected="selected".  So the code block above should be this:
<cfloop list="#lstFinds#" index="k" delimiters=",">
<option value="#k#"
<cfif listfindnocase(ValueList(getproducts.ptype), k)>
selected="selected"
</cfif>>#k#
</option>
</cfloop>

Answer: Ok, the asker provided the following code via a Pastebin
<cfset lstFinds = 'abc,xyz,def,www,kkr,mon,tue,wed'>

<cfquery name="getproducts" datasource="cdfg">
    select ptype
     from
    mytable
    where
    ID = <cfqueryparam cfsqltype="cf_sql_integer" value="#id#">
</cfquery>

these are coming from database column ptype of a table as: abc,wed,mon,def

<select name="sbbox" id="sbbox" class="can" multiple>
  <cfloop list="#lstFinds#" index="k" delimiters=",">
    <option value="#k#" <cfif #listfindnocase(k,getproducts.ptype)#>selected</cfif>>#k#</option>
  </cfloop>
</select>

I ran the following code as at cflive.net
<cfset lstFinds = 'abc,xyz,def,www,kkr,mon,tue,wed'>

<cfset getProducts = {pType = "abc,wed,mon,def"}>

<cfoutput><select name="sbbox" id="sbbox" class="can"  multiple>
  <cfloop list="#lstFinds#" index="k" delimiters=",">
    <option value="#k#" <cfif #listfindnocase(getproducts.ptype,k)#>selected</cfif>>#k#</option>
  </cfloop>
  </select></cfoutput>

When I run this code, abc, def, mon, and wed are selected. Should these not be selected, or should others be checked?
This code appears to be doing what you are asking. The only changes I made

Changed the logic as per what Matt suggested in question comments.
Because I don't have the data to run a query against, I setup a getProducts structure with the key "pType" and the values as Asker suggested they might be. For the purpose here, my sample struct is functionally identical to a one-row query.

Finally, is it possible that you're trying to pull this from multiple rows? You might try
<cfset variables.ptypes = valuelist(getproducts.ptype)>
<cfoutput><select name="sbbox" id="sbbox" class="can" multiple>
  <cfloop list="#lstFinds#" index="k" delimiters=",">
    <option value="#k#" <cfif #listfindnocase(variables.ptypes,k)#>selected</cfif>>#k#</option>
  </cfloop>
  </select></cfoutput>

Comment: The style attributes you added are clutter.  The guy is trying to solve a logic problem.
Comment: Yeah, it was a tiny box i was tired of scrolling in, but you're 100 right, I'll pull them out of answer. Should have before I answered.


How to find the smallest distance(want as much as different problem solving skill for this question)

Question:
Find the shortest distance from A to D given that one must at least touch the BC once
This is a open type question, better use some simple methods i wanna know more different kind of problem solving skills for this question, the more simple the methods the better
Comment: If you have solved the problem then maybe you should edit your solution into the question so we don't waste our time telling you things you already know.
Comment: well, actually, i have solved this question but i wanna know more problem solving techniques to this question
Comment: Better with some easy method without using any differentiation
Comment: @Mathematics: Photons are tiny but their mathematical abilities should not be underestimated. They know that to minimize the path length, one should make the angle of incidence equal to the angle of reflection.
Answer: Hint: Reflect $CD$ in line $BC$. Then $D$ goes to say $D'$. Draw $AD'$.
Comment: Yup, this is what i use to solve this question, but can you solve with with different methods?
Comment: Because you asked for "without differentiation" in a comment, I assumed that the way you had done it was the standard calculus way.


Minecraft command unfindable unbalanced brackets

Question: I know that there been about three others persons that asked something like this, but the command is not so long:

/summon Skeleton ~ ~1 ~ {ActiveEffect:[{minecraft:speed,Amplifier:10,Duration:3600},{minecraft:health_boost,Amplifier:7,Duration:3600},{minecraft:jump_boost,Amplifier:7,Duration:3600},{minecraft:resistance,Amplifier:7,Duration:3600},{minecraft:strength,Amplifier:7,Duration:3600},{minecraft:glowing,Duration:3600}],HandItems:[{id:iron_sword},{id:shield}],ArmorItems:[{leather_helmet}],CustomName:Warrior,Visible:5,Equipment:[{id:397,Count:1},{CustomName:Warrior's Head}], DropChances:[1.0f]}

Without the tag, it make:

{[{},{},{},{},{},{}],[{},{}],[{}],,[{},{}],[]}

I checked and re-checked, but I just can't find where is the error.
Here is what the command block says:
Comment: A little bit of double checking would find the issue, I bet. You have a semicolon instead of a comma, I think. Not sure, though, because I don't play Minecraft.
Comment: Yes this is right; in fact, I followed the way to check the command's brackets with the already-have-an answer question but I still don't find it. If it's interest you, I've edited the question.
Comment: Except now you've fixed it. If you had done that prior to asking, you would have found the issue.
Answer: Breaking it down into a method-by-method format shows the issue:
/summon Skeleton ~ ~1 ~
{
    ActiveEffect:
    [{
        minecraft:speed,Amplifier:10,Duration:3600
    },
    {
        minecraft:health_boost,Amplifier:7,Duration:3600
    },
    {
        minecraft:jump_boost,Amplifier:7,Duration:3600
    };        <--- Here is your typo
    {
        minecraft:resistance,Amplifier:7,Duration:3600
    },
    {
        minecraft:strength,Amplifier:7,Duration:3600
    },
    {
        minecraft:glowing,Duration:3600
    }],
    HandItems:
    [{
        id:iron_sword
    },
    {
        id:shield
    }],
    ArmorItems:
    [{
        leather_helmet
    }],
    CustomName:Warrior,Visible:5,Equipment:
    [{
        id:397,Count:1
    },
    {
        CustomName:Warrior's Head
    }],
    DropChances:[1.0f]
}

By breaking it down, you can see you have used a ; about halfway through your ActiveEffect block. This is likely what's throwing out your command, as in most programming languages, this is used to terminate the line.
In this command however, as from your screenshot, the error is suggesting a parsing fail - caused by an unexpected character: the ;.
EDIT: while this isn't actually causing the error, (Courtesy of Kcats) you are missing the syntax for the declaration of the leather helmet - it should be id:leather_helmet
Comment: The problem is probably not that the semicolon "ends the line", and rather that they simply have a semicolon where there's supposed to be a comma, which can cause any kind of parsing error.
Comment: also id: is missing for leather_helmet
Comment: Thank you very much, but the command don't seem to work as well as it is: the skeleton acts very weird...
Comment: @Kimatuy I don't believe that the command has anything to do with the AI of the skeleton, the only thing you have changed is the speed and the jump height. If it's doing anything other than that, I can't see how the command you have used would be affecting it's behaviour


Place button as LAST column in gridview

Question: I have a grid view and I add columns to it by code:
//Retrieve "Table" from database
gridOffers.DataSource = table;
gridOffers.DataBind();

The columns added by code are being added AFTER the button, which is not what I need:

How do I make sure the Add To Cart button the very last thing?
Source of gridView:
<Columns>
             <asp:ImageField DataImageUrlField="ImageUrl" ControlStyle-Width="100"
                ControlStyle-Height = "100" HeaderText = "Preview Image"
                 ItemStyle-HorizontalAlign="Center">
<ControlStyle Height="100px" Width="100px"></ControlStyle>

<ItemStyle HorizontalAlign="Center"></ItemStyle>
             </asp:ImageField>
             <asp:TemplateField ShowHeader="False">
                 <ItemTemplate>
                     <asp:Button ID="Button1" runat="server" CausesValidation="false"
                         CommandName="btnAddToCart" Text="Add To Cart" />
                 </ItemTemplate>
             </asp:TemplateField>
        </Columns>

Comment: What worked for you ? I have same issue
Answer: You're defining columns in the GridView source AND by databinding a data source to the GridView. Therefore you have two sources of columns; there may or may not be a guaranteed order in which columns are added to the GridView.
Instead, why not set AutoGenerateColumns for the GridView to False and then explicitly specify the column order by using BoundField for each field you want from the data source in your GridView source followed by your image and button columns?
Comment: I assume that he asks how to control the order of the columns even when `AutoGenerateColumns` **is** set to `true`. The order is guaranteed since the declaratively added controls will be created first  and then then the databound/manually created. That is documented in the [Page's Lifecycle](http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.80%29.aspx)(search "controls created declaratively").
Comment: @Tim Schmelter: whilst I believe you are correct in terms of control creation order, unless I'm missing something the page life cycle link only says that the Init and Load events for a control added at run time might occur later than controls created declaratively. It does include controls in templates of data bound controls as having potentially later events. Since the OP had not explicitly mentioned that keeping AutoGenerateColumns as True was important, I suggested a solution where you can be clear about your intent ie the column order is explicit.
Answer: I don't know if there's a less hacky way, but you could use RowDataBound to change the order, so that the AutoGenerated columns are followed by your other columns:
protected void gridOffers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    TableCell cell = e.Row.Cells[0];
    e.Row.Cells.RemoveAt(0);
    //Move first to the end
    e.Row.Cells.Add(cell);
    cell = e.Row.Cells[0];
    e.Row.Cells.RemoveAt(0);
    //Move second to the end
    e.Row.Cells.Add(cell);
}

Comment: +1, in my experience there is *not* a less hacky way to do this while still having the auto-generated columns in there.
Comment: +1, Thank you. However I can do without auto generated columns, I just didn't know about it.
Answer: Do you have AutoGenerateColumns set to true on the Gridview? If so set this to false and manually set the fields in the grid using asp:BoundField setting the DataField to the name of the field from the datasource.
This way you can set the exact order of your columns.
Comment: You can see in the image that he has `AutogenerateColumns=true` ("Auto-generate-fields"). I assume that he asks how to control the order of the columns even when `AutoGenerateColumns` **is** set to `true`.

Place button as LAST column in gridview


How to easily switch to angular 2

Question: So I learn angularJs not long ago, and I'm just getting started to get comfortable with it. But angular 2 is on the way and I have 2 major question:
1) Should I stop learning and working with angular 1 and start learning angular 2 instead?
I know a little about angular 2 and I know almost every thing has changed. So
2) What I know from angular 1 is any good in learning angular 2? Or should I learn angular 2 like it's a whole new framework? Is there any good way or guide to switch from angular 1 to 2?
Thanks in advance for your answers.
Comment: Angular (v2) and AngularJS (v1) have 7 characters in common. The rest is totally different.
Comment: duplicate: http://stackoverflow.com/questions/34114593/angular-vs-angular-2?rq=1
Answer:
I learn angularJs not long ago

Then, this is the perfect time to start learning Angular 2, too. Starting a new language version while you have not already spend a lot of time on another one is a good choice in my opinion. However since Angular 2 is still in RC you should not completely leave learning Angular 1.x and start with Angular 2.

1) Should I stop learning and working with angular 1 and start
  learning angular 2 instead?

No, even though the future of Angular framework seems to be Angular 2, this version is still in RC and building large apps using it would be a high risk.Angular 1.x compared to Angular 2 is more stable on this aspect. Angular 2 is constantly evolving, every few weeks there are totally new concepts included.
You should not stop learning Angular 1.x but, you should start learning Angular 2, too.

2) What I know from angular 1 is any good in learning angular 2?

Although there are a lot of changes like between these versions they still have similarities.For instance, in Angular 2 the concept of controllers does not exist, but they use Components. ng-if and ng-for directives from Angular 1.x look like *ngIf and *ngFor in Angular 2.  The best resource to compare the two versions is their official website which you can find here here.

Is there any good way or guide to switch from angular 1 to 2?

Although you can still find very useful information about upgrading from Angular 1.x to Angular 2 on their official website
 I would suggest that you treat Angular 2 as a completely new framework and start it from zero.Also the knowledge you already have about Angular 1.x will be helpful since there are concepts that have not changed that much. There are plenty of tutorials available online for free that you could use.
My favorite YouTube playlists are:

Angular 2 Start
Angular 2 Basics Course
Build Angular 2 Weather App
Comment: I will suggest 1 more playlist here, Learn Angular2 step by step: https://www.youtube.com/watch?v=5DXkozJ7mp0&list=PLFtLsSgifot9PrUPDWcvH3mBVjNkw9wzs
Answer: Well , This is the major question for all angular2 beginners who knows angular1 ... ,
Just imagine you don't know angularjs1 then Definitely you are more comfortable with angular2 ... The thing is Angular is the future that is the unwritten truth ... Definitely Angular1 is not going to die ...but It may be loose from the competition ... You have to consider following things to choose angular2 ...

Type Script (Great Coding Structure)
Componets (Great Library Support )
Rich Third party library Support
Creator the Giant (Google )

Finally You have to go with the future ... (Angular2)

How to easily switch to angular 2


How can I remove the coating from black iron pipe?

Question: I'm building a couple industrial style tables, using black pipe from Home Depot for the legs. The fittings and smaller nipples are all a faded gray color that perfectly complements the black cherry stain I used on the wood. But the longer segments of pipe come in a black color that is too dark and very patchy and uneven. I would really like to remove it and ideally match the color of the fittings.
Based on some research, I tried using mineral spirits to clean them up. This had very little effect. Next I tried sanding. This does break through the black, but is very slow going and the sand paper quickly fills up with black goop. Also this cuts all the way through to the underlying metal, which results in a shinier color than the fittings. There's got to be a better way.
According to this video, the black stuff is mill scale and can be removed with Jasco paint and epoxy remover. This does look effective from the clip, but the Jasco stuff is $45/gal and seems pretty toxic. Also I'm skeptical that the black stuff is actually mill scale.
Before I drop the money on the Jasco, can anyone tell me what the stuff is and maybe recommend a less toxic way of removing it? I wouldn't mind painting over it if I can figure out how to properly prime the current surface so the paint stays on.
Comment: Are you opposed to leaving it there and painting it solid black ?  If its hard to remove is unlikely to flake off over time.
Comment: I use lacquer thinner
Comment: I'm totally open to painting, and leaning that direction. Do you have any suggestions for preparing the black surface to be painted over? Mineral spirits + sanding resulted in a goopey mess that never wiped clean. Highly doubt paint would adhere.
Comment: a propane flame or a fire will remove the coating, but will make toxic smoke.
Comment: What does "less toxic" mean? Any of these materials will kill you if you eat enough of them. Use appropriate safety precautions and dispose of everything properly.
Answer: It is "mill varnish" , nothing to do with mill scale. I find no definition in the  ASTM index. Very likely it is a varnish ; A resin plus a solvent/vehicle. Mineral spirits or gasoline should take it off. Different mills may use different products as there is no firm definition. It is applied to new , relatively scale free pipe. A industrial purchaser does not want to see his brand new pipe delivery covered with rust. Oil companies sometime order pipe with no mill varnish as it is a nuisance to remove. I have seen it hard like paint , I have seen is still gooey. Mill scale is thick black iron oxide scale; Fe O and Fe3 O4. The mill removes scale with concentrated sulfuric acid. I have seen some new steel products with scale allowed to weather , rust ( complex hydrated Fe3 O4 - brown) will loosed the mill scale so blast cleaning is easier
Comment: I heard that long age the nasty black liquid collected from the steel mill coke ovens ,was cut back with solvent and used as a coating.; probably the start of "mill varnish". Today that is illegal .
Answer: Simple answer, use PVC pipe cleaner and plenty of cloth rags. The pipe cleaner is basically acetone (don't use the purple primer!) but comes with the convenient applicator. Dissolves the black coating gunk instantly and you can wipe it away quickly with a rag, but act fast. The acetone evaporates quickly and the gunk starts to set again. I just did 12 ft. of pipe this way, and it brings the surface to a grey smooth look that matches the shorter threaded nipples of the same pipe size that usually come wrapped in clear plastic. You will likely need some coating back on top of this, even if you like the smooth grey look and choose not to paint, as it appeared like a tiny bit of rust flashed up on the surface of one pipe. I chose to rub mine down with black shoe polish. No heavy coating, but serves as a decent rust inhibitor for indoor use, and the pipes will be mounted out of reach so no chance it will rub off on someone. I had mixed piping from two different manufacturers, and the PVC pipe cleaner worked excellently on both coatings.
Answer: Mill scale is the iron interacting with air while the metal is very hot. It's almost one and the same as the surface rather than a coating on it. The problem is removing it without removing the steel underneath
Grinding with a different disks will work, as will a steel brush, or sandpaper.
The easiest is probably using muriatic acid. It's cheap at about $10 / gal. Be careful when using it and use appropriate precautions. Here's a video on it and it shows how easy and well it works
Comment: It doesn't look like pictures/videos of mill scale I've seen online. It seems more like some sort of a powdery, greasy paint, for lack of a better description.
Comment: I was responding to your question where you state that you have mill scale to remove. If it' s not mill scale, then it's a different question which then, yes, requires a different answer.
Answer: Slow... but low toxicity
Leave the pipe outside until it's nice and rusty. Then remove the rust by electrolysis (washing soda or baking soda in water work for an electrolyte.) This happens to leave a pretty grayish "clean" surface, IF you rinse with hot water and immediately dry it (leave it sitting around wet and it will re-rust.)
It's possible that you can skip the "let it get rusty" part, but I know for a fact that starting from rusty gets results that are similar to what you describe wanting.
Comment: I don't think it's going to rust as long as it has the thick black coating on it. Pretty sure that's what it's for. Or do you mean I should grind it down and then let it rust?
Answer: It's some sort of rust preventative, possibly fish oil,  fish oil will evetually set like varnish (it can take several weeks to set in warm weather) but while tacky can be cleaned off using white spirit, or possibly grease remover.
caustic soda solution will remove it too. caustic soda relatively cheap, not technically toxic, but is very corrosive and a powerful irritant. keep away from eyes, skin, and aluminium.
Answer: Pure turpentine worked fast and easy. Just saturate a rag and wipe a few times.


Flutter Is it possible to fade in and fade out markers for google_maps_flutter?

Question: I think it would look nice if the markers faded in and out as they were presented. Is this possible with google_maps_flutter?
Answer: So, good news and bad news.
The good news is that it looks like markers have been made into widgets according to this entry in the google_maps_flutter pull requests here: https://github.com/flutter/plugins/pull/1240
which would (probably) mean that they can be manipulated by other flutter features.
The bad news is that I was unable to find any documentation on this feature (which isn't too surprising, given that this pull request was committed on March 6th, so it's fresh off the presses.) I posted a question to the writer of that pull request, user iskakaushik and asked if those widgets will be open to AnimatedOpacity, which would do exactly what you want.
So, I would check that thread and see how he responds.  It looks like you're going to be one of the first users of that feature!
Comment: Thank you for that. I hope it becomes possible soon!
Comment: I do too.  if I get a response, I'll post it here.
Comment: Any news on fading in out google maps markers I would be happy to upvote an answer ? : )


Python: installing psychopy audiolib

Question: I'm really sorry if this is a stupid question, but here it is.
I'm using Python and I've installed psychopy via anaconda command prompt in class. Now I want to use psychopy sound functions. So I tried to import sound, but get that there's no API found and that I should install pyo or pygame, which I tried to do in the anaconda command prompt, but that doesn't work either.
Since I'm not familiar working with this kind of things, so I really have no idea how to solve this. I hope someone can help. I've tried looking on the internet, but can't find any solutions there either.
Answer: Both pygame and pyo cannot be installed with pip. You need to download them from external links and install manually.

pygame: http://www.pygame.org/download.shtml
pyo: http://ajaxsoundstudio.com/pyodoc/download.html

@edit Note that those packages will only work with 32-bit Python 2.7, so if you're using a 64-bit version of Python or Python 3.x you won't be able to use them.
Comment: I installed pyo, but how should I import it in Python?
Comment: simple `import pyo` should be sufficient assuming that you installed `pyo` in your anaconda distribution
Comment: I installed it in Anaconda, but when I try import pyo, it gives me the following error: import pyo

  File "", line 1, in
    import pyo

  File "C:\Users\Ineke\Anaconda\lib\site-packages\pyo.py", line 21, in
    import pyolib.analysis as analysis

  File "C:\Users\Ineke\Anaconda\lib\site-packages\pyolib\analysis.py", line 30, in
    from _core import *

  File "C:\Users\Ineke\Anaconda\lib\site-packages\pyolib\_core.py", line 32, in
    from _pyo import *

ImportError: DLL load failed: %1 is geen geldige Win32-toepassing.
Comment: what version of `python` are you using? 2.7 or 3.x?
Comment: Python 2.7.10 for 64 bits, I installed this from pyo: pyo_0.7.7_py2.7_setup.exe : Windows (Win 7 to 10), python 2.7, 32-bit from http://ajaxsoundstudio.com/software/pyo/. Thanks for all the help!
Comment: note that those packages will only work with 32-bit `python 2.7`, so if you're using a 64-bit version of `python` or `python 3.x` you won't be able to use them

Python: installing psychopy audiolib


Reading variables when they're initialized

Question: Although this is a newbie question, I was confused on how the value of the variable is read?
int a = 7;

would it be left to right or right to left?
also this:
//X is a supper class of Y and Z which are sibblings.
public class RunTimeCastDemo {

    public static void main(String args[]) {
            X x = new X();
            Y y = new Y();
            Z z = new Z();
            X xy = new Y(); // compiles ok (up the hierarchy)
            X xz = new Z(); // compiles ok (up the hierarchy)
            //      Y yz = new Z();   incompatible type (siblings)
            //      Y y1 = new X();   X is not a Y
            //      Z z1 = new X();   X is not a Z
            X x1 = y; // compiles ok (y is subclass of X)
            X x2 = z; // compiles ok (z is subclass of X)
            Y y1 = (Y) x; // compiles ok but produces runtime error
            Z z1 = (Z) x; // compiles ok but produces runtime error
            Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y)
            Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z)
            //      Y y3 = (Y) z;     inconvertible types (siblings)
            //      Z z3 = (Z) y;     inconvertible types (siblings)
            Object o = z;
            Object o1 = (Y) o; // compiles ok but produces runtime error
        }
    }

I don't get how the superclass = new subclass is read
 X xy = new Y(); // compiles ok (up the hierarchy)
    X xz = new Z(); // compiles ok (up the hierarchy)

(Why would it be up the hierarchy, if X is the superclass of them? should it not be down?)
Comment: The thumb rule is you can always use supertype variable to refer a subtype object.
Comment: How is it read? You have two choices: either a = 7, or 7 = a. In Java you can't reassign a primitive integer, so only one way makes sense, no?
Comment: thank you @DaveNewton but what if you're dealing with Object assignments to variables? Do the same things apply?
EX:
Superclass X = subclass Y;
can it be read as X = subclass Y
or Y = Superclass X?
Comment: @muddayard ... Assignment is assignment, regardless of the type(s).
Answer:
...how the value of the variable is read?

For an = (assignment) operation, the value on the right is evaluated and stored into the variable on the left. So in your example, the 7 is evaluated first and stored into a. If the right hand side was more complicated, it would be evaluated left-to-right before being stored into the variable on the left.

Why would it be up the hierarchy, if X is the superclass of them? should it not be down?

It is permissible to store a subclass as its superclass because the subclass implements all the functionality of the superclass. So, if X defines method Test(), and Y is a subclass of X, then Y implements the method as well. So you can have an instance of Y and store it in a variable typed for X because all of X's functionality is available in Y.
Comment: @Fls'Zen :D thank you for your help! I actually understood your explanations unlike my textbook >_>
Comment: okay, that did clarify it for me, however, I am a bit confused on this: (referring back to the code above)

 X xy = new Y(); // compiles ok (up the hierarchy)
What does it mean when xy is 'type' X but refers to object Y?
Can xy access all of object Y's methods or do they require casts?
Comment: For `X xy = new Y()`, you wouldn't be able to call `xy.YMethod()` without a cast because `xy` is the `X` type. The `Y` object isn't modified when it is stored into an `X` variable, but the case is required because you could also do, for example, `X xy = new Z()`, where `Z` is also a subclass of `X`. If you then tried running `((Y)xy).YMethod()`, the cast would fail because the object itself is a `Z`. So I rambled on a bit, but in short, yes, if an object is stored as its supertype, then you'll need to cast it to the subtype if you need to access any subtype's methods.
Comment: so in order for the variable to access the object's method, it would have to be the same type too (without using a cast)?
Y xy = new Y(); xy.YMethod();
this would require no cast but this would?:
X xy = new Y(); ((Y)xy).YMethod();
Comment: Yes, that's it! The variable needs to be of a type that knows about the method, otherwise you'll get a compile error.


Normal distribution and algebra problem

Question: Bags of cement are labeled $25 \operatorname{kg}$. The bags are filled by machine and the actual weights are normally distributed with mean 26.0 kg and standard deviation $0.50 \operatorname{kg}$. It is decided to purchase a more accurate machine for filling the bags. The new mean is $25.5$ and the standard deviation is $.255$. The cost of the new machine is $\$5000$. Cement sells for $\$0.80$ per $\operatorname{kg}$. Compared to the cost of operating with a $26 \operatorname{kg}$ mean, how many bags must be filled in order to recover the cost of the new equipment?
I'm unsure of why the answer is $12,500  --- 5000 / (0.5 \cdot 0.8 )$
Why isn't it $20.4$ because of $5000 / (25.5 \cdot 0.8)$? I know that the question wants to compare the new mean with the old, but I'm not quite clear on what that means?
Answer: You know that the old machine is underselling each bag by an average of $\mu _1 - 25 = 1 {\rm kg}$, and the new machine is underselling each bag by an average of $\mu _2 - 25 = 0.5{\rm kg}$.
Hence the average savings per bag by switching to the new machine is $1 {\rm kg} - 0.5 {\rm kg} = 0.5 {\rm kg}$.
Since the cement sells for \$0.80 a kilo, this is an average savings of $0.5 {\rm kg} \cdot 0.8 {\rm \$/kg} = {\rm \$ 0.40}$ per bag.
Hence to recoup the full investment, the company needs to sell $$n = \frac{\rm \$5,000}{\rm \$ 0.40} = {\rm 12,500\; bags}$$ to recoup the investment.
Answer: On average the weight of a bag is only 0,5 kg (=25.5-25) over 25 kg with the new maschine-instead of 1 kg (=26-25) . The equation is $\Delta e=p \cdot \Delta w\cdot q$.
$\Delta e$= difference of earnings=$5,000
$\Delta w$=difference of the weights per bag=1 kg/bag-0.5 kg/bag=0.5 kg/bag
q=amount of bags
p=price of a bag of cement=$0.8/kg
You have to solve the equation for q.
Thus on average you have sell 12,500 bags to recover the costs. In this calculation the concept of the expected value has been used.
Remark:
It is not sure, that you recover the costs. With the sample size of 12,500 bags, there is a possibility, that you do not recover the costs, because the weights of the bags are random variables. It is also possible, that your additional earnings are higher than
$5,000.

Normal distribution and algebra problem


What's the best way to keep all section headers visible in a long collapsible sidebar menu?

Question: I have a sidebar menu with 4 expandable sections. Each section can potentially expand to the point where it will push the other section titles off the screen.
At the moment, I've got the section titles stickied to the bottom of the screen if a section is too long so that users can still quickly switch sections without having to scroll too far.

Is there a better way to keep all the section titles visible without forcing users to look at the top and bottom of the menu to navigate?
Are there better design patterns for sidebar navigation that would work better with this much text than an accordion menu?
EDIT: Just to clarify, this is a sidebar menu on a website, not a phone app. The image is only pertaining to the sidebar and isn't the entire site design.
Comment: @pathfinder Absolutely, the tricky bit is making sure that it's clear that the content inside the open item scrolls separately from the rest of the sidebar.
Comment: That is essentially an accordion menu. Pretty standard option. That said, what's not standard is a paragraph of text for each link. It may make perfect sense for your needs, but that's somewhat atypical. If it makes sense to have that much text, it may make more sense to consider an index or TOC type of navigation for your site rather than a side bar.
Comment: @DA01 Unfortunately, I effectively have to condense a filtered feed into a sidebar... perhaps a better way of phrasing my question would be to ask if there are types of sidebar navigation that would be more suitable than an accordion menu? Thanks for helping me clarify my question :)
Comment: I think you handled it in a really good way. If you don't mind I am going to use this idea in a few places I was trying to figure out how to handle an accordion that has really long content :) I am assuming the content inside the open item still scrolls.
Answer: Considering the width of your image, I assume it's a phone app, although it may also be a narrow column on a web site. In any case, you can have just a short excerpt of the content and an indication to see the rest on another screen/page, it could three dots, a link like "more content" or any other method that you like.
That works well for what you have as articles now, but if you also need a solution for the sections, then you have to change the design, using a Table of Content, as suggested by @DA01 may work very well.
Answer: You could place bullits (for instance: dots) in a vertical side menu that represent the sections. On touch the menu should show all the titles next to the bullits, or you could navigate immediately to the section selected. It depends on how well your user would know the content and if they are discovering or navigating.
example: https://www.apple.com/nl/iphone-5s/
Comment: Sorry, I don't think I was very clear, but it's for a website and not specifically a smartphone app. I'll edit the original post to clarify that.
It sounds like the touch functionality you're referring to could be replicated with hover, but using bullets as an indicator of available content would be more useful if I was trying to save horizontal screen real estate, and not so much with keeping all the section titles visible at all times.
Answer: You could use a variation of the Multi-Toggle with Active Parent Links Design pattern. Perhaps sticking your Parent links left, while placing your expandable menu items to the right of the menu structure.
http://codepen.io/micahgodbolt/full/mnLiF

I do think that sticking parent menu links to the bottom of the screen could be problematic considering how screen sizes can vary so significantly. What if the screen height is so small that the menu can't expand at all?
It seems like this is a perfect example of a content issue. I'm not sure there is a better approach beyond addressing the CONTENT length for your menu to deal with the size of the sub-sections. Can you just show the headline of the article in the sub-menu, do you need the whole description and "view" link?
You could also add a scroll bar to your sub-menu to keep it at a max-size. Also clunky.
Comment: Yup, varying screen sizes is definitely my biggest problem with this. Unfortunately, the design requirements I have to work within are effectively creating a feed reader in a sidebar. I'm guessing I'm out of options at this point, but thanks anyway!


Change of Sign Of Continuous Function

Question: Prove that if there is a continuous function $f(x)$ such that $f(a)<0$ and $f(b)>0$ then there exists a $a<c<b$ such that $$f(c)=0$$ and $f(x)$ does not change sign in any of the intervals $(c-\delta, c)$ and $(c, c+\delta)$ for some $\delta>0$ but $f(x)$ has opposite signs on these intervals.
Note that the intermediate value theorem implies the existence of $c$ such that $f(c) = 0$.
As suggested in the comment, there are continuous functions $f$ with $c$ such that $f(c)=0$ but $f$ is not of fixed sign on both side. For example, given the function
\begin{align}
f: (-1, 1) \to \mathbb R,\ \ \ \ \ \ f(x) = \begin{cases} x\sin \frac 1x, & \text{ if } x\neq 0, \\ 0 & \text{ if } x=0 \end{cases}
\end{align}
then $f(0) = 0$ but we cannot find such $\delta$. But we can find another $c\neq 0$ with that property.
Comment: Does this answer your question? [Proof that if f(a)<0 and f(b)>0 f and is continuous on \[a,b\] then f changes sign at some c in (a,b)](https://math.stackexchange.com/questions/2994771/proof-that-if-fa0-and-fb0-f-and-is-continuous-on-a-b-then-f-changes-sign)
Comment: Please find that $\delta$.
Comment: Consider $f(x)=x\sin\frac{1}{x}$ for $x\not=0$ and $f(0)=0$.
Comment: https://en.wikipedia.org/wiki/Intermediate_value_theorem#:~:text=In%20mathematical%20analysis%2C%20the%20intermediate,some%20point%20within%20the%20interval.&text=The%20image%20of%20a%20continuous,interval%20is%20itself%20an%20interval.
Comment: I am not asking about IVT, plz read the question carefully
Comment: This function has the above property
Comment: But in your example you haven't given $a$ and $b$ as mentioned in the question
Comment: Take $a=-\epsilon$ and $b=\delta$ where $\epsilon,\delta$ are suitable positives.
Comment: Almost. Take $a = -\frac 2 {3\pi}$ and $b= \frac2\pi$.
Comment: Chose $c=\frac{1}{4π}$ and chose $\delta$ sufficiently close to $\frac{1}{4π}$
Comment: Chose $\delta=\frac{1}{25π}$
Comment: Zoom it as long as you want to find such $\delta$.           https://www.geogebra.org/classic/ssgkmepa
Comment: I proved that the function you gave in your example has the above property
Comment: Nice. Write your proof then.
Comment: Whenever $x$ lies in the interval $(\frac{1}{4π}, \frac{1}{4π}+\frac{1}{25π})$ then it is easy to show that $\frac{1}{x}$ lies in $(3π, 4π)$ and hence $xsin(\frac{1}{x})$ is negative in this interval. Similarly we can show that when $x$ lies in the interval $(\frac{1}{4π}-\frac{1}{25π}, \frac{1}{4π})$ then $xsin(\frac{1}{x})$ is positive and hence the function has the above property
Comment: @player3236 the strong form of IVT proves the case when there are finitely many roots of $f(x)$ on $(a, b)$ and not the case when $f(x)$ has infinitely many roots in the interval $(a, b)$
Comment: @player3236 the strong form of IVT proves the case when there are finitely many roots of $f(x)$ on $(a, b)$ and not the case when $f(x)$ has infinitely many roots in the interval $(a, b)$
Comment: @user763338: By "opposite signs" do you mean _strictly_ opposite?
Comment: Yes I mean strictly opposite
Comment: So a counterexample would be a continuous function with no isolated zeros. This smells like a cantor set example. (A cantorexample, if you will.)
Answer: Quasi gives a good counterexample to the question as asked, but we can also find a counterexample that is nonconstant on every open interval of $[a,b]$.
Let $f_0$ be the zero function on $[0,1]$. Define a sequence $f_k$ by, at the $k{th}$ step in the construction of the ternary cantor set, adding triangle functions supported on the removed intervals, scaled by $(-1)^{k+1}$.
(By "triangle function" I mean a function defined on an interval $I$ such that the union of $I\times\{0\}$ with its graph is an equilateral triangle.)
The sequence $f_k$ will converge to some continuous $f$. Choose $a,b$ such that $f(a) < 0$ and $f(b) > 0$. The zero set of $f$ is the restriction of the ternary Cantor set to $[a,b]$. As this is a perfect set, the function $f$ has no isolated zeros, and because between any two zeros $f$ changes sign, it will change sign infinitely often in any neighborhood of any zero.
Comment: My revised post was worked out independently, but it's clear that it's in the same spirit as your answer. Plus 1 for yours.
Answer: For an easy counterexample, let $f:\mathbb{R}\to\mathbb{R}$ be defined by
$$
f(x)=
\begin{cases}
x+1&\text{if}\;x < -1\\[4pt]
0&\text{if}\;-1 \le x \le 1\\[4pt]
x-1&\text{if}\;x > 1\\[4pt]
\end{cases}
$$
and let $a=-2,b=2$.

But suppose we require that $f$ is not identically zero on any open interval?

With that additional assumption, I think the following will still yield a counterexample . . .

Let $C$ denote the Cantor set, and let $J=[0,1]{\setminus}C$

For each $x\in J$, let $s(x)=(-1)^n$, where $n$ is the number of digits before the first digit of $1$ in the ternary representation of $x$.

Since $C$ is closed, for all $x\in J$, the distance $d(x,C)$ is positive.

Let $f:\mathbb{R}\to\mathbb{R}$ be defined by
$$
f(x)=
\begin{cases}
x&\text{if}\;x < 0\\[4pt]
0&\text{if}\;x \in C\\[4pt]
s(x)d(x,C)&\text{if}\;x\in J\\[4pt]
x-1&\text{if}\;x >1\\
\end{cases}
$$
and let $a=-1,b=2$.

Then there does not exist $c\in (a,b)$ satisfying the specified conditions.
Comment: But what is the function is not constant on any interval
Comment: It's a good question.
Comment: Can you give the proof when the function is not constant
Comment: I'll think about it . . .
Comment: Both of these counterexamples are well done, +1 to your answer

Change of Sign Of Continuous Function


Showing $\psi \colon G \rightarrow G$ is bijective requires only showing injectivity?

Question: This is from a past paper. I will write the question in full, but it is only one step I do not understand (the first step):
"Let $G$ be a finite abelian subgroup. Let $\psi \colon G \rightarrow G$ be given by $\psi(g)=g^2$. Show that if $|G|$ is odd, then $\psi$ is bijective."
Then the first step given in the explanatory solution is:
"Since $\psi$ is a function from the finite set $G$ to itself, it's sufficient to show that $\psi$ is injective".
However I cannot see how the above statement follows simply from knowing that $\psi$ is a function from $G$ to $G$.
Thanks
Comment: You can look at this graphically with venn diagrams and arrows between them. After you have made |G| choices of arrows such that the function is injective, every element must have been hit exactly once.
Comment: See [this question](https://math.stackexchange.com/questions/57913/suppose-that-g-is-a-finite-nonabelian-group-with-odd-order-show-s-is-surjectiv?rq=1).
Answer: Suppose the elements of $G$ be $\{g_1,g_2,\cdots,g_{2n+1}\}$. Now let $\exists~g\in G$, $g\ne e$, such that $g^2=e$. Then consider the set $A=\{g_1g,g_2g,\cdots,g_{2n+1}g\}\subseteq G$. Now if $g_ig=g_jg$, the post multiplying with $g^{-1}$ on both sides we get $g_i=g_j$. So all the elements of $A$ are distinct and $|A|=|G|$. So $A=G$. However $g_ig=g_j\implies g_i=g_jg$, so there are an even number of elements in $A$, contradictory to our assumption. So there cannot exist a $g\ne e$ in $G$ such that $g^2=e$. Hence $\psi$ is an isomorphism.
Answer: If $G$ is finite and $\psi\colon G\longrightarrow G$ is an injective function, then $\#\psi(G)=\#G$ (because $\psi$ is injective). But the only subset of $G$ with $\#G$ elements is $G$ itself. Therefore $\psi(G)=G$. In other words, $\psi$ is surjective.


20 amp circuit breaker trips after a few minutes or sometimes hours later

Question: The 20 amp circuit breaker that controls my man cave, my rear patio lights including a lampost, and some outlets in my back yard started tripping about two weeks ago.  Currently the lights and outlets in backyard are not in use and have not been since late October.
As early as yesterday, I unplugged, and put all light switches in the off position that is controlled by that breaker.  The breaker held for about 7 hours before tripping late last night.
The outlets and lampost in back yard are all new.  They were installed last May when I had some work done on my back yard.  Never was there any problem after installation up until 2 weeks ago.  We live in NY and did have a major Blizzard about 3 weeks ago as well as freezing temp over the last week or so.  I checked the outlets and all are dry and wiring is all intact.
Any other suggestions??  Quite stressful not being able to use my man cave and the thought of all the $$$ it may take to correct!
Comment: Is this a standard breaker in the breaker box with everything else?  Its it a GFCI breaker or a GFCI outlet?
Comment: First step would be to use a clamp on ammeter, and see how much current the circuit is drawing.  If you're not comfortable opening up the service panel, you're going to want to contact an Electrician.  NOTE: The clamp only goes around the ungrounded (hot) conductor, not the entire cable.
Comment: You said you have an outlet under the bar. Is the light switch also outside? I am wondering if your supply line was damaged under the ground, now with water /ice it is conducting causing the breaker to trip.
I have also seen metal boxes wear a hole through the hot wire insulation causing intermittent shorts. Can you isolate the outside power and see if the problem stops as a way to try and identify where the issue is.
Comment: So you were able to cut off power to the lights outside? If they're disconnected, then the storm shouldn't matter. Of course the guess is a short somewhere, but I don't know that it's anything we can help with. -- You're not using anything more on this circuit now, right? No more heaters, appliances, etc. than usual?
Comment: Standard breaker in box.  One outdoor outlet is a GFCI outlet.  Another outlet outside is not GFCI, but under cover of an outdoor bar.  After resetting the breaker, the GFCI outlet works fine until of course the circuit breaker trips again.
Comment: TFK, no, power to the lights was not disconnected.  They have just been in the off position on light switch.  Both lampost and outdoor light sconces just turned off.  Nothing more is being used on circuit, actually less is on circuit since closing up back yard in October.  Please pardon my ignorance, I am not that electrically inclined.  Outside of changing an outlet and resetting my breaker, I am a novice.
Comment: The light switch for the lampost is outside, but covered .  The light switch for the two outdoor sconces is inside.  I guess I can attempt to isolate all outside power and reset the breaker and see if it holds.
Comment: I have isolated the outside power and reset my circuit breaker.  It's only been about 15 minutes, but my man cave still has power.
Comment: Lets hope it holds then in the nice weather you can dig it up.
Answer: If you're getting a plain breaker trip, the usual reason is overcurrent.  You have too much stuff on that circuit.
From your comments, a GFCI outlet tripping is not your problem.
You can get power monitor devices that will tell you what each device draws.  The simplest is the Kill-a-Watt, which for about $20 and measures a single load. They make more sophisticated monitors too.
The breaker that's tripping has a number - either 15 or 20.  That's the maximum amps. Multiply by 120 (i.e. 1800 or 2400), that's the maximum watts, and also the maximum VA (volt-amps).
By now you probably know which devices are on this circuit, so check every one with the tester, one by one.  Check it in the same conditions that make the breaker trip.  Tally up the amps, VA, and watts.
At this point, people often find a big surprise. I can't guess what your surprise is.  Now you work the list, same as you would if you were trying to be "green" or save on your energy bill.  Lots of people with those motives will help you with this problem.
FYI 1 watt of energy, run continuously, costs you $1/year or more.  Some upgrades will pay for themselves.
If stuff is running continuously, you want your breaker capacity to be 125% of the continuous loads.
Answer: You have an earth leakage problem. Due to the outdoors nature of that circuit its a bet that moisture has gotten into the circuit be it the fixtures or into the cabling. Fluorescent lights can also be a culprit of this if you have any fitted. Ultimately the correct way to locate it which also is the easiest is to do insulation resistance testing. Im going to assume you have no electronics connected to this circuit aswell as they tend to have a higher than nomral earth leakage that can cause nuisance tripping
Answer: It is not earth leakage as only rcd/rcbos monitor earth leakage. A breaker tripping would only suggest over current/overload. You probably have a short somewhere.
Comment: Hi, welcome to DIYSE. This question was asked and answered some time ago. Late answers are discouraged unless they contribute something new. It looks like your answer was really a comment on another answer. Stick around and contribute a few questions and answers and you will earn the reputation required to comment, upvote, and downvote.


What's the difference between a cyclic and periodic function?

Question: I've seen the words "cyclic" and "periodic" used to describe characteristics of a given function. What do they mean? I can't seem to find a difference. Wikipedia says a periodic function is one that repeats values in a periodic interval.
Maybe I was mistaking about the phrase "cyclic" being used to describe functions. One place I do see the word used in math is cyclic group.
Comment: Can you give an example of where you saw a function described as "cyclic"?
Comment: @Rahul I think I first came across the term when reading about integer factorization algorithms. I found a mention of it here http://www.merriam-webster.com/dictionary/cyclic%20function
Comment: Your link gives me "To view the definition of *cyclic function*, activate your Merriam-Webster Unabridged Dictionary FREE TRIAL now!" Can you just quote the example in your question? Although I'm guessing Greg's answer is probably what you need.
Comment: "a mathematical function that changes in value by an additive constant whenever its variable arguments pass continuously through a cycle of values"
Answer: A cyclic function might be referring to the iterates of a function (that is, when it's composed with itself multiple times). In particular, a function might be called cyclic if one of its iterates is the identity function. For example, every permutation of a finite set is a cyclic function according to this definition.
In particular, this is a completely different notion from a function being periodic, which discusses only the function itself (not its iterates) and how it behaves under translations of the domain.
Comment: Can you update the link? It doesn't work.
Answer: I would say that cyclic just means that it has certain range of independent values it can only use. For example, a Lagrangian becomes cyclic when you convert into polar coordinates. Essentially, the only values that are  going to happen/actually have an effect on the dependent variable are [O,2pi] Therefore it is cyclic. I guess functions in polar coordinates in general might be an easy example of cyclic functions?
[This info on Lagrangians being cyclic in polar came from Thornton's Classical Dynamics 5th]
Comment: Thanks for your answer, and welcome to math.SE! One small advice: the answer could be more close to the question: what is the difference between cyclic v.s. periodic. Thus better to compare the two, instead of just stating one.
Answer: The difference between a cyclic and periodic function is that one is the inverse of the other.
Take $f=\sin(x)$, which is periodic. An inverse $f^{-1}$ is normally done after restricting the domain of $f$ so that it's one-to-one and $f^{-1}$ isn't multi-valued. This does not interest us.
If you don't restrict the domain, $f^{-1}$ becomes multi-valued and we call it cyclic.
And if you invert a cyclic function you get a periodic function.