text:
Q: Google Sheets v4 API Ruby - Trying to update values in cells in a column but the updates are not happening Ruby: 2.3.1
Rails: 5.0.0
I have a sheet containing data like below: A, B , C, D represents the columns name in the sheet and 1, 2, 3 represents the row numbers.

I have written a script mentioned about here and from it I am trying to update the values in cells B2 and B3 and for updating I am using the following code:
spreadsheet_id = "<My Private Spreadsheet ID>"

range = 'Sheet1!B2:B3'

value_range_object = {
  "majorDimension"=>"COLUMNS",
  "values"=>[
     [9, 18] # B2 should be updated with value 9 and B3 should be updated with value 18
   ]
}

service = Google::Apis::SheetsV4::SheetsService.new
service.authorization = authorization
update_res = service.update_spreadsheet_value(spreadsheet_id, range, value_range_object, value_input_option: 'USER_ENTERED')

puts ">>>>>>>>>> update_res: #{update_res.inspect}"

But that puts is printing
>>>>>>>>>> update_res: #<Google::Apis::SheetsV4::UpdateValuesResponse:0x000000068acc70 @updated_range="Sheet1!B2", @spreadsheet_id="<My Private Spreadsheet ID>">

and there are no updates made to the sheet.
As per the documentation when an update is successful following kind of response should be received
{
  "spreadsheetId": spreadsheetId,
  "updatedRange": "Sheet1!B1:D5",
  "updatedRows": 3,
  "updatedColumns": 2,
  "updatedCells": 6,
}

Comparing that with the response I am getting there is definitely something which is missing or incorrect in my code and which is hampering the updates to be applied.
Can I please get some guidance to get past my problem and hence achieve my desired goal?
Update
I tried out this with a slightly different approach following the example given at https://developers.google.com/sheets/samples/writing#write_a_single_range
As part of this I created a fresh new blank sheet on Google Drive, shared it with my Service Account and tried to update it with the following code:
require 'google/apis/sheets_v4'

ENV["GOOGLE_ACCOUNT_TYPE"] = 'service_account'
ENV["GOOGLE_CLIENT_EMAIL"] = '<client_email_from_downloaded_json_here>'
ENV["GOOGLE_PRIVATE_KEY"] = "<private_key_from_downloaded_json_here>"

SCOPE = Google::Apis::SheetsV4::AUTH_SPREADSHEETS

authorization = Google::Auth.get_application_default(SCOPE)

# Initialize the API
service = Google::Apis::SheetsV4::SheetsService.new
service.authorization = authorization

spreadsheet_id = '<MY SPREADSHEET ID HERE>'

sheet_name = 'Sheet1'

range = "Sheet1!A1:D5"

value_range_object = {
  "majorDimension" => "ROWS",
  "values" => [
     ["Item", "Cost", "Stocked", "Ship Date"],
     ["Wheel", "$20.50", "4", "3/1/2016"],
     ["Door", "$15", "2", "3/15/2016"],
     ["Engine", "$100", "1", "30/20/2016"],
     ["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"]
   ]
}

update_res = service.update_spreadsheet_value(spreadsheet_id, range, value_range_object, value_input_option: 'USER_ENTERED')

puts ">>>>>>>>>> update_res: #{update_res.inspect}"

But strangely that is also not working. I am getting the following response
>>>>>>>>>> update_res: #<Google::Apis::SheetsV4::UpdateValuesResponse:0x00000006540348 @updated_range="Sheet1!A1", @spreadsheet_id="MY SPREADSHEET ID HERE">

and the sheet is also blank after executing the code.
Can anybody please take a look into this and comment on what is going on?

A: This is solved.
The solution is to use Symbol-keys, instead of String-keys in ValueRangeObject. That is I had to change my value_range_object from following
{
  "major_dimension" => "ROWS",
  "values" => [
     ["Item", "Cost", "Stocked", "Ship Date"],
     ["Wheel", "$20.50", "4", "3/1/2016"],
     ["Door", "$15", "2", "3/15/2016"],
     ["Engine", "$100", "1", "30/20/2016"],
     ["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"]
   ]
}

TO
value_range_object = {
  major_dimension: "ROWS",
  values: [
     ["Item", "Cost", "Stocked", "Ship Date"],
     ["Wheel", "$20.50", "4", "3/1/2016"],
     ["Door", "$15", "2", "3/15/2016"],
     ["Engine", "$100", "1", "30/20/2016"],
     ["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"]
   ]
}

Take a note that hash keys are Symbols and not Strings.
Looks like a simple thing but took me few hours to figure out this.
More details can be found at https://github.com/google/google-api-ruby-client/issues/462#issuecomment-243927914
Thanks.


text:
Q: For loop, remove only 1 value even if shown multiple times || Discord.js I'm using MYSQL as my database for a command. I used a for loop to find the value given by the user.
^pet add <rarity> <type> | ^pet add common Black
I spent 7 hours figuring out how to get the for loop to then rewrite it last night.
I want to loop through the table column "common" and search for the type the user enters.
Just like the example; if I wanted to add Black to my pet list, I only want to remove one from the table.
I got it to search through the table for the type the user wants, but every time I want to remove only one instance of "Black" It either removes it partially correct, removes all of them or removes a value of "White" instead.
I've done a lot of testing, I couldn't find good examples of each issue it gave me.

I've also caught this issue, but I believe I fixed it with
if (!rows[0].common.includes(bunPet)) return;

case "common":
let commonCheck = rows[0].common.split(", ");
if (commonCheck.length <= 1) return message.reply('Please get another bun for your Common hold before setting a pet.');

    for (i = 0; i < commonCheck.length; i++) {
        let commonMatch = commonCheck[i].match(bunPet);
        con.query(`SELECT * FROM holds WHERE id = '${message.author.id}'`, (err, rows) => {
            let alreadyRan = rows[0].pets;

            if (alreadyRan === bunPet) {
                return console.log('Already ran')
            } else {
                con.query(`SELECT * FROM bun WHERE id = '${message.author.id}'`, (err, rows) => {
                    if (err) throw err;

                    if (commonMatch) {
                        sql = `UPDATE bun SET common = '${commonCheck.join(", ")}' WHERE id = ${message.author.id}`;
                        con.query(sql);
                        con.query(`SELECT * FROM holds WHERE id = '${message.author.id}'`, (err, rows) => {
                            if (err) throw err;

                            sql = `UPDATE holds SET pets = '${bunPet}' WHERE id = '${message.author.id}'`;
                            con.query(sql);
                        });
                        message.reply(`**${bunPet}** is now your current pet!\n**Your last pet has been removed.**`)
                    }
                });
            }
        });
    }
break;

A: Did some more digging inside other SO posts and found a fix.
Instead of using a for loop and searching through the whole list and trying to stop it from running on each value; I can use a indexOf search in a splice function.
case "common":
    let commonCheck = rows[0].common.split(", ");
    if (commonCheck.length <= 1) return message.reply('Please get another bun for your Common hold before setting a pet.');

    commonCheck.splice(commonCheck.indexOf(bunPet), 1);

    sql = `UPDATE bun SET common = '${commonCheck.join(", ")}' WHERE id = '${message.author.id}'`;
    con.query(sql);

    con.query(`SELECT * FROM holds WHERE id = '${message.author.id}'`, (err, rows) => {
        if (err) throw err;

        sql = `UPDATE holds SET pets = '${bunPet}' WHERE id = '${message.author.id}'`;
        con.query(sql);
        message.reply(`**${bunPet}** is now your current pet!\n**Your last pet has been removed.**`);
    });
break;

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is a wrapper type in Graphql? I am learning the official GraphQl doc.
When I come to the chapter introspection link here
I have encounter something called wrapper type.
input:
{
  __type(name: "Droid") {
    name
    fields {
      name
      type {
        name
        kind
      }
    }
  }
}

Output:
{
  "data": {
    "__type": {
      "name": "Droid",
      "fields": [
        {
          "name": "id",
          "type": {
            "name": null,    # here
            "kind": "NON_NULL"
          }
        },
        {
          "name": "name",
          "type": {
            "name": null,    # here
            "kind": "NON_NULL"
          }
        },
        {
          "name": "friends",
          "type": {
            "name": null,    #  here
            "kind": "LIST"
          }
        },
        {
          "name": "friendsConnection",
          "type": {
            "name": null,       # here
            "kind": "NON_NULL"
          }
        },
        {
          "name": "appearsIn",
          "type": {
            "name": null,      # here
            "kind": "NON_NULL"
          }
        },
        {
          "name": "primaryFunction",
          "type": {
            "name": "String",     # normal here
            "kind": "SCALAR"
          }
        }
      ]
    }
  }
}

The article claims the name of those type of fields of type is NULL because  it's a " wrapper" type of kind NON_NULL
Could someone explain what is exactly a wrapper type? Better provide an example or code to explain why primaryFunction has a name but others do not.

A: From the spec:

All of the types so far are assumed to be both nullable and singular: e.g. a scalar string returns either null or a singular string.
A GraphQL schema may describe that a field represents list of another types; the List type is provided for this reason, and wraps another type.
Similarly, the Non-Null type wraps another type, and denotes that the resulting value will never be null (and that an error cannot result in a null value).
These two types are referred to as "wrapping types"; non‐wrapping types are referred to as "named types". A wrapping type has an underlying named type, found by continually unwrapping the type until a named type is found.

A wrapping type wraps another type, which itself may also be a wrapping type. However, as you "unwrap" each wrapping type, eventually you have to hit a named type that all those wrapping types are associated with. In other words, wrapping types can never be used by themselves. A wrapping type always has exactly one named type it's associated to.
In introspection, to determine what type the wrapping type is wrapping, use the ofType field:
{
  __schema {
    types {
      name
      ofType {
        name
      }
    }
  }
}

You can add additional levels to potentially "unwrap" types further:
{
  __schema {
    types {
      name
      ofType {
        name
        ofType {
          name
        }
      }
    }
  }
}

As to why introspection doesn't show a name for these types, it's because the spec specifically prohibits it. Take a look at the section for the List type:

Lists represent sequences of values in GraphQL. A List type is a type modifier: it wraps another type instance in the ofType field, which defines the type of each item in the list.
Fields

*

*kind must return __TypeKind.LIST.

*ofType: Any type.

*All other fields must return null.

A: Here is some snippet from a tutorial I have done the other day. It represents a type wrapped with GraphQLNonNull operator (it's for the server side):
const ContestStatusType = require('./contest-status')
const NameType = require('./name')

module.exports = new GraphQLObjectType({
  name: 'ContestType',
  fields: {
    id: { type: GraphQLID },
    description: { type: GraphQLString },
    status: { type: new GraphQLNonNull(ContestStatusType) },
    createdAt: { type: new GraphQLNonNull(GraphQLString) },
    createdBy: { type: new GraphQLNonNull(GraphQLString) },
    names: {
      type: new GraphQLList(NameType),
      resolve(obj, args, { loaders, pgPool }) {
        return loaders.namesForContestIds.load(obj.id);
        return pgdb(pgPool).getNames(obj)
      }
    }
  }
});


text:
Q: A polynomial inequality Given $x_1,x_2, \ldots, x_n \ge 0, \alpha \ge 1$, show that
$\sum_{i}\alpha x_i(\sum_{j \le i}{x_j})^{\alpha-1} \ge (\sum_{i}x_i)^\alpha$
We're pretty sure the inequality holds for the given precondition. It can be validated using a small piece of matlab code. Now we post it for rigorous proof. Its continuous version is easy:
$\int^{n}\alpha x(\tau)(\int^{\tau}{x(t)}dt)^{\alpha-1}d\tau= (\int^{n}x(t)dt)^\alpha$
When writing down the proof, there are more details to be finalized, so we're stuck for a rigorous proof. Hope there's anyone who can help or point us to some resource.

A: Setting $s_i = \sum_{j \leq i} x_j$, just write
$$ \sum_{i \leq n} \alpha x_i s_i^{\alpha-1} = \sum_{i \leq n} \int_{s_{i-1}}^{s_i} \alpha s_i^{\alpha-1} dt \geq \sum_{i \leq n} \int_{s_{i-1}}^{s_i} \alpha t^{\alpha-1} dt = \int_{0}^{s_n} \alpha t^{\alpha-1} dt = s_n^{\alpha}
$$


text:
Q: Is there any unique Id that ag-grid generates and attaches for every row in the grid I wanted to implement the validations of certain columns in the ag-grid table in angular. My approach towards it is,

*

*I will maintain a form group and the children's of form groups are form arrays. The controls in the form array are pushed from a directive that sits on top of ag-grid.

*I use a custom cell renderer to display a border around the cell to show case an error entry by the user.

*So to get the correct control from form array inside the cell renderer component, I need to map a unique Id of row with the form array index to get the correct control.

*I tried using RowNodeId but that Id currently is coming up from a backend system. When I copy a row, then that row doesn't have any Id, that creates a problem for me to fetch the correct control from form array.

*While debugging I have found RowNode has "_objectId" associated with it, which seems unique and this will be available for copied rows also and I see it doesnt change with grouping/sorting/filtering.

Could anyone suggest me how should I decide my Id for the above mentioned scenario. I really appreciate for your help in advance.
PS: I am using v22 of ag-grid for some reason.


text:
Q: Wt C++ error: 'panel' does not name a type while using auto I am trying to compile a standard example of Wt widget (C++ web toolkit) given here: https://webtoolkit.eu/widgets/layout/grouping-widgets (last example on the page).
Below is the code:
#include <Wt/WAnimation.h>
#include <Wt/WPanel.h>
#include <Wt/WText.h>

auto panel = Wt::cpp14::make_unique<Wt::WPanel>();
panel->setTitle("Collapsible panel");
panel->addStyleClass("centered-example");
panel->setCollapsible(true);

Wt::WAnimation animation(Wt::AnimationEffect::SlideInFromTop, Wt::TimingFunction::EaseOut, 100);

panel->setAnimation(animation);
panel->setCentralWidget(Wt::cpp14::make_unique<Wt::WText>("This panel can be collapsed."));

This is the error: 'panel' does not name a type
on compiling with both g++ -std=c++14 and g++ -std=c++11


text:
Q: How to ask for type of word I encountered a book explaining the meaning reify followed by examples but it did not mentioned its a verb. I had to lookup dictionary for that. My question is when this type of strange/new word pops out from someone in conversation what should I ask if I want to know what type of word is it as in parts of speech? Instead of asking like "Is reify a verb, adjective, noun?"

A: Although part of speech is the correct term (see Wikipedia), it might be too vague if you don't include some context.
More specific terms might be word class, lexical class, or lexical category (according to the same Wikipedia article).

A: Yes, you could ask someone "what part of speech" is some word, although it would be best to ask of an English teacher because otherwise they might not know what you mean. If they look puzzled, then you can clarify by asking, "It it a noun, a verb, an adjective ..?"
However on a related note, it's not a bad idea to get familiar with common suffixes for different parts of speech.  The -fy (or -ify) suffix is generally associated with verbs:  clarify, edify, deify, magnify, etc.  You can turn some of these into nouns by removing the y and adding ication:  clarification, edification, deification, magnification, etc.  You can also turn some into adjectives by adding ied after the f: clarified, edified, deified, magnified.
Unfortunately there are exceptions like the adjectives "stuffy" and "leafy" which follow a similar-looking (but completely different) pattern.  And there are some -fy verbs that are turned into nouns in a different way, like "testify" -> "testifier" (someone who testifies), "testimony" (what is said while testifying) or "testimonial" (a written declaration of trust or admiration)
But for the most part it can be helpful to recognize these patterns.  See this list of words that end in -fy and note most are verbs.


text:
Q: Does $\delta W=pdV$ hold for non-ideal gases I have that for quasistatic processes,
$$ \delta W= \textbf{f}\cdot d\textbf{x}  $$
so for a gas $\delta W=pdV$.
Does this only hold ideal gases or will it hold for van der waal's gas?

A: That is nothing but a mechanical relation valid for every type of isotropic fluid (even viscous, in the quasi-static regime), so gases in particular, no matter any further state equation.


text:
Q: What's the opposite of the phrase "pay under the table"? Could you tell me what is the opposite of the phrase pay under the table? For example:

The company pays their employees under the table.

Would it be natural to say pay over the table?

A: There isn't a standard way of describing the method of payment, though I have seen "over the table" used occasionally. The best way of describing this situation is to say that the employees are on the books. According the the Cambridge Dictionary, this means that the employees are

officially employed by a company, or an official member of an organization, society, sports team, etc.:

The implication is that all payments to the employees are recorded in the correct manner.

A: I would know what you meant if you said "pay over the table", but I've never heard it said before. I would say that someone was "paid legally" or "paid legitimately" if I needed to express this.

A: Simply saying "taxed" might be useful in some cases.
For example, "Is this under the table?" "No, its taxed."

A: It might be understood especially if contrasted with pay under the table informally, but there is no need for that because, in most contexts, the verb pay independently implies an honest and legal exchange.
I don't think it's common. You can use publicly, officially, law-abidingly instead to stress the legitimate nature of the payment.

A: A word that means the opposite of under the table and uses the same metaphor is aboveboard:
American Heritage Dictionary

adv. & adj.
Without deceit or trickery; straightforward.
[Originally a gambling term referring to the fact that a gambler whose hands were above the board or gaming table could not engage in trickery, such as changing cards, below the table.]

A: If we can understand the context as being in the United States, I would say:

The company pays their employees through W-2.

or

The company has W-2 employees.

Grammatically, this is wrong. But this is how people say it orally.
A more boring wording that is reserved for policies and compliance documents could be:

The company reports employee earnings using IRS Form W-2.


text:
Q: Changing tip labels for a multiphylo object The answer and question is related to this post: Change tip labels in phylogeny in R. I have old tip labels I want to replace with new tip labels because of taxonomic changes. How would I do this with a multiPhylo object in R? I have a random distribution of trees from the posterior I would like to update with new taxonomic names.

A: multiPhylo objects are simply lists of phylo objects so the best way to modify them is to use lapply.
First you should define the function allowing to rename tips
## Function for renaming tips
rename.tips.phylo <- function(tree, names) {
    tree$tip.label <- names
    return(tree)
}

You can then apply it to as many trees as you'd like:
## Generating 50 random 5 tips trees
random_trees <- rmtree(50, 5)

## Renaming all the tips
random_trees_renamed <- lapply(random_trees, rename.tips.phylo,
                               names = c("A", "B", "C", "D", "E"))

However, the output will be a list so you'll have to manually switch the class back to multiPhylo:
## Class of the original object
class(random_trees)
#[1] "multiPhylo"

## Class of the renamed trees
class(random_trees_renamed)
#[1] "list"

## Changing the class
class(random_trees_renamed) <- "multiPhylo"
class(random_trees_renamed)
#[1] "multiPhylo"

And now all your tip labels have been renamed:
## First tree
random_trees_renamed[[1]]$tip.label
#[1] "A" "B" "C" "D" "E"
## 42nd tree
random_trees_renamed[[42]]$tip.label
#[1] "A" "B" "C" "D" "E"


text:
Q: Load file in new window with event listener on form submission while keeping other form validations valid I have a web form that has a sales force "Web-To-Lead" form action. The end goal is to have the form submit like normal while also loading pdf into a new page.
I have two validations set up for certain form items.
The first one is a captcha validation which looks like so:
var allow_submit = false

function captcha_filled () {
    allow_submit = true;
}
function captcha_expired () {
    allow_submit = false
}
function check_captcha_filled (e) {
    console.log('verify captcha')
    if (!allow_submit) {
        alert('ERROR: Please verify you are human by filling out the captcha')
        return false
    }
    captcha_expired()
    return true
}

(This works as expected.)
The second validation I have is for an input to be :checked in order for the form to submit. That code is as follows:
function fnSubmit() {
    if($("input:checkbox[id='chk']").is(":checked") == false){
        alert("You must agree to collect and use your personal information.");
        return false;
    }
}

(This also works as expected.)
The problem comes with trying to integrate my pdf_Download() function while maintaining those validations. Because the form action is already reserved for the web-to-lead, I decided to use an onclick EventListener that generates a new window to open with the desired location. The location uses a <?=$_REQUEST in PHP.
Below is a minimal example of the form and the js I have attempted so far to make this work.
<form action="web-to-lead" method="POST" onSubmit="return fnSubmit() & check_captcha_filled() & pdf_Download()">
<button class="def_btn bluest" name="submit">Contact</button>

<script>
function pdf_Download(e) {

    if($("input:checkbox[id='chk']").is(":checked") == false || !allow_submit == false) {
        e.preventDefault()
        return false
    } else {
        document.querySelectorAll('button.bluest').addEventListener("click").window.open('<?=$_REQUEST['bf_file']?>');
        return true
    }
}
</script>

If something is unclear please let me know.

A: I believe it will work with this

If it doesn't work please add screenshot devtools I will correct the answer

<form action="web-to-lead" method="POST" onSubmit="fnSubmit() && check_captcha_filled() && pdf_Download()">
<button class="def_btn bluest" name="submit">Contact</button>

<script>
function pdf_Download(e) {

    if($("input:checkbox[id='chk']").is(":checked") == false || !allow_submit == false) {
        e.preventDefault()
        return false
    } else {
      window.open("<?=$_REQUEST['bf_file']?>");
      return true
    }
}
</script>


text:
Q: iphone and Gmail When sending an Gmail email from my iPhone with Gmail as the default account those who receive my email have it show up in their in-box identified as "GMAIL", not from my email address or identifying me.   What do i need to change for email recipients to see the email is from me?

A: I found some key videos that show how your setup should look like:
If all else fails, delete the setup and re-add it following the instructions here on Google.
Good Luck!


text:
Q: Animation in react-native I was looking for the logo to reduce to some default size from the actual size and after completion of that some text data should be shown....
but when i saw the facebook website there was no where i found reducing the size of the logo from default.
How should i achieve this
 Animated.timing(
this.spinValue,
{
  toValue: 1,
  duration: 4000,
  easing: Easing.linear
}

i didn't get how to change the size of the image in this...
Along with decreasing the size of the image i want the image to move top so some space left at the bottom there i would like to show other text on completion of the animation...
Sorry if i'm wrong..help me out with some docs or references
I have tried:
const imagePos = this.state.scaleValue.interpolate({
      inputRange: [0, 1],
      outputRange: [500, 200]
    })
    const imageTop = this.state.scaleValue.interpolate({
        inputRange: [0, 1],
        outputRange: [400, 100]
      })

  return <View>
  <Animated.Image style={{ height:imagePos ,width:imagePos ,top : imageTop }} resizeMode={'contain'} source={require('../assets/new_images/logo1.png')} />

  </View>

A: You can for example use "scale" to scale down image size on componentDidMount. If I understood you correctly this is what you want
class Playground extends React.Component {
  state = {
    scaleValue: new Animated.Value(1),
  }

  componentDidMount() {
    Animated.spring(
      this.state.scaleValue,
      {toValue: 0.5}
    ).start();
  }

  render() {
    return (
      <Animated.Image
        source={{uri: 'http://i.imgur.com/XMKOH81.jpg'}}
        style={{
          flex: 1,
          transform: [
            {scale: this.state.scaleValue},
          ]
        }}
      />
    );
  }
}

A: I achieved this by using multiple animations
this is my componentdidmount
Animated.timing(
        this.state.scaleValue,
        {toValue: 1 ,duration : 1000 ,easing : Easing.ease ,delay:0}
      ).start();

this is my rendet
   const imagePos = this.state.scaleValue.interpolate({
      inputRange: [0, 1],
      outputRange: [200, 150]
    })
    const imageTop = this.state.scaleValue.interpolate({
        inputRange: [0, 1],
        outputRange: [0.35*windowHeight, 0.1*windowHeight]
      })
      const content = this.state.scaleValue.interpolate({
          inputRange: [0, 1],
          outputRange: [0.6*windowHeight, 0]
        })

  return <View style={{flex:1,alignItems:'center'}}>
  <Animated.Image style={{ height:imagePos ,width:imagePos ,top :imageTop}} resizeMode={'contain'} source={require('../assets/new_images/main_screen.png')} />
  <Animated.View style={{flex:1,alignItems:'center',top : content}}>

    <View><Text>Hi this is bottom content</Text></View>
    </Animated.View>
  </View>


text:
Q: What does "tags whose commits are reachable from the specified commit" mean? In one of my projects, I am trying to get the most recent tag after checking out a branch, or from origin/master. If I run git tag -l --sort=-creatordate --merged | head -n1 or a git describe, I get the same result, but its from a tag from far in the past. If i get rid of the --merged, it shows the correct, most recent tag in the project.
Checking out a specific branch gives me back the correct, last known tag in the repo, but if its from origin/master or FETCH_HEAD, it gives me one in the past.
I'm mainly wondering how the --merged flag works, because the manual pages just says it Only list tags whose commits are reachable from the specified commit.

A: There are two parts to this:

*

*the general concept of reachability, and

*how git tag -l --merged works, which uses the concept itself.

Reachability is a property of a graph, or in Git's case, a directed graph.  Consult either the Wikipedia article, or Think Like (a) Git, for a proper explanation.  (Or see one of my many StackOverflow answers showing how to determine which branches contain various commits.)  The rest of this assumes you already understand reachability.
A tag, in Git, is just a fancy pointer: in effect, an arrow pointing to one particular commit.  But there's one other special thing about tags in Git:  They can point to a tag object, rather than directly to a commit.1  The tag object has the annotations for git tag -a or message for git tag -m.  The tag object then holds the raw hash ID of the underlying commit.
This brings us to the wording in the documentation:

the manual pages just says [--merged]

Only list tags whose commits are reachable from the specified commit.

We run:
git tag -l --merged <commit-specifier>

so we pick one commit.  That's the "specified commit".
The git tag -l operation will now iterate through every tag.  The tag either points directly to a commit, or to an annotated tag object that points to a commit.  That commit exists somewhere in the overall Git commit graph.  The question that --merged applies is: can we reach the tagged commit from the specified commit?
If we can reach the tagged commit, git tag -l lists the tag.  If not (or if we must skip the tag because it does not tag a commit after all), git tag -l omits the tag.

1A tag name is actually allowed to point to a tree or blob object, as well as to a commit or annotated tag object.  In this case there is no commit at all, and git tag -l --merged will just ignore that tag.  Also, an annotated tag object can actually refer to any other kind of object, not just a commit object.  So the true rule for resolving a tag name is:

*

*If tag name refers to an annotated tag object, switch to that annotated tag object.

*While we have an annotated tag object, switch to the object that is the target of this annotated tag.  (Git refers to this internally as peeling tags, analogous to peeling an onion, layer by layer.)

*Stop: we have an object.

We now know the object to which the tag refers.  If it's a commit, it's a candidate for this --merged listing.  If not, it's not.


text:
Q: Using history command in Bash alias So I'm quite unfamiliar with Bash and am learning as I go along through trial and error. I'm wondering why the following doesn't work:
I define the function repeat in my bashrc file.
repeat () {
         history > /dev/null
         !-2
}

And then call it in the same file as follows:
alias .="repeat"

Yes, I know I'm hijacking the dot operator but I have my own alias for it (specifically for sourcing ~/.bashrc). The idea is to be able to write . and have it repeat the last command. This works if I type the commands manually in an interactive shell but doesn't work like this inside of an alias. Never mind that it's not repeatable more than once, I just want to get it working before I address that issue. When I type . I get the following output:
bash: !-2: command not found
I considered that history is not reading from my history file when called non-interactively and contains no commands in its history, but no, this outputs my history:
repeat () {
        history
        !-2
}

However, I get the same result. The ! command doesn't seem to work.
Any idea what I'm doing wrong?
EDIT: I have it working the way I want it now (please tell me if there is a more elegant solution) but I want to get rid of the command to be executed, i.e. I just want the output from the command itself. I thought I would try something like this:
 19 repeat () {
 20         for ((i = 0; i<${1}; i++ ))
 21         do
 22                 $(fc -s) | tail -n +2
 23         done
 24 }
 25
 26 alias .="repeat 1"
 27 alias 1.="repeat 1"
 28 alias 2.="repeat 2"
 29 alias 3.="repeat 3"
 30 alias 4.="repeat 4"
 31 alias 5.="repeat 5"
 32 alias 6.="repeat 6"
 33 alias 7.="repeat 7"
 34 alias 8.="repeat 8"
 35 alias 9.="repeat 9"
 36 alias 10.="repeat 10"

But it unfortunately doesn't work, it gives me the wrong output and then when I try again it enters an infinite loop. How do I achieve this?

A: You can use the fc command which "is used to list or edit and re-execute commands from the history list ". Bash manual gives an example for this.

A useful alias to use with this is r="fc -s", so that typing r cc runs the last command beginning with cc and typing r re-executes the last command.


text:
Q: Playwright: do not reuse existing web server in container environment I am using playwright for e2e testing of my (angular) web application and loving it so far. I would like to configure playwright test to reuse an existing web server when not in CI environment nor when running from a Docker container.
The playwright docs provide the following example, which was helpful to start the server in CI environment only:
  webServer: {
    command: 'npm run start',
    port: 3000,
    timeout: 120 * 1000,
    reuseExistingServer: !process.env.CI,
  },

I was wondering if it would be equally simple to achieve the same behavior when running from a Docker container? Or if instead I should think of another way of doing so (e.g. setting environment variables)?


text:
Q: "Accustom someone to sth" Vs "make someone get used to sth" In order to discover the semantic difference between these two words, I need to figure out how the following sentences differ in meaning:

*

*Try to make your child get used to healthy foods.

*Try to accustom your child to healthy foods.

A: "make" somebody do something implies "forcing" somebody to do something.
The two sentences would have the same meaning if you would change "make" with "help":

Try to help your child get used to healthy foods.


text:
Q: Why did they have to attack the Capitol? All the districts have formed a coalition and they have cut off power supply and food supply to the Capitol. That mountain hangar in district 2 has been disabled as well, so the Capitol cannot mount an effective attack. So why do they need to attack the Capitol? They can just camp outside and let the Capitol starve. They can shoot down any aircraft that leaves. It's an easy victory without unnecessary bloodshed. Sure, Snow might escape but is his life really worth so much trouble? Even if he does escape, he has no power to do anything.

A: Because they want a glorious victory.

*

*Sitting outside quietly and letting the Capitol starve might win them the war in the end, but it wouldn't be a very spectacular way to end it all. Remember that one of the chief advisors to Coin is a master of public relations and used to be a Head Gamemaker. From a PR point of view, an active and highly visible victory in the heart of the Capitol itself would be a much more fitting end to the war than a passive victory and Snow's surrender due to lack of supplies. It showcases the military might of the rebellion, and ensures that nobody else will be likely to rebel against the new establishment in the near future.

*This argument works from a practical as well as a PR point of view. Revolutions are based on fire and impulse. Sure, District 13 has a well-planned strategy, a huge military arsenal, and a rigorously organised force. But the other Districts have risen up more or less impulsively in their hatred against Snow, the Capitol, and the Games. If the war turned into an extended siege, it wouldn't take long for their fire to die down and many of them to get bored and go back home. The rebel forces will grow weaker, if anything, as time goes on.
Because they don't know what resources the Capitol might have.

*

*The Capitol's ability to set up the minefield of traps and pods shows that they still have a good deal of military resources at their disposal. If the rebels simply sit and wait, the Capitol might be able to roll out some new weapon or strategy and inflict larger losses on the rebels than they would sustain by simply marching into the city. It's safer to hit them while they're weak and disoriented than to wait, possibly allowing them to gather their wits and have a better chance in the final battle.

*And as well as military resources, there's also supplies to be considered. The Capitol might have a massive storage bunker somewhere in the city with enough food for years. Who knows, with all their technology they might even have a way of creating food. There's no guarantee that starving them out would even work, when they don't know how much food the Capitol might have.
Because their real target is the Capitol leaders, not the populace.

*

*A siege would harm the poorest citizens of the Capitol more than anyone else. The slaves and Avoxes would be the first to die, and you can bet your life that President Snow would have the last morsel of food for himself. Now President Coin personally probably doesn't give much more of a damn about the common people than Snow does, but when you're the leader of a popular rebellion, you have to at least give the appearance of caring about the lower orders.

*Conversely, all-out attack is a strategy which promotes speed. A swift rebel victory, ending the war in a matter of days, ensured that they had the Capitol leaders captured and incarcerated (or more likely executed) before they had a chance to create much of a 'human shield'. Note that this was exactly Snow's final tactic: using Capitol children as a shield for himself. Given more time, he would have been able to do this more effectively. Striking quickly to the heart of the Capitol, while it did mean a lot of collateral damage to buildings and property, probably saved the lives of a lot of the less privileged Capitol citizens whose starved bodies might otherwise have been used to protect Snow and the other top dogs.

A: This is just speculation, but maybe they need to take the Capitol by force.  They are trying to prove that they are a threat, and what better way to do that than to strike quickly and powerfully at the center of the enemies.  If they hope to have the people accept them as a serious government, they might think that laying siege would look like a coward's game, that the people will accept them more than if they just strike.


text:
Q: Excel not opening .xls made from C# StringBuilder The following code was written several months ago and tested perfectly, with that funny little warning message in Excel.  Now, though, after the C# code runs without errors and the browser downloads the exported .xls file, the Excel application opens but displays nothing, as if it didn't open the exported file.  Can anyone see problems with this code or know why Excel suddenly wouldn't open this document?  Many thanks in advance!
The C# Code:
[HttpGet]
public void DownloadReport()
{
    string filename = "ReportExport";

    //Report source data organized here

    StringBuilder sb = new StringBuilder();
    sb.Append("
");
    sb.Append("
");
    foreach (DataColumn column in reportData.Columns)
    {
        sb.Append("");
        sb.Append(column.ColumnName);
        sb.Append("	");
    }
    sb.Append("
");
    foreach (DataRow row in reportData.Rows)
    {
        sb.Append("
");
        foreach (DataColumn column in reportData.Columns)
        {
            sb.Append("");
            if (row[column] == null)
            {
                sb.Append("");
            }
            else
            {
                sb.Append(row[column]);
            }
            sb.Append("	");
        }
        sb.Append("
");
    }
    sb.Append("
");
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    string style = @"";
    Response.Write(style);
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}

A: You are not generating a XLS file. The stated code generates a HTML fragment and tells the browser that this is a Excel file. Excel itself checks the data and cannot parse it (it is expecting binary data). Better use a Excel generator library.
Have a look at Create Excel (.XLS and .XLSX) file from C#
Personally I have made good experiences with NPOI and the Open XML SDK.

A: Adding Response.ClearHeaders() before setting the header seems to have done the trick.  Perhaps the content type had been previously specified and needed to be reset.


text:
Q: Use an if with a python str.find() I am trying to parse the following string with Python : At 11:00 am EST, no delay, 7 lane(s) open. I need to read it to see if it contains the string no delay. I have used the following to parse it: contents_of_tunnel.find("no delay").
This runs fine. But when I use it in an if/else, such as below:
>>> if contents_of_tunnel.find("no delay") == True:
...   print 1
... else:
...   print 0
...
0

It comes out to zero. Why is this? I believe that the issue is with the first line, the one that goes like so: >>> if contents_of_tunnel...
Thanks for the help.

A: Maybe you want something like this:
if 'no delay' in contents_of_tunnel: print 1
else: print 0

or just
print 1 if 'no delay' in contents_of_tunnel else 0

A: find(...)
  S.find(sub [,start [,end]]) -> int

  Return the lowest index in S where substring sub is found,
  such that sub is contained within S[start:end].  Optional
  arguments start and end are interpreted as in slice notation.

  Return -1 on failure.

The only way this will print 1 is if contents_of_tunnel starts with "no delay" because the index returned will be 0. -1 evaluates to True.
You should use:
if contents_of_tunnel.find("no delay") != -1:

or
if "no delay" in contents_of_tunnel:

or
try:
    index = contents_of_tunnel.index("no delay")
    # substring found
except ValueError:
    # substring not found

A: The reason is that contents_of_tunnel.find("no delay") returns a number. Therefore, instead of using  a == True, use an != -1. That way it will do what you had expected.


text:
Q: Don't show picture miniature if i click like button and picture share miniature in my fan page, private profil etc Hi I have problem with view share and like button in my page. If i click like button on my page for example this picture http://www.debuton.com/obrazek.php?206 i have this window http://scr.hu/8qi/a8n7g and I doens't have picture miniature and this is view with my profile when i click the like button. Same here with share button they doesn't view picture miniature only link :/ please help me
I will be grateful

A: What is the code you are using? Make sure you have data-show-faces="true" so you can see the faces of users who have liked the page. If the user's privacy settings are strong, you won't seen an image no matter what settings you change.


text:
Q: Rails 4 with cofffeescript, unwanted jquery sortable detatch I use ruby on rails 4 with jquery-ui-rails gem. And some list have sortable jquery function.
$ ->
  $('#projects').sortable
        handle: '.handle'
        opacity: 0.4
        update: ->
            $.post($(this).data('update-url'), $(this).sortable('serialize'))

This is my code, not apply tab indent.
Problem:
List actually working on first connect project page, and I connect a list into show page,
then I click Back links. Not working sortable
What happen?

A: Seems you have turbolinks enabled. Read about them here: github/rails/turbolinks.
Problem is that when you change page with clicking, turbolinks only loads new page by ajax and updates current page. Without reloading any css and js. So $ -> will not work after first load.
There are two solutions to this problem:
First, use document.addEventListener "page:load", -> instead of $ ->.
Or second, remove turbolinks gem from Gemfile and remove its require from application.js.


text:
Q: Remove multiple whitespace element in an array php I have an array which contains multiple white space element. Below is an array :
Array ( [0] => Intermarché [1] => catalogue Intermarché [2] => promotion [3] => Intermarche [4] => produit en réduction [5] => )

5th indexed element in an array has double white space.
I tried array_filter($array) php function but it removes only one white space element. Is there any array function in php to remove elements which has n number of white spaces ?
Input :
$array = [
    "Intermarché",
    " ",
    "promotion",
    "  ",
    "        "
];

Expected Output :
$array = [
    "Intermarché",
    "promotion"
];

A: You can use array_filter() by providing trim() as a callback.
Which trims the value and then checks if it would be empty. It does not change actually the values.
$myArray = array(
    0 => "Intermarché ",
    1 => "catalogue Intermarché             ",
    2 => "promotion ",
    3 => "Intermarche",
    4 => "produit en réduction" ,
    5 => "  ",
    6 => ""
);

$myArray = array_filter($myArray,  'trim');
var_dump($myArray);

which gives you
array(5) {
  [0]=>
  string(13) "Intermarché "
  [1]=>
  string(35) "catalogue Intermarché             "
  [2]=>
  string(10) "promotion "
  [3]=>
  string(11) "Intermarche"
  [4]=>
  string(21) "produit en réduction"
}

Link to code Sandbox

A: You have an array like:
$array = [
" test",
"test foo ",
"test bar",
"test foo bar"
];

loop over it like this:
foreach($array as &$arr) {
    $arr = str_replace(" ", "", $arr);
}

print_r($array);

result:
Array
(
    [0] => test
    [1] => testfoo
    [2] => testbar
    [3] => testfoobar
)

BR

A: You can use array_map() to clean them and array_filter() to remove empty ones afterwards.
Demo: https://3v4l.org/LenLJ
$myArray = [
    "Intermarché ",
    "catalogue Intermarché             ",
    "promotion ",
    "Intermarche",
    "produit en réduction" ,
    "  ",
    ""
];

$noDoubleWhitespace = array_filter(
    array_map(
        fn($string) => trim(preg_replace('/\s{2,}/u','', $string)),
        $myArray
    )
);

var_dump($noDoubleWhitespace);

gives
array(5) {
  [0] =>
  string(12) "Intermarché"
  [1] =>
  string(22) "catalogue Intermarché"
  [2] =>
  string(9) "promotion"
  [3] =>
  string(11) "Intermarche"
  [4] =>
  string(21) "produit en réduction"
}

Below PHP 7.4 use
$noDoubleWhitespace = array_filter(
    array_map(
        function ($string) {
            return trim(preg_replace('/\s{2,}/u', '', $string));
        },
        $myArray
    )
);


text:
Q: Bing Map Route API : Route point showing lat, long not address When click on grid item, I pass lat and long for source and destination and route display on the map.
But everytime I see latitude and longitude on [A] and [B] route point instead of address.
So how to display address on [A] and [B] point instead of lat, long ?

Following is my code.
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', () => {

      that.directionsManager = new Microsoft.Maps.Directions.DirectionsManager(that.map);
      that.directionsManager.clearAll();
      // Set Route Mode to driving
      that.directionsManager.setRequestOptions({
        routeMode: Microsoft.Maps.Directions.RouteMode.driving
      });

      that.directionsManager.setRenderOptions({
        drivingPolylineOptions: {
          strokeThickness: 3
        }
      });

      const waypoint1 = new Microsoft.Maps.Directions.Waypoint({
        location: new Microsoft.Maps.Location(that.truckData.currentLat, that.truckData.currentLong)
      });

      const waypoint2 = new Microsoft.Maps.Directions.Waypoint({
        location: new Microsoft.Maps.Location(that.truckData.workLat, that.truckData.workLong)
      });

      that.directionsManager.addWaypoint(waypoint1);
      that.directionsManager.addWaypoint(waypoint2);

that.directionsManager.calculateDirections();

A: If you want something else to display instead of the coordinates, pass it into the address property of the waypoints as shown in this code sample: https://www.bing.com/api/maps/sdkrelease/mapcontrol/isdk/directionscreatedrivingroute


text:
Q: Plotting temporal data day and hour together I have a frame with temperature data and the time. It looks like this:

area day hour temperature
d1 09_11_2013 01H0min0s 18,723
d1 09_11_2013 04H0min0s 17,558
d1 09_11_2013 07H0min0s 16,963
d1 09_11_2013 10H0min0s 22,753
d1 09_11_2013 13H0min0s 28,468
d1 10_11_2013 01H0min0s 21,318
d1 10_11_2013 04H0min0s 20,126
d1 10_11_2013 07H0min0s 19,151
d1 10_11_2013 10H0min0s 25,404
d1 10_11_2013 13H0min0s 29,890
i1 09_11_2013 01H0min0s 18,485
i1 09_11_2013 04H0min0s 17,368
i1 09_11_2013 07H0min0s 16,844
i1 09_11_2013 10H0min0s 24,171
i1 09_11_2013 13H0min0s 28,072
i1 10_11_2013 01H0min0s 21,246
i1 10_11_2013 04H0min0s 20,103
i1 10_11_2013 07H0min0s 19,151
i1 10_11_2013 10H0min0s 27,087
i1 10_11_2013 13H0min0s 28,518

In my example I have two areas and five temperatures per hour per day.
I use this function (package ggplot2) but I would like to plot the column hour as well.
ggplot(data, aes(x=day, y=temperature, colour=area, group=area)) + geom_point()

A: I would create a time element that combines the date and hour. You can then use this as the x-axis, and use scale_x_datetime for more control over the breals and labels.
# Your data
dat <- read.table(header=T, text=
"area  day  hour    temperature
d1  09_11_2013  01H0min0s   18,723
d1  09_11_2013  04H0min0s   17,558
d1  09_11_2013  07H0min0s   16,963
d1  09_11_2013  10H0min0s   22,753
d1  09_11_2013  13H0min0s   28,468
d1  10_11_2013  01H0min0s   21,318
d1  10_11_2013  04H0min0s   20,126
d1  10_11_2013  07H0min0s   19,151
d1  10_11_2013  10H0min0s   25,404
d1  10_11_2013  13H0min0s   29,890
i1  09_11_2013  01H0min0s   18,485
i1  09_11_2013  04H0min0s   17,368
i1  09_11_2013  07H0min0s   16,844
i1  09_11_2013  10H0min0s   24,171
i1  09_11_2013  13H0min0s   28,072
i1  10_11_2013  01H0min0s   21,246
i1  10_11_2013  04H0min0s   20,103
i1  10_11_2013  07H0min0s   19,151
i1  10_11_2013  10H0min0s   27,087
i1  10_11_2013  13H0min0s   28,518", stringsAsFactors=F, dec=",")

# Create a data-time vector
dat$time <- as.POSIXct(
              paste(dat$day, gsub("[^0-9]+", ":", dat$hour)),
              format="%d_%m_%Y %H:%M:%S")

# Plot
library(ggplot2)

ggplot(dat, aes(x=time, y=temperature, colour=area)) +
           geom_point() +
           theme(axis.text.x=element_text(size=10))


text:
Q: Storing date in two bytes I am reading a Let us C book, in that to store date in two bytes formula is there
int year = 1990, month = 03, day=22

date = 512*(year-1980)+32*month+day

I do not understand the above formula, like why 1980 is being subtracted from given year and multiplying with 512 then multiplying 32 with month and adding day.
Could someone please explain me above formula.
Thanks in advance.

A: The above formule just store the day (1-31 or 0-30) on 5 digits, the month (0-11 or 1-12) on 4 digits  and the year on 7 digits to put it in only 2 bytes.
The epoch here is year 1980, that means that all will be fine for years between 1980 and 2127. My advice would be to avoid negative values and choose an appropriate start year. For example date = 512*(year-1950)+32*month+day would be fine for years between 1950 and 2077.
I advise you to avoid negative values because right shift of signed value is defined by standard as implementation dependant so you cannot know if the new bits will be filled with 1 or with 0. So even if you want to process negative values, always use unsigned short for you 2 byte values or uint16_t to have deterministic shifts.


text:
Q: How to start with phonegap - installation I have some simple question becuse phonegap docs is so hard to understand, also some tutorial for first basic steps are welcome.

*

*Everything what I need to install to use phonegap?

*Where is the folder of instaled phonegap?

*How to start instalation (CMD, node.js) ?

I type in CMD:
C:\> npm install -g phonegap

and I get:

What is the next step? Please help?

A: Its not an error its just a warning.
It means its working, next type in the following in your command prompt
phonegap create myapp com.cordovaprogramming.hello Hello
This will create a myapp folder writes the application ID as com.cordovaprogramming.hello to the application's configuration file and allows you to have an Hello as an application name.
For more information check http://www.kodkillerz.com/using-cordova-command-line-interface/
That is for cordova, just replace cordova with phonegap and all will work fine.
Thanks

A: you can refer the below article for installing Phonegap/Cordova.
http://thejackalofjavascript.com/phonegap-3-cli-setup-mac-windows/
http://coenraets.org/blog/cordova-phonegap-3-tutorial/
http://teusink.blogspot.in/2013/07/guide-phonegap-3-android-windows.html
http://sdk.revmobmobileadnetwork.com/phonegap_cordova.html
http://docs.phonegap.com/en/3.5.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide
Phonegap Cordova installation Windows


text:
Q: Excel 2016 Conditonal formatting and color scales I want to compare A10 with B10. If B10 is greater than A10 then I want both columns to be in red. I have looked at YT for solutions but there are only one dimension. I have also checked most common references w/o any luck. Do you have any good advice?

A: Color scales will take into account all values in the range that the conditional format applies to and will then distribute the colors based on the value of each cell in relation to all other cells.
What you describe cannot be done with color scales but with a conditional formatting rule that uses a formula. Select both cells A10 and B10, create a new rule with this formula:
=$B10>$A10
Set the color to red. Note the $ sign in front of the column letter, but not the row number. When you copy the format to other rows, this relative row reference will then apply to the current row.


text:
Q: Sample size for best forecasting ARIMA model How can we decide the size or portion of the data given to get the ARIMA that has the best forecasting properties?
I mean, for example, we have a hourly series with over 28.000 elements.
Which is the criteria that tells us: do ARIMA over last 100 elements, or 250 last elements, so the ARIMA we get is better for forecasting?
I am interested in short time prediction, like for 24 hours.
I read everywhere but found no criterion yet.

A: A good rule of thumb is: more is usually better.
Then again, more may not always be better. For instance, your data-generating process may have changed strongly over time, so that the data from before the change may not reflect current and future dynamics of your series any more. In such a case, it may indeed be better not to use your full dataset. (You may want to look at our questions tagged change-point if you suspect something like this to be going on.)
Overall, the best way to assess almost anything about a forecast is to use a holdout sample. Hold out the last part of your data, say the last week (168 hours). Fit a model to the $n$ historical periods before that. Forecast out 24 hours. Note the error. Move the entire setup forward one hour (fit with $n$ historical periods, forecast 24 hours ahead, note the error). Do this until you have gone through your holdout sample. You should now have 168-24+1=145 errors. Do this for various "reasonable" values of $n$. Pick the one that yields the lowest error.
You will need to specify "reasonable" values of $n$, best based on your prior knowledge. Alternatively, just pick some numbers than make sense. You will also need to specify the forecast accuracy measure you want to use. I'd recommend the Mean Squared Error (MSE) if you are looking for unbiased point forecasts.
This section in a free online forecasting textbook is very helpful.

That said, 28000 hourly data points correspond to over three years of data. Without knowing anything else about your data, I suspect that there may be multiple sources of seasonality involved, like intra-daily, intra-weekly (e.g, for retail, call center or electricity demands, which show strong weekly patterns), or intra-yearly (like temperatures or weather information more generally). (S)ARIMA is not really made for handling multiple seasonalities. If you suspect that your data exhibits complex seasonalities, it will probably be more useful if you use a dedicated model to model these than if you optimize the history used by an inappropriate model like ARIMA. This earlier question may be helpful, as may other questions in the time-series tag on "complex seasonalities".


text:
Q: Using ML to assist human labelling in dataset with highly unbalanced classes Are there scientific issues with using ML to assist human annotation?
I've got a 3 class unlabelled dataset where only 1 in 500 elements belong to the 2 classes of interest.
The labels arn't trivially discernible for all the elements of the unlabelled data, however as most elements of the majority class are easily dectable by a simple NN it could be used to filter out most elements of the majority class, bringing the number down to around 1 in 100, and increasing the effectiveness of human annotators time by 50x. The labelled dataset will be used to train, test and validate a classifer.
However I can foresee reasons why this could cause an issue specifically from an academic point of view:

*

*If the annotated data is unrepresentative due to bias in the ML used before human annotation the classifier might struggle to generalise

*Use of an ML data-cleaner, which isn't based on human supplied, justifiable rules, puts a black box at the beginning of the data analysis proccess

*Only annotating a small proportion of the highly prevalent class makes the dataset very selective, would this invite criticism on the misuse of this bias (i.e. manipulation for a desired hypothesis)

All thoughts appreciated

A: I think the key is to keep in mind what you're really after. Is this a kaggle competition? Then sure, your approach sounds fine.
If this is for an academic paper, or medical work that will be put in the field, and you want something that will generalize well and pass peer review, then I don't think this is a good approach. Because you can't just ignore some of your samples.
Besides the 'validity' or 'correctness' of the approach, it also might not help as much as you think. Part of the problem is the pre-classifier that you're proposing. Is it 100% accurate? How do you know, if it's discarding too many to actually look through. The problem is that if it's not 100.0% accurate, than you're losing your most valuable training examples by discarding them, because they are the ones that are fooling the current algorithm.
If you will permanently use this pre-classifier, then it's valid to have this step, and it's just part of your whole 'black box'. But then you need to accurately report the false negatives that it's discarding as part of your overall assessment (and preferably your overall loss function so you can optimize it correctly)

A: If there is a model that can label your data for you, then why even train one?
I would say using another model to label data for a model is bad. First, if a better model exists that can label a dataset why not just use that good model instead. Second, if the classes are highly unbalanced that is much more the reason that you want accurate labels so your model can do it's best. Otherwise you are just confusing it, why would you do that?
Labeling data is arduous for humans, but that is why we are trying to make machines good enough so we can at some point stop doing that.
If you want an easier way, you start by only labeling the minority class, and then labeling an equal number of the other classes and train using that, such that your dataset is no longer unbalanced. Eg say u have 100 samples 10, 40, 50 are the number of samples in each class. So you will start by labeling the 10, the sample 10 from the 40 and then the 50 and label them too; then train a model on a dataset of your 30 samples that are unbiased. This method has it's pros and cons but I will stop here as that was not your original question.

A: It is true that usually more data lead in better decisions. In your case, what you are trying to do is accelerate the labeling process and the way you propose to do it is valid. Since the question is which examples one should manually label and it is true that using a system to discard "uninteresting" examples with high confidence makes sense. It's not about ignoring examples, it is about giving priority to some of them that are not trivial.
Having a classifier that generalizes well to the true distribution of the training data is another topic. You can ensure this by evaluating the classifier in a holdout set split in a stratified way. Since it is cheaper to obtain samples from one of the classes you can balance the training set in a later step (by over/under sampling), after having labeled the data.


text:
Q: Converting data in text file to dataframe I'm having difficulty coming up with a simple solution to make a nice simple dataframe to work with from text in the format below:
    Dose [Gy]   Relative dose [%]    Structure Volume [cm³]
            0                   0                   45888.7
          0.1            0.166667                   27061.7
          0.2            0.333333                   18911.6
          0.3                 0.5                   14907.6
          0.4            0.666667                   12602.7
          0.5            0.833333                   11127.8
          0.6                   1                   10041.9
          0.7             1.16667                   9184.75
          0.8             1.33333                   8480.96
          0.9                 1.5                   7885.19
            1             1.66667                   7382.82
          1.1             1.83333                   6947.77
          1.2                   2                   6570.69
          1.3             2.16667                   6242.93
          1.4             2.33333                   5959.37
          1.5                 2.5                   5713.12
          1.6             2.66667                   5497.12
          1.7             2.83333                   5305.86
          1.8                   3                    5135.8
          1.9             3.16667                   4983.65
            2             3.33333                   4846.38
          2.1                 3.5                    4720.5
          2.2             3.66667                   4604.54
          2.3             3.83333                    4496.7
          2.4                   4                   4396.11
          2.5             4.16667                   4303.21

What I was doing was directly indexing the value on each line, like:
  for line in lines:
       value1 = line[10:20]
       value3 = line[55:70]

However, its not very pythonic, and not robust at all.
Now I am trying to let pandas do the heavy lifting and am struggling to get the data to come out correctly. For example:
df = pd.read_csv(StringIO.StringIO(data), sep="          ",engine='python')

Which outputs something that still includes new lines "\n" and "'" along with the numbers.
Is there a smarter way to tackle this? Or do I need to do a lot of pre-processing before pandas can work with it?
Thanks for any help/advice!

A: I think you need separator s{2,} - 2 or more whitespaces:
import pandas as pd
import numpy as np
from pandas.compat import StringIO

temp=u"""Dose [Gy]   Relative dose [%]    Structure Volume [cm³]
            0                   0                   45888.7
          0.1            0.166667                   27061.7
          0.2            0.333333                   18911.6
          0.3                 0.5                   14907.6
          0.4            0.666667                   12602.7
          0.5            0.833333                   11127.8
          0.6                   1                   10041.9
          0.7             1.16667                   9184.75
          0.8             1.33333                   8480.96
          0.9                 1.5                   7885.19
            1             1.66667                   7382.82
          1.1             1.83333                   6947.77
          1.2                   2                   6570.69
          1.3             2.16667                   6242.93
          1.4             2.33333                   5959.37
          1.5                 2.5                   5713.12
          1.6             2.66667                   5497.12
          1.7             2.83333                   5305.86
          1.8                   3                    5135.8
          1.9             3.16667                   4983.65
            2             3.33333                   4846.38
          2.1                 3.5                    4720.5
          2.2             3.66667                   4604.54
          2.3             3.83333                    4496.7
          2.4                   4                   4396.11
          2.5             4.16667                   4303.21"""
#after testing replace StringIO(temp) to filename
df = pd.read_csv(StringIO(temp),sep=r'\s{2,}', engine='python')

print (df)
    Dose [Gy]  Relative dose [%]  Structure Volume [cm³]
0         0.0           0.000000                45888.70
1         0.1           0.166667                27061.70
2         0.2           0.333333                18911.60
3         0.3           0.500000                14907.60
4         0.4           0.666667                12602.70
5         0.5           0.833333                11127.80
6         0.6           1.000000                10041.90
7         0.7           1.166670                 9184.75
8         0.8           1.333330                 8480.96
9         0.9           1.500000                 7885.19
10        1.0           1.666670                 7382.82
11        1.1           1.833330                 6947.77
12        1.2           2.000000                 6570.69
13        1.3           2.166670                 6242.93
14        1.4           2.333330                 5959.37
15        1.5           2.500000                 5713.12
16        1.6           2.666670                 5497.12
17        1.7           2.833330                 5305.86
18        1.8           3.000000                 5135.80
19        1.9           3.166670                 4983.65
20        2.0           3.333330                 4846.38
21        2.1           3.500000                 4720.50
22        2.2           3.666670                 4604.54
23        2.3           3.833330                 4496.70
24        2.4           4.000000                 4396.11
25        2.5           4.166670                 4303.21

A: use read_fwf as it's a fixed width file and pass the column positions as a list of tuple pairs:
In [63]:
t="""    Dose [Gy]   Relative dose [%]    Structure Volume [cm³]
            0                   0                   45888.7
          0.1            0.166667                   27061.7
          0.2            0.333333                   18911.6
          0.3                 0.5                   14907.6
          0.4            0.666667                   12602.7
          0.5            0.833333                   11127.8
          0.6                   1                   10041.9
          0.7             1.16667                   9184.75
          0.8             1.33333                   8480.96
          0.9                 1.5                   7885.19
            1             1.66667                   7382.82
          1.1             1.83333                   6947.77
          1.2                   2                   6570.69
          1.3             2.16667                   6242.93
          1.4             2.33333                   5959.37
          1.5                 2.5                   5713.12
          1.6             2.66667                   5497.12
          1.7             2.83333                   5305.86
          1.8                   3                    5135.8
          1.9             3.16667                   4983.65
            2             3.33333                   4846.38
          2.1                 3.5                    4720.5
          2.2             3.66667                   4604.54
          2.3             3.83333                    4496.7
          2.4                   4                   4396.11
          2.5             4.16667                   4303.21"""

You can see that the final df is formatted correctly:
df = pd.read_fwf(io.StringIO(t), colspecs=[(0,13),(14,33),(34,59)])
df

Out[63]:
    Dose [Gy]  Relative dose [%]  Structure Volume [cm³]
0         0.0           0.000000                45888.70
1         0.1           0.166667                27061.70
2         0.2           0.333333                18911.60
3         0.3           0.500000                14907.60
4         0.4           0.666667                12602.70
5         0.5           0.833333                11127.80
6         0.6           1.000000                10041.90
7         0.7           1.166670                 9184.75
8         0.8           1.333330                 8480.96
9         0.9           1.500000                 7885.19
10        1.0           1.666670                 7382.82
11        1.1           1.833330                 6947.77
12        1.2           2.000000                 6570.69
13        1.3           2.166670                 6242.93
14        1.4           2.333330                 5959.37
15        1.5           2.500000                 5713.12
16        1.6           2.666670                 5497.12
17        1.7           2.833330                 5305.86
18        1.8           3.000000                 5135.80
19        1.9           3.166670                 4983.65
20        2.0           3.333330                 4846.38
21        2.1           3.500000                 4720.50
22        2.2           3.666670                 4604.54
23        2.3           3.833330                 4496.70
24        2.4           4.000000                 4396.11
25        2.5           4.166670                 4303.21

A: Although the other solutions might be more pythonic, I would propose to first convert the file such that it doesn't contain multiple blank spaces anymore. Then you can easily read it into a pandas dataframe:
import pandas as pd

infile = open('test.txt', 'r')
outfile = open('testout.txt', 'w')

for eachrow in infile:
    stripped = '#'.join(filter(None,eachrow.split('  ')))
    outfile.write(stripped)

infile.close()
outfile.close()

df = pd.read_csv('testout.txt', encoding = 'latin1', sep='#', engine='python')
df.head()


text:
Q: Sync iPhone applications in iTunes Suppose I have one the one hand one iTunes library on a PC used to sync Outlook contacts and calendar plus on the other hand one iTunes library on a Mac that syncs music, podcasts, apps, ringtones, etc. Both libraries are based on iTunes 9.0.2.
It turns out that the iTunes library on the PC always tries to sync apps and ringtones as well. Unfortunately, this boils down to deleting apps and ringtones from the iPhone because the apps are not part of the iTunes library on the PC. After unchecking the checkbox to sync apps and ringtones and plugging the iPhone into the Mac the checkbox is also unchecked on the Mac.
It seems as if the settings for syncing apps and ringtones are stored on the iPhone rather than in the particular iTunes library. Whenever syncing apps and ringtones is active on one machine it is also active on the other and vice versa.
How can I make the PC ignore apps and ringtones and only sync contacts and calendar?

A: This might do the trick.  The problem is that iTunes wants you to sync with only one computer (or manually).  This twiddles the bits in iTunes to convince the iPod/iPhone that the two computers have the same library.
It isn't clear if you need to have the same files on both systems, but it does let you automatically sync to two different computers.


text:
Q: Installing pyobdc I'm trying to install pyodbc using pip3 but getting the below error:
[hvr@07EUW1HVRHAP02A ~]$ pip3 install pyodbc
Collecting pyodbc
  Using cached https://files.pythonhosted.org/packages/81/0d/bb08bb16c97765244791c73e49de9fd4c24bb3ef00313aed82e5640dee5d/pyodbc-4.0.30
.tar.gz
Installing collected packages: pyodbc
  Running setup.py install for pyodbc ... error
    Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dp0ls1b2/pyodbc/setup.py'
;f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" insta
ll --record /tmp/pip-0dv3z9sq-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'pyodbc' extension
    creating build
    creating build/temp.linux-x86_64-3.6
    creating build/temp.linux-x86_64-3.6/src
    gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-s
trong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPYODBC_VERSION=4.0.30 -I/
usr/include/python3.6m -c src/buffer.cpp -o build/temp.linux-x86_64-3.6/src/buffer.o -Wno-write-strings -DHAVE_UNISTD_H -DHAVE_PWD_H -D
HAVE_SYS_TYPES_H -DHAVE_LONG_LONG -DSIZEOF_LONG_INT=8 -I/usr/include
    In file included from src/buffer.cpp:12:0:
    src/pyodbc.h:56:17: fatal error: sql.h: No such file or directory
     #include <sql.h>
                     ^
    compilation terminated.
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-dp0ls1b2/pyodbc/setup.py';f=getattr(tokenize, 'op
en', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-0dv
3z9sq-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-dp0ls1b2/pyod
bc/

A: This issue can be address by first installing ODBC libraries for UNIX by running following commands:

:~$ sudo apt install unixodbc-dev

:~$ pip install pyodbc


text:
Q: How to install Need for Speed Shift 1-2 game? Is there any way to install either Shift 1 or Shift 2 on Ubuntu?

A: You will probably be able to run the application using Wine . Wine is a compatibility layer for Windows executables, allowing a number of Windows applications to run on Linux / Ubuntu.
According to the Wine AppDB entry for NFS Shift 1, the application does have fairly good support and (assuming the patch is installed) should play with little or no problems.

A: I'm not sure if those two are supported by PlayOnLinux  as yet, but that should be your best bet. Installation is automated.
Edit: as George said, Wine (what powers PlayOnLinux) should be able to run it. You will just need to know what you are doing if you encounter problems installing ;).

A: Speed Dreams is a nice linux option for racing. The easiest install method that works for me is located here:
http://www.webupd8.org/2009/12/speed-dreams-140-ubuntu-deb.html


text:
Q: OK to use residual sum of squares for cross-validation of binary outcome? For an OLS model the mean squared error can be used to assess the fit of the trained model on the validation data.
What is the equivalent for a logistic regression model? Can I simply use the following residual sum of squares function?
$RSS=\Sigma^N_{i=1}(y_i-{\hat p})^2$

A: What you propose is equivalent to using the Brier score which is a proper scoring rule.  So it is certainly OK to use it for cross-validation.
See also logistic regression predictive modeling.


text:
Q: $ not defined in JavaScript Firebug is reporting that
$ is not defined
[Break On This Error] $(function(){
I have a simple index.php page that does a php include to include the contents I need.
The contents are as follows:

        <form id="ipad" name="ipad">
                Zip Code:
                <input class="searchBox Black" id="txtZip" name="txtZip" type="text" />

                <input type="submit" value="Submit">
        </form>

I do this in other places and I am fine. I don't understand the error.....

A: Did you include the jQuery library?

A: Add this before your script tag. It uses google's CDN.

A: Are you including jQuery at the top of your script?


text:
Q: Python producer/consumer with process and pool I'm trying to write simple code for producer consumer with process. Producer is a process. For consumer I'm getting processes from Pool.
from multiprocessing import Manager, Process, Pool
from time import sleep
def writer(queue):
   for i in range(10):
     queue.put(i)
     print 'put 1 size now ',queue.qsize()
     sleep(1)

def reader(queue):
   print 'in reader'
   for i in range(10):
     queue.get(1)
     print 'got 1 size now ', queue.qsize()

if __name__ == '__main__':
    q = Manager().Queue()
    p = Process(target=writer, args=(q,))
    p.start()
    pool = Pool()
    c = pool.apply_async(reader,q)

But I'm getting error,
Process Process-2:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "pc.py", line 5, in writer
    queue.put(i)
  File "<string>", line 2, in put
  File "/usr/lib/python2.7/multiprocessing/managers.py", line 758, in _callmethod
    conn.send((self._id, methodname, args, kwds))
IOError: [Errno 32] Broken pipe

Can anyone point me, where am I going wrong.

A: Hi I had found this answer,
from multiprocessing import Manager, Process, Pool,Queue
from Queue import Empty

def writer(queue):
   for i in range(10):
     queue.put(i)
     print 'put %i size now %i'%(i, queue.qsize())

def reader(id, queue):
   for i in range(10):
     try:
       cnt = queue.get(1,1)
       print '%i got %i size now %i'%(id, cnt, queue.qsize())
     except Empty:
       pass

class Managerss:
   def __init__(self):
     self.queue= Queue()
     self.NUMBER_OF_PROCESSES = 3

   def start(self):
     self.p = Process(target=writer, args=(self.queue,))
     self.p.start()
     self.workers = [Process(target=reader, args=(i, self.queue,))
                        for i in xrange(self.NUMBER_OF_PROCESSES)]
     for w in self.workers:
       w.start()

   def join(self):
     self.p.join()
     for w in self.workers:
       w.join()

if __name__ == '__main__':
    m= Managerss()
    m.start()
    m.join()

Hope it helps


text:
Q: How to transform a tree using a futumorphism in PureScript? I have the following data type and example equation that I want to transform with a futumorphism...
import Matryoshka as M
import Data.Functor.Nu (Nu(..), observe, unfold)

data ArithmeticF a
  = Mult a a
  | Div a a
  | Add a a
  | Num Number

type Arithmetic = Nu ArithmeticF
derive instance functorArith :: Functor ArithmeticF

equation :: Arithmetic
equation = (div (n 3.0) (n 4.0)) `add` (div (n 3.0) (n 4.0))

mult :: Arithmetic -> Arithmetic -> Arithmetic
mult a b = M.embed $ Mult a b

div :: Arithmetic -> Arithmetic -> Arithmetic
div a b = M.embed $ Div a b

add :: Arithmetic -> Arithmetic -> Arithmetic
add a b = M.embed $ Add a b

n :: Number -> Arithmetic
n a = M.embed $ Num a

Using futu
this is my attempt at writing a function to factor out (Div (Num 1.0) (Num 4.0)) from the equation.
In the end I want the resulting tree to be (Mult (Div (Num 1.0) (Num 4.0)) (Add (Num 3.0) (Num 3.0))).
This function type checks but I must be doing something wrong, since it doesn't evaluate when I run it.
solve :: Arithmetic -> Number
solve = M.cata algebra

simplify :: Arithmetic -> Arithmetic
simplify s = M.futu factor s

factor :: GCoalgebra (Free ArithmeticF) ArithmeticF Arithmetic
factor s = case M.project s of
  (Add a b) ->
    case (Tuple (M.project a) (M.project b)) of
      (Tuple (Div c d) (Div e f)) -> do
        let dd = solve d
        let ff = solve f
        if dd == ff
          then
            Mult
              (liftF $ observe (unfold dd (\m -> Div 1.0 dd )))
              (liftF $ observe (unfold c (\g -> Add c e )))
          else Add (liftF $ observe a) (liftF $ observe b)
      _ -> Add (liftF $ observe a) (liftF $ observe b)
  (Div a b) -> Div (liftF $ observe a) (liftF $ observe b)
  (Mult a b) -> Mult (liftF $ observe a) (liftF $ observe b)
  (Num a) -> (Num a)

main = log $ M.cata show (simplify equation)

A: I seem to have missed the connection between Recursive/Corecursive and Nu's observe and unfold methods.
class (Functor f) <= Recursive t f | t -> f where
  project :: t -> f t
instance recursiveNu ∷ Functor f ⇒ Recursive (Nu f) f where
  project = observe
class (Functor f) <= Corecursive t f | t -> f where
  embed :: f t -> t
instance corecursiveNu ∷ Functor f ⇒ Corecursive (Nu f) f where
  embed = flip unfold (map observe)

In the end I was able to write futu's GCoalgebra like so:
factor :: GCoalgebra (Free ArithmeticF) ArithmeticF Arithmetic
factor s = case M.project s of
  (Add a b) -> case Tuple (observe a) (observe b) of
    Tuple (Div c d) (Div e f) ->
      if solve d == solve f -- observe d == observe f
      then Mult (liftF $ Div (M.embed $ Num 1.0) d) (liftF $ Add c e)
      else Add (liftF $ observe a) (liftF $ observe b)
    _ -> Add (liftF $ observe a) (liftF $ observe b)
  (Div a b) -> Div (liftF $ observe a) (liftF $ observe b)
  (Mult a b) -> Mult (liftF $ observe a) (liftF $ observe b)
  (Num a) -> (Num a)

For some reason, I could make a catchall case like a -> M.project a, so there's some verbosity in handling the default cases.  There might be a better way to do this.


text:
Q: Newton-Raphson in C I am writing a program to find an approximation of the square root of a given integer n using the Newton-Raphson method in C. I have used the following formula:

This is my code:
#include <stdio.h>

double newton_raphson(int n, int iter);

double newton_raphson(int n, int iter)
{
    if(iter == 0) // base case
        return 1;
    else // iterative case
        return (1/2*(newton_raphson(n, iter-1) + n/(newton_raphson(n, iter-1))));
}

int main()
{
    int n;
    int i;

    printf("Enter a number you want to know the square root of:\n");
    fflush(stdout);
    scanf("%d", &n);
    printf("Enter number of iterations to be worked out:\n");
    fflush(stdout);
    scanf("%d", &i);

    printf("%.3f", newton_raphson(n,i-1));

    return 0;
}

When I input 2 and 3, and the output expected is 1.417 (the square root of 2 after 3 iterations) I get the error -1.#IO. When I input 5 and 2 for example, I get 0.000. I have debugged it but still can't really figure out what the problem is. Any help is greatly appreciated.
edit: elaborated on the output

A: Your issue seems to be that you are mishandling floating point arithmetic.

*

*The first argument of the newton_raphson function should be a double, especially because you seem to be calling it recursively. As it is right now, you just cast the result of one iteration into an integer and pass that to the next iteration.

*1 / 2 uses integer arithmetic. That should be 0.5 or 1.0 / 2.0 instead. Note that in integer arithmetic, 1 / 2 is 0. The error you see is because then you pass that 0 to the next iteration and then it divides by 0.
The fixed code
#include <stdio.h>

double newton_raphson(double n, int iter);

double newton_raphson(double n, int iter)
{
    if (iter == 0) {
        return 1;
    }
    else {
        return 0.5 * (newton_raphson(n, iter - 1) + n/(newton_raphson(n, iter - 1)));
    }
}

int main()
{
    int n;
    int i;

    printf("Enter a number you want to know the square root of:\n");
    fflush(stdout);
    scanf("%d", &n);
    printf("Enter number of iterations to be worked out:\n");
    fflush(stdout);
    scanf("%d", &i);

    printf("%.3f\n", newton_raphson(n, i - 1));

    return 0;
}

Possible improvements
As others pointed out in the comments, you could make this implementation more efficient.
First, you can eliminate a function call by saving the result in a variable. Since this is a recursive function, this will save you a lot of execution time if you have many iterations.
double newton_raphson(double n, int iter)
{
    if (iter == 0) {
        return 1;
    }
    else {
        double xk = newton_raphson(n, iter - 1);
        return 0.5 * (xk + n / xk);
    }
}

Then, you could eliminate recursion alltogether. This will make your program consume much less memory if you run with many iterations because you get rid of unnecessary stack operations.
double newton_raphson(double n, int iter)
{
    int k;
    double xk = 1;
    for (k = 0; k < iter; k++) {
        xk = 0.5 * (xk + n / xk);
    }
    return xk;
}

Some more tips
For the iteration count, you should use unsigned int (or simply unsigned) instead of int. It does not make sense to run a negative number of iterations, eg. you can't run -5 iterations... so you do not need a signed integer there.
#include <stdio.h>

double newton_raphson(double n, unsigned iter);

double newton_raphson(double n, unsigned iter)
{
    unsigned k;
    double xk = 1;
    for (k = 0; k < iter; k++) {
        xk = 0.5 * (xk + n / xk);
    }
    return xk;
}

int main()
{
    int n;
    unsigned i;

    printf("Enter a number you want to know the square root of:\n");
    fflush(stdout);
    scanf("%d", &n);
    printf("Enter number of iterations to be worked out:\n");
    fflush(stdout);
    scanf("%u", &i);

    printf("%.3f\n", newton_raphson(n, i - 1));

    return 0;
}

Few more things:

*

*It is usually a good practice to protect your code from possible division by zero errors, by checking the parameters of your functions or the results of function calls that can possibly return zero.

*You should possibly check the input for negative numbers and tell the user that a negative number isn't something you can calculate the square root of with this algorithm.

*For the input, you could allow the user to enter a floating point number instead of an integer.


text:
Q: Should you build your docker image in your CI build step? Are there any best practices or patterns that advise building your docker image, rather than just your project, during your CI build step?
I have a GitLab CI pipeline with these steps:

*

*build (builds the dotnet solution with dotnet build )

*test (runs the unit tests with dotnet test )

*package (builds the docker image with a Dockerfile that builds the solution with dotnet publish  then copies the output to the final image, and pushes the image to the registry)

*deploy (deploys the docker image from the registry to the environment)

This all works fine, but it occurs to me that if the package and publish steps only happen on master , then you would only know about a problem with docker build once branches are merged.
Should the build step (and the test step???) use the docker build rather than an independent build of the project, therefore ensuring that "the whole thing builds" rather than just "the dotnet solution" builds? I chose the latter initially, as it seemed to be the simplest way to fail early, for the fewest possible reasons, but now I'm not so sure this is optimal.

A: On the pipeline for a Merge Request you could build a docker image from there as well to see if it works. Just keep the option in GitLab to force that the Merge Request should be rebased before it passes. There is a lot of strategies depending on multiple things. So it's hard to say best practices.
A simple pipeline example of a Merge Request:

*

*build

*test

*build-docker

But try to rebase before pushing if there are any conflicts that are easier to solve locally.


text:
Q: populate lable control inside a gridview based on inline Conditional statement I am trying to display a plain text in the column(contains a label) of gridview based on  a condition. Here is my erroneous code. Please correct.
 <asp:Label ID="lblAsgn" runat="server"   Text= '<%#Eval("StatusId") == 0 ? "NEW" : "OLD" %>' > </asp:Label>

Thanks in advance.
BB

A: <asp:Label
    ID="lblAsgn"
    runat="server"
    Text='<%# FormatText(Eval("StatusId")) %>' />

where FormatText could be a method in your code behind:
protected string FormatText(object o)
{
    int value;
    if (int.Parse(o as string, out value) && value == 0)
    {
        return "NEW";
    }
    return "OLD";
}

A: Try this :
 <asp:Label ID="lblAsgn" runat="server"   Text= '<%# Eval("StatusId").Equals(0) ? "NEW" : "OLD" %>' > </asp:Label>


text:
Q: javascript won't change dom value I have no  idea what i doing wrong.
I dynamically insert rows to table. These rows have some cells, in cells I have input elements.
Next i change values in input via browser (just type in filed :) ).
When i get element by id of this_table values of input fields are default.

var testbtn=document.getElementById('test');
testbtn.onclick = function(){
var tab=document.getElementById('testtab');
var row = tab.insertRow(1);
var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.className='th_lp';
    cell1.innerHTML='<input id="testid" value="1"></input>';
    cell1.className='th_lp';
    cell2.innerHTML='bb';
}
var testbtn2=document.getElementById('test2');
test2.onclick=function(){
 alert(document.getElementById('testtab').innerHTML);
}

    th1	th2

<button id="test">
TEST
</button>

<button id="test2">
TEST2
</button>

Here is simple example
jsFiddle

*

*click btn

*change input text to some else

*click btn

when I do these steps i have alert message
"......"
input value is still 1. Why?
How can I get innerHTML of this table with new input values?

A: If the user changes the value of an input field, then the property value  is changed but not the attribute. innerHTML does show the content of the  attribute value but not the property value. You would need to manually sync  the attributes before calling innerHTML
You could do something like that:

var testbtn = document.getElementById('test');
testbtn.onclick = function() {
  var tab = document.getElementById('testtab');
  var row = tab.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.className = 'th_lp';
  cell1.innerHTML = '<input id="testid" value="1">';
  cell1.className = 'th_lp';
  cell2.innerHTML = 'bb';
}
var testbtn2 = document.getElementById('test2');
test2.onclick = function() {

  //search for all input elements
  var inputElements = document.getElementsByTagName('input');

  for( var i=0; i < inputElements.length ; i++ ) {
    //set the attribute value of the input element to the content of the property value
    inputElements[i].setAttribute('value',inputElements[i].value );
  }

  alert(document.getElementById('testtab').innerHTML);
}

    th1
    th2

<button id="test">
  TEST
</button>

<button id="test2">
  TEST2
</button>

A: The value attribute of the input will never change unless you set it manually.  Think of this as the "default" value (used primarily with form.reset).  You are going to have to add an onblur/onkeyup event to update the value if you want the HTML to dynamically reflect the value.

A: Each time you add a new input element, it gets the same id as the last one. ID's should be unique. Also, input is not a content element. It should not have a closing tag.

A: Before I fully looked at what this is about, I see cell1.className blah TWICE, while I see no such thing for cell2... is that why i get an error?

A: In your jsfiddle, if you change:
alert(document.getElementById('testtab').innerHTML);

to:
alert(document.getElementById('testid').value);

you will see that the input's value matches what you entered.

A: The attribute's main role is to initialize the DOM properties. So, once the DOM initialization completed, the attribute's job is done.
In general, property values can change, whereas the attribute values can never be changed.
Replace
document.getElementById('testtab').innerHTML;

with
document.getElementById('testid').value;


text:
Q: How to add product to cart programmatically in Magento I am unable to add product to cart programmatically in Magento , I have tried every possible technique to add product with quantity to cart ( in Magento), following are the things I have tried and forums/sites taken help from. But none of them is working. I am using Magento Community edition 1.9.1.1. If anyone has any suggestion/answer, please share.

*

*Tried to do it via URL - e.g. [Magento_Store_URL]/checkout/cart/add?product=[id]&qty=[qty] or even like this -  [Magento_Store_URL]/checkout/cart/add/product/[id]/qty/[qty]. I have also tried with form_key, generated via Mage::getSingleton('core/session')->getFormKey();. All these stuff is not working at all. These things are mentioned here - Magento website

*Next, I have tried via programmatically, like this.

<?php
require_once 'app/Mage.php';
Mage::app();
$product=new Mage_Catalog_Model_Product();
$product->load(1); // 1 is product id, this is simple product ( type)
$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote->addProduct($product, 1 ); // quantity is 1
$cart = Mage::getSingleton('checkout/cart');
$cart->init(); // tried commenting this too!
$cart->addProduct($product, 1 ); // quantity is 1
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$quote->collectTotals()->save(); header('Location: '. 'http://localhost/magento/index.php/checkout/cart');

*

*Also tried following.

<?php
require_once 'app/Mage.php';
Mage::app();
$params=array( 'product'=>1, 'qty' => 3 );
$cart = Mage::getSingleton('checkout/cart');
$product = new Mage_Catalog_Model_Product();
$product->load($params["product"]);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
header('Location: '. 'http://localhost/magento/index.php/checkout/cart');

I have taken help from following websites.

*

*http://gzchauhan.blogspot.in/2012/03/programmatically-add-product-in-cart-in.html

*Magento - Add a product to the cart via query string without form_key parameter

*https://magento.stackexchange.com/questions/17997/product-not-adding-to-cart

*https://magento.stackexchange.com/questions/32967/programmatically-adding-product-to-cart-returns-empty-price

*http://subasd.com.np/magento-programmatically-add-product-to-cart-with-custom-options/
Is there any wrong in my code, whatever I have tried or is there any setting issue with my Magento Installation?
Update 1
I have tried below from the answer proposed to this question, still that is not working.

$formKey = Mage::getSingleton('core/session')->getFormKey();
$params = array(
    'product' => 3,
    'qty' => 2,
 'form_key' => $formKey
);
$product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($params['product']);
$cart = Mage::helper('checkout/cart')->getCart();
$cart->addProduct($product, $params);
$cart->save();

Update 2
This is working, if I create a controller and place all code there, not working - in a standalone page that refers /app/Mage.php .

A: Since 1.8 you won't be able to add a product to the cart from a GET request alone, as you need to provide the form_key.
You should be able to add a product to the cart using the following:
form_key is the main thing to get right here.
$params //should include at least a valid form_key, qty

$product = Mage::getModel('catalog/product')
                    ->setStoreId(
                        Mage::app()
                        ->getStore()
                        ->getId()
                    )
                    ->load($product_id);

$cart = Mage::helper('checkout/cart')->getCart();
$cart->addProduct($product, $params);
$cart->save();

Take a look at the addProduct function in app\code\core\Mage\Checkout\Model\Cart.php if you need to debug (and then in the app\code\core\Mage\Sales\Model\Quote.php too)

A: Here is the easy way to add product to cart/quote:
$customer = Mage::getModel('customer/customer')->load($customerId);
$product = Mage::getModel('catalog/product')->load($productId);
// load quote by customer and store...
$quote = Mage::getModel('sales/quote')->setStore($storeId)->loadByCustomer($customerId);
$quote->addProduct($product, 1);
$quote->setIsActive(1);
$quote->collectTotals()->save();