text:
Q: Exchange message size limit My client's Exchange 2010 has been set to send/receive messages up to 25MB, however Exchange still rejects messages 16-20MB in size:
Technical details of permanent failure:
Google tried to deliver your message, but it was rejected by the recipient domain.
We recommend contacting the other email provider for further information about the
cause of this error. The error that the other server returned was: 552 552 5.3.4
Message size exceeds fixed maximum message size (state 17).

They don't want a 25MB limit, only 20MB. But the limit doesn't seem to have an effect - messages still get rejected due to size.
Send & Receive connectors are all set to 25MB limit.
Anyone have any ideas on this?

A: In addition to your limits on send & receive connectors, there's a global setting that controls message size limit, as well as possibly limits on message size for individual mailboxes.
The global limit is found by going to:
EMC -> Organization Configuration ->Hub Transport -> Global Settings -> Transport Settings
And be aware that this setting can take some time to apply.
And, here's a link to an article on the subject, which actually has three more locations that probably don't apply, but that you can also find message limits in.


text:
Q: Imagemagick's -lat '50x50' not working in minimagick I need to run local adaptive threshold(-lat) method in MiniMagick.
I tried with the following code:
image.lat '50x50'
Its give an error stack level too deep when image.write 'output.jpg' is run.

Can anyone suggest a way to use (-lat) method in MiniMagick.

A: The common approach to stack options with MiniMagick is combine_options:
image.combine_options do |c|
  c.lat '50x50'
  # more options
end

This should not help in your case, though. Image#write copies the file from temporary location to the local file with given name. You might want to inspect your temporary file in /var/folders/.... to see whether the threshold was applied.
It sounds like an imagemagick glitch. Did you try
$ mogrify -lat 50x50 file.jpg

Does it work?

A: It looks like the -lat command is not included in mogrify. I ran into the same problem and found this question, two years after the OP, using IM version 6.9.2-3 Q16 x64 on Windows 7.
There is a discussion on the ImageMagick board here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery nested drag and drop event propagation I've got two nested divs both droppable. Based upon the content of the inner div it's determined through the accept property whether an element is allowed to drop. By doing so I prevent duplicates in the inner droppable.
The problem is that if the accept property is set to false within the inner div the event is bubbled to the parent. The parent accepts the drop and that is exactly what I don't want. One complicating factor is that the accept function's arguments consist only of the dropped nodes, I have no reference to the actual event object so I can't stop propagation :(
So the big question is: can I prevent event propagation to the parent droppable if the child accept property evaluates to false?
The code:
$(node).droppable({
    tolerance: "intersect",
    accept: function(nodes) {
                    //if acceptPM evaluates to false the event is bubbled which I don't want
        return acceptPM(nodes);
    },
    greedy: true,
    activeClass: "ui-state-default",
    hoverClass: "ui-state-hover",
    drop: function(event, ui) {
        //do something
    }
});

A: Solved it.
I worked around the event propagation, I removed the accept function and added a check in the drop function. If the item allready exists do nothing and the drop is reverted :)
Perhaps not the cleanest way but it works.
Quite simple in hindsight..


text:
Q: Android audio level meter I got a question I hope you can help with, I have searched but had no luck yet. Basically I have made a few ios apps and a couple android but I'm still learning the basics of java and android etc. I have radio streaming apps and have audio level bars on the ios versions, I want to put these on the android versions but can't work out the code to have a left and right bar for sound. Any ideas where to learn some code and also so it stretches from left of screen to right but for all screen sizes? Thanks in advance.

A: Checkout the Visualizer class. It should provide you with what you need to display a level meter. Unfortunately, it is only available in API 9 and higher and requires the RECORD_AUDIO permission.


text:
Q: cplusplus importing csv does not recognise first column? I'm trying to import a csv file into my c++ program but I am having a few problems and would like some clarification.
The data in the csv file is arranged like below. As you can see there are 12 cells that I would like to import.
x, y, z, p
1, 2, 3, 4
5, 6, 7, 8

My function to import said csv file is the following:
  while ( getline (myfile, stringg, ','))
    {
        std::cout << "j: " << j << "  " << stringg << std::endl;

        j++; //Note: j counts each cell.
    }
    myfile.close();
}

Everything imports perfectly fine. However it seems j has stopped counting. This shouldn't be the case since the number in the csv file is still being printed.
j: 0 x
j: 1 y
j: 2 z
j: 3 p
1
j: 4 2
j: 5 3
j: 6 4
5
j: 7 6
j: 8 7
j: 9 8

Now I know why I believe it's doing that. The end of each line does not have a comma at the end. However! This still does not account for why j stopped counting?

A: count of j is correct... if you take a closer look your file will be like this
x, y, z, p'\n'
1, 2, 3, 4'\n'
5, 6, 7, 8'\n'

So when you when the value of j is 3 line read by getline() is p'\n'1 which when printed on console as
j: 3 p
1

after that j is incremented and next token read in 2...same for rest..

A: getline is reading the input until the next ',' character. In your case, this means that stringg will contain this:
1. iteration: stringg == "x"
2. iteration: stringg == " y"
3. iteration: stringg == " z"
4. iteration: stringg == " p\n1" // The fourth string contains the next line!

Errors like these should be easily visible when debugging the program.
One approach to solve this problem could be to read line by line using the default getline and inside this loop split the resulting string into further parts using ',' as the separator.


text:
Q: Magento javascript undefined is not a function jquery selectric? I am having a problem on my site trying to add a few dropdown menus to the header!
I am using Magento CE 1.8.0 with Airhotels module.
The weird thing is on some pages it works and on some it doesn't. It seems to me that pages related directly to Airhotels module don't seem to be working, maybe this is a clue?
As you can see from these images I am getting error undefined is not a function:

*

*broken

*

*working

I have added this line to airhotels.xml under All Pages
<action method="addJs"></action>
This is my jQuery script located in public_html\app\design\frontend\default\stylish\template\page\html\header.phtml

Any help is appreciated I am really stuck!

A: i think the problem is with getting the value
try something like that (this is bad example - next one is good):

Select something

 Choice 1

 Choice 2

 Choice 3

with JS code:
$(function(){
    $('.customOptions').selectric({
        maxHeight: 300,
        onChange: function(element) {
           alert( $(element).val() );
        }
    });
});

result is empty,
but now try something like this:

Select something

 Choice 1

 Choice 2

 Choice 3

put something into LI - ie.  Choice 1 with data attribute where you put some custom values:
$(function(){
    $('.customOptions').selectric({
        maxHeight: 300,
        onChange: function(element) {
           alert( $('.selectricItems').find('.selected span').attr('data-value') );
        }
    });
});

i think that if you use this method you should be able to get selected value from data-attr  and do whatever you want. (REMEMBER - do not put data-attr=""  into LI tag - it will not work)


text:
Q: Use React Material to fit table to page I want to implement different sub pages:

Full code example:
https://stackblitz.com/edit/react-qvzw66?file=src%2FBusinessDetails.js
Main page:
const useActiveAccountStyles = makeStyles(theme => ({
  root: {
    display: 'flex'
  },

  aside: {
    display: 'flex',
    flexDirection: 'column'
  },
  asideLink: {
    marginBottom: '8px',
    width: '230px',
    textDecoration: 'none',
  }
}))

export default function App() {
  const styles = useActiveAccountStyles();

  return (
    <React.Fragment>
      {/*
Activate Account wizard
*/}

      <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start">
        <Grid item >
          <Box m={5} pl={10}>
            <Router>
              <Container className={styles.root}>

                  <Link className={styles.asideLink} to='/business-structure'>Business structure</Link>
                  <Link className={styles.asideLink} to='/business-representative'>Business representative</Link>

                <Switch>
                  <Route path='/business-structure' component={BusinessStructure} />
                  <Route path='/business-representative' component={BusinessRepresentative} />
                </Switch>
              </Container>
            </Router>
          </Box>

        </Grid>

      </Grid>

    </React.Fragment>
  )
}

Table page:
import { useState, useContext } from 'react';
import { useHistory } from "react-router-dom";
import { Typography, Container, Box, TextField, FormControl, Grid, Button } from '@material-ui/core'
import SelectOption from './SelectOption'
import { DataGrid, GridColDef, GridValueGetterParams } from '@material-ui/data-grid';

const columns = [
    { field: 'id', headerName: 'ID', width: 90 },
    {
        field: 'status',
        headerName: 'Status',
        width: 150,
        editable: true,
    },
    {
        field: 'invoiceNumber',
        headerName: 'Invoice Number',
        width: 150,
        editable: true,
    },
    {
        field: 'client',
        headerName: 'Client',
        width: 150,
        editable: true,
    },
    {
        field: 'invoiceTotal',
        headerName: 'Invoice Total',
        width: 150,
        editable: true,
    },
    {
        field: 'date',
        headerName: 'Date',
        type: 'number',
        width: 110,
        editable: true,
    },
    {
        field: 'dueDate',
        headerName: 'Due Date',
        description: 'This column has a value getter and is not sortable.',
        sortable: false,
        width: 160,
        valueGetter: (params) =>
            `${params.getValue(params.id, 'firstName') || ''} ${params.getValue(params.id, 'lastName') || ''
            }`,
    },
];

const rows = [
    { id: 1, status: 'Paid', invoiceNumber: '343423', age: 35 },
    { id: 2, status: 'Paid', invoiceNumber: '433222', age: 42 },
    { id: 3, status: 'Paid', invoiceNumber: '344432', age: 45 },
    { id: 4, status: 'Paid', invoiceNumber: '233223', age: 16 },
    { id: 5, status: 'Paid', invoiceNumber: '545322', age: null },
    { id: 6, status: 'Paid', invoiceNumber: '334322', age: 150 },
    { id: 7, status: 'Paid', invoiceNumber: '444322', age: 44 },
    { id: 8, status: 'Paid', invoiceNumber: '232312', age: 36 },
    { id: 9, status: 'Paid', invoiceNumber: '545344', age: 65 },
];

export default function BusinessStructure(props) {
  return (
    <Container style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Typography variant="h4">
            All Invoices
        </Typography>

        <Box>

                <DataGrid
                    rows={rows}
                    columns={columns}
                    pageSize={5}
                    checkboxSelection
                    disableSelectionOnClick
                />

        </Box>
    </Container>
);
}

Do you know how I can code can be edited in a way to resize according to above pictures?

A: All you need to do is remove your  display: 'flex', justifyContent: 'space-between' from your Container.
By setting flex to it you are saying that all children inside here are flex items and by default the flex-direction is row. Alternatively you could also include flex-direction: column but that would achieve the same thing as just removing them.
export default function BusinessStructure(props) {
  return (
    <Container>
        <Typography variant="h4">
            All Invoices
        </Typography>

        <Box>

                <DataGrid
                    rows={rows}
                    columns={columns}
                    pageSize={5}
                    checkboxSelection
                    disableSelectionOnClick
                />

        </Box>
    </Container>
);
}


text:
Q: How can one determine the pkey of an inserted row after using pg_insert()? I need to be able to identify the row I just inserted after using pg_insert, but the doc just says that it returns true/false. How can I determine the pkey of the record from a pg_insert()? I know i could use a hand crafted query with a "RETURNING pkey" at the end, but I don't want to use the pg_query() because pg_insert automatically escapes everything for you so I want to use it instead.

A: You can use pg_query_params with a RETURNING clause and use parameters to escape everything.
The only problem with this function is that, when an error occurs, you cannot know the real cause of the problem. Getting correct error message means using pg_send_query_params with pg_get_result.
See a code example.

A: Since there are no id concept in pgsql (only sequences), you can use the following code.
SELECT currval(pg_get_serial_sequence(tablename, 'id'));


text:
Q: Extracting MUST-match and MUST_NOT-match Boolean clauses from an EDismax query I have a Query q returned by ExtendedDismaxQParser's parse() method. I need to generate from that Query q a new BooleanQuery qNew. The BooleanQuery qNew should consist of:

*

*a MUST-match Boolean clause for each MUST-match clause in the original Query q.

*a MUST_NOT-match Boolean clause for each MUST_NOT-match clause in the original Query q.

*a single SHOULD-match Boolean clause consisting of the rest of the original Query q.

*Other certain SHOULD-match clauses I might need to add.

For example, if the Query q is a +b c +d -e -f g and the other certain clauses are x, y and z then the new BooleanQuery qNew should be (a c g) +b +d -e -f x y z.
In order to generate that BooleanQuery qNew I need to extract all the MUST-match and MUST_NOT-match Boolean clauses from the original Query q, which would have been easy had q been a BooleanQuery. I looked at the ExtendedDismax parse() method code, and the returned Query q's dynamic type can be either a BooleanQuery or a BoostedQuery. Is there a general way to perform that transformation from the Query q returned by ExtendedDismax parse() method to the new BooleanQuery qNew?
Clarification: The original Query q doesn't necessarily consists of any MUST-match, MUST_NOT-match or SHOULD-match clauses. As a matter of fact, the original Query q can be any Query that can be returned by ExtendedDismaxQParser's parse() method. Queries such as a b c and a b -c shuold be transformed into (a b c) x y z and (a b) -c x y z respectively. Therefore, wrapping the original query in a MUST-match clause of a Boolean query and add those x, y and z clauses (as suggested in a comment) wouldn't solve the problem in such cases.


text:
Q: Retrieve and Rank Python: What kind of "Answer Data" to pass to rank method? I'm accessing the Retreive-And-Rank service using Python. So far I've uploaded my configuration and documents and have trained my ranker on the relevance file. All that is left, I presume, is to pass some query results (from Solr?) into the "rank" method of my R-A-R object.
My question: What exactly are those results, and what form do they come in? And how do I access them?
Right now I am accessing the PySolr object using the get_pysolr_client() method, then searching a query and using the returned results:
answer_data = pysolr.search(query)
rrv1.rank(<my_ranker_id>, answer_data, top_answers=10)

I'm doing this because it's analogous to what IBM does in the rank() method in the Java example. But I'm getting the error message:
AttributeError: 'Results' object has no attribute 'read'

I'm getting this because PySolr returns a "Results" object.
What should I be passing instead to the rank() method to get it to work?
The Retrieve_and_Rank specification for the rank method is as follows, and I think that answer_data is supposed to be a "file-like" object:
def rank(self, ranker_id, answer_data, top_answers=10)

A: One workaround is to call pysolr's _send_request method:
results = pysolr._send_request("GET", path="/fcselect?q=%s&ranker_id=%s&wt=json" %
                              (query_string, ranker_id))
for doc in json.loads(results)["response"]["docs"]:
    print doc

Thanks to rishavc on dW Answers for this.


text:
Q: Can I add methods and attributes to a class derived from peewee.Model I am working on an app with Cherrypy and Peewee, and I would like to know if my approach is good or wrong and dangerous.
All the examples of Peewee classes that I found have only the Meta subclass and the <xxx>Field attributes. I have never found an example with helper methods or properties.
I tried to make my own, and it works!
It works very well and I find it convenient, but I am afraid that I'm getting into trouble.
So my question is: can I add as many properties and methods to my classes derived from the peewee.Model, so I can do cool things like in the snippet below?
Or are there limits and guidelines to what I can do?
class PeeweeModel(peewee.Model):
    class Meta:
        database = db

class TempFile(PeeweeModel):
    file_type = peewee.IntegerField()
    original_file_name = peewee.CharField()
    temp_file_name = peewee.CharField()

    DRAWING = 1
    PDF = 2

    def href(self, settings):
        if(self.file_type == DRAWING:
            return self.temp_file_name
        elif(self.file_type == PDF:
            if settings.show_pdf:
                return self.temp_file_name
            elif settings.show_bitmap:
                bitmap = TempFile.create_bitmap_from_pdf(self.temp_file_name)
                return bitmap.temp_file_name

    @staticmethod
    def create_bitmap_from_pdf(self, file_name):
        [...]

Edit:
I would appreciate a comment about the constructor.
For example, I would like to do both these:
tmp = TempFile(file_name)                            # and run my own constructor
tmp = TempFile(original_file_name=file_name, [...])  # and run Peewee's constructor

A: Yes! Of course you can, by all means. Models are just normal python classes, so you can treat them as such and add methods, properties, attributes, etc.


text:
Q: Pass props to React component dependent on route I have a root component which uses react-router:
<HashRouter>

    <Sidebar />

    <Switch>
      {/* -- routes go here -- */}
    </Switch>

</HashRouter>

I want my Sidebar component to have different content depending on which route we're on. So if I have two routes, foo and bar, when I go to /foo I want Sidebar to have different props than when I visit /bar. I've tried passing the location as a prop:
<Sidebar location={this.context.router.location.pathname} />

But I'm pretty sure that's not how it works... And sure enough it didn't work.

A: You can use withRouter to pass values from route to another component. This way you can do conditional rendering or implement any other logic related to the current route to your component.

You can get access to the history object's properties and the closest
  's match via the withRouter higher-order component. withRouter
  will re-render its component every time the route changes with the
  same props as  render props: { match, location, history }.

Example (from official documentation)
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (

You are now at {location.pathname}

    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

A: Here's a method using React Router's withRouter to 'connect' the <Sidebar /> component to the router.
With withRouter we create our <Sidebar /> component as normal, then 'connect' it like this:
//Sidebar
class Sidebar extends React.Component {
  render() {
    const { location } = this.props;

    return (

Sidebar

You are now at {this.props.location.pathname}

    )
  }
}

const SidebarWithRouter = withRouter(Sidebar);

In the end we have a new <SidebarWithRouter /> component connected to the router so it has access to match, location, and history.
Unfortunately the code snippet won't work in Stackoverflow due to the history within the iframe, but here's the code, and a working Codepen.
let { BrowserRouter, Link, Route } = ReactRouterDOM;
let { Switch, withRouter } = ReactRouter;
let Router = BrowserRouter;

// App
class App extends React.Component {
  render() {
    return (
      <Router>

              <Link to="/">Home</Link>

              <Link to="/about">About</Link>

            <SidebarWithRouter  />

          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/about" component={About} />
          </Switch>

      </Router>
    );
  }
}

//Home
const Home = () => (

Home

This is the Home Page.

);

//About
const About = () => (

About

This is about

);

//Sidebar
class Sidebar extends React.Component {
  render() {
    const { location } = this.props;

    return (

Sidebar

You are now at {this.props.location.pathname}

    )
  }
}

const SidebarWithRouter = withRouter(Sidebar);

ReactDOM.render(<App />, document.getElementById("app"));


text:
Q: Gradient border around popup Currently I'm working on a HTML implementation of the Office Ribbon to use in Web Apps.
Here's a screenshot that shows you:

You see that I have a DropDown on the ribbon under "New Items". So far so good, but let's compare it against the real Office implementation:

Here you see that the dropdown menu has a gradient around it that makes makes it's clear that it's laying on top of the interface.
Now I cannot accomplish then so I was hoping someone can given me a solution to this issue.
The HTML for the dropdown element is as following:

        New
Items

Create

Manage

Delete

The css is as follows:
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .icon { text-align: center; display: inline-block; padding-top: 2px; padding-left: 3px; padding-right: 3px; vertical-align: top; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .bigicon { height: 70px; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .smallicon { padding-top: 0px; height: 24px; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .icon:hover { background-color: #cde6f7; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .icon:active { background-color: #92C0E0; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .icon .label { line-height: 16px; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .smallicon { display: inline-block; padding-right: 5px; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .smallicon IMG { vertical-align: middle; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .smallicon .label { display: inline-block; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .icon .menu { position: relative; top: -1px; left: 1px; }
#OfficeUI .ribbon .tabs > ul li[role=tab] .contents .group .icongroup .icon .menu .menucontents { position: relative; z-index: 100; background-color: white; left: -4px; border-top: 1px solid #C6C6C6; border-bottom: 1px solid #C6C6C6; background-image: linear-gradient(#C6C6C6, #C6C6C6), linear-gradient(#C6C6C6, #C6C6C6); background-size:1px 100%;     background-position: 0 0, 100% 0; background-repeat: no-repeat; }

How can i do this ?

A: Use box-shadow. It is supported since IE9.


text:
Q: How can I get /bin/login to not timeout In my /etc/inittab I am using the following line:
ttyS0::respawn:/bin/login

This gives me a login prompt if I want to connect to the serial port. But it keeps echoing this:
[hostname] login:
Login timed out [hostname] login:
Login timed out [hostname] login:

How can I stop that and get it to not timeout?
So to clarify what came up in the comments:

*

*The login timeout is the regular expected behaviour

*I want to change that behaviour on my machine, so that login does not timeout anymore

*In other Linux distributions you can edit LOGIN_TIMEOUT in /etc/login.defs as explained in this answer: change tty login timeout - ArchLinux

*This does not work in Busybox

A: As you have spotted, the login program can be, and usually is, configured to time out if no input is received for a certain number of seconds.  There are various motivations for this behaviour, ranging from wanting to keep unused dial-up lines clear to the world wanting you to clean your screen.  There are, equally, reasons for not wanting it, as you have here.  Hanging up to clear the line is fairly meaningless if there's no modem, for one thing.
Unfortunately, login programs vary in this regard.  The login from (say) Debian's login package respects a /etc/login.defs configuration file.  I have LOGIN_TIMEOUT set to 0 in mine.  But other login programs have this unconfigurable and hardwired.  There is more than just the one login program in the world.  ☺
The login program in FreeBSD is — alas! — one such.  So too, is the login program that is built in to Busybox.  The former has a hardwired timeout of 300 seconds; the latter, a mere 60 seconds.
The Busybox code is a compile-time constant.  You'll have to actually modify the source to the program and re-build it in order to disable this behaviour.  Per commentary in the code of the FreeBSD login program that explains why it is a run-time variable not a compile-time constant, the FreeBSD authors expect you to vary this by patching the /usr/bin/login binary itself.
There are a few mitigating strategies.  One is — alas! — to keep getty in the loop.  FreeBSD's login is invoked by FreeBSD's getty, which has a to capability in /etc/gettydefs that is normally set to zero.  Busybox's getty similarly has a -t option.  Both mean that an idle, not logged in, serial terminal sits forever at the login: prompt displayed by getty, and the timeout in login is not begun.
I don't use getty on virtual terminals, myself.  So for FreeBSD I have a very simple login-prompt program that simply waits for the user to press return.  And on Linux I turn off the timeout with login.defs as mentioned.
For real terminals on serial lines, however, I still use getty.
Further reading

*

*https://unix.stackexchange.com/a/236959/5132

A: Apparently impossible without changing the source code.
Searching for login.defs or LOGIN_TIMEOUT yields indeed no relevant results and looking at loginutils/login.c it really seems like the value and the whole timer are hardcoded:

enum {
    TIMEOUT = 60,
    EMPTY_USERNAME_COUNT = 10,
    /* Some users found 32 chars limit to be too low: */
    USERNAME_SIZE = 64,
    TTYNAME_SIZE = 32,
};

[…]
static void alarm_handler(int sig UNUSED_PARAM)
{
    /* This is the escape hatch! Poor serial line users and the like
     * arrive here when their connection is broken.
     * We don't want to block here */
    ndelay_on(STDOUT_FILENO);
    /* Test for correct attr restoring:
     * run "getty 0 -" from a shell, enter bogus username, stop at
     * password prompt, let it time out. Without the tcsetattr below,
     * when you are back at shell prompt, echo will be still off.
     */
    tcsetattr_stdin_TCSANOW(&G.tty_attrs);
    printf("\r\nLogin timed out after %u seconds\r\n", TIMEOUT);
    fflush_all();
    /* unix API is brain damaged regarding O_NONBLOCK,
     * we should undo it, or else we can affect other processes */
    ndelay_off(STDOUT_FILENO);
    _exit(EXIT_SUCCESS);
}

[…]
int login_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int login_main(int argc UNUSED_PARAM, char **argv)
{

[…]
    /* We install timeout handler only _after_ we saved G.tty_attrs */
    signal(SIGALRM, alarm_handler);
    alarm(TIMEOUT);

Note how there the last part isn't indented, there seems to be no if around it, so it always runs. How you could probably do is to uncomment the last two lines and compile busybox anew if that is possible.
Alternative idea
From busybox' example inittab:
# <action>: Valid actions include: sysinit, respawn, askfirst, wait, once,
#                                  restart, ctrlaltdel, and shutdown.
#
#       Note: askfirst acts just like respawn, but before running the specified
#       process it displays the line "Please press Enter to activate this
#       console." and then waits for the user to press enter before starting
#       the specified process.

So you could simply change respawn to askfirst. This way /bin/login after the timeout expires would simply goes back to the Please press Enter… prompt instead of starting /bin/login right away again.


text:
Q: Preprocessing of rows of a DataFrame by numeric characters of specified size Let it be the following Python Panda DataFrame:
                NAME  NUM_OWNERS             NUM_DOCS       NUM_RESIDENTS
               Total   23900137              21028886         44571130.0
        Macael-04062     366607                324413           727945.0
               Spain    4283950               3642683          8464411.0
      Badalona-08911       5829                  6250            15480.0
      Vallecas-28031       5691                  5215            10358.0

I want to keep the rows containing a 5-digit number and modify the value of the NAME column by that number.
Resulting DataFrame:
                NAME  NUM_OWNERS             NUM_DOCS       NUM_RESIDENTS
               04062     366607                324413           727945.0
               08911       5829                  6250            15480.0
               28031       5691                  5215            10358.0

A: Let us try use contains filter then split assign the new value
out = df[df.NAME.str.contains('-')].assign(NAME = lambda x : x['NAME'].str.split('-').str[-1])
Out[83]:
    NAME  NUM_OWNERS  NUM_DOCS  NUM_RESIDENTS
1  04062      366607    324413       727945.0
3  08911        5829      6250        15480.0
4  28031        5691      5215        10358.0

A: df=df[df['name'].astype(str).str.contains(r'[\d]{5}')].assign(name = lambda x : x['name'].str.replace(r'[a-zA-Z]-?',''))

This logic check for 5 numbers if it is found then replaces characters


text:
Q: Bounding Fourier coefficients using translates of a function Having real trouble solving this problem, I know there's probably something obvious that I'm missing but it's driving me mad!

Exercise 1.3. Let $f \in C(\mathbb{R} / \mathbb{Z})$. For $y > 0$ let
  $$\omega(y) = \int_0^1 |f(t + y) - f(t)| dt.$$
  Show that the Fourier coefficients $c_k$ of $f$ satisfy
  $$|c_k| \le \frac 1 2 \omega\left(\frac 1 {2k}\right)$$
  for $k \ne 0$.


text:
Q: For what values of $a$ does $b\in\mathbb{N}$? I've the following function:
$$b=\frac{1}{2}-\frac{1}{r-2}+\sqrt{\frac{1}{4}-\frac{r-3}{(r-2)^2}+\frac{a(1+a)}{r-2}+\frac{a(a^2-1)}{3}}$$
I know that:

*

*$\text{a}\ge1$ and $a\in\mathbb{N}$;

*$\text{r}\ge3$ and $r\in\mathbb{N}$.

If I set the value of $r$, what does $a$ has to be in order to let $b\ge1$ and $b\in\mathbb{N}$? Are there restrictions on $a$ in order to let $b\ge1$ and $b\in\mathbb{N}$?

A: Let $s = r - 2$. Then $$b=\frac{1}{2}-\frac{1}{s}+\sqrt{\frac{1}{4}-\frac{s - 1}{s^2}+\frac{a(1+a)}{r-2}+\frac{a(a^2-1)}{3}}$$ $$b = \frac{1}{2}-\frac{1}{s}+\sqrt{\frac{1}{4}-\frac{1}{s}+\frac{1}{s^2}+\frac{a(1+a)}{s}+\frac{a(a^2-1)}{3}}$$ $$b = \frac{1}{2}-\frac{1}{s}+\sqrt{\left(\frac{1}{2}-\frac{1}{s}\right)^2+\frac{a(1+a)}{s}+\frac{a(a^2-1)}{3}}$$.
Let $t = \frac{1}{2}-\frac{1}{s}$ or $\frac{1}{s} = \frac{1}{2} - t$, such that $$b = t + \sqrt{t^2 - a(1 + a)t + \frac{a(1 + a)}{2} + \frac{a(1 + a)(a - 1)}{3}}$$
$$b = t + \sqrt{t^2 - a(1 + a)t + \frac{3a(1 + a) + 2(a - 1)a(1 + a)}{6}}$$
$$b = t + \sqrt{t^2 - 2t\frac{a(1 + a)}{2} + \frac{a(1 + a)(2a + 1)}{6}}$$
$$b = t + \sqrt{t^2 - 2t\sum_{i = 1}^{a} i + \sum_{i = 1}^{a} i^2}$$
As for all integers $a$, $$t < \sum_{i = 1}^{a} i$$
$$b = t + \sqrt{\left(-t + \sum_{i = 1}^{a} i\right)^2} = t - t + \sum_{i = 1}^{a} i = \sum_{i = 1}^{a} i = \frac{a(a + 1)}{2}$$
$b$ is only dependent upon $a$. If $a\in \mathbb{N}$ and $a \geq 1$, then $b\in \mathbb{N}$ and $b > 1$.


text:
Q: Weclapp PHP API { "error": "invalid data" } I am trying to use Weclapp API by using Curl and PHP. So far i have the following code
$ch = curl_init("https://xxx.weclapp.com/webapp/api/v1/contact");

$data = array(
  "'lastName' : 'Bar'",
  "'firstName' : 'Foo'");
$data_string = json_encode($data);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "AuthenticationToken: xxxxxx",
    'Content-Type: application/json')
);

$result = curl_exec($ch);
curl_close ($ch);

Unfortunately the result is { "error": "invalid data" }
If i use the following bash cmd it works:
curl -H "AuthenticationToken:xxxx" -H "Content-type: application/json" -X POST -d '{"lastName" : "Bar", "firstName" : "Foo"}' https://xxxx.weclapp.com/webapp/api/v1/contact

So where is the difference between my PHP Code and that bash CMD?
Thank you!

A: The error is here:
$data = array(
  "'lastName' : 'Bar'",
  "'firstName' : 'Foo'");

This is not a valid php array format. Change it to:
$data = array(
'lastName'  => 'Bar',
'firstName' => 'Foo'
);


text:
Q: Problem with accessing file in Firebase Storage with Firebase Cloud Functions, file returns "[object Object] " When trying to access an image in my home directory of Firebase storage with node.js functions, I'm getting [object Object] as a response. I guess I initialized the bucket incorrectly, but not sure where I'm going wrong.
That's the debug info in firebase functions:
ChildProcessError: `composite -compose Dst_Out [object Object] [object Object] /tmp/output_final2.png` failed with code 1

Here's my code:
const admin = require('firebase-admin');
admin.initializeApp();
const storage = admin.storage();

const os = require('os');
const path = require('path');
const spawn = require('child-process-promise').spawn;

exports.onFileChange= functions.storage.object().onFinalize(async object => {

    const bucket = storage.bucket('myID.appspot.com/');
    const contentType = object.contentType;
    const filePath = object.name;
    console.log('File change detected, function execution started');

    if (object.resourceState === 'not_exists') {
        console.log('We deleted a file, exit...');
        return;
    }

    if (path.basename(filePath).startsWith('changed-')) {
        console.log('We already changed that file!');
        return;
    }

    const destBucket = bucket;
    const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
    const border = bucket.file("border.png");
    const mask1 = bucket.file("mask1.png");
    const metadata = { contentType: contentType };
    return destBucket.file(filePath).download({
        destination: tmpFilePath
    }).then(() => {
        return spawn('composite', ['-compose', 'Dst_Out', mask1, border, tmpFilePath]);

    }).then(() => {
        return destBucket.upload(tmpFilePath, {
            destination: 'changed-' + path.basename(filePath),
            metadata: metadata
        })
    }); });```

A: If, with
const bucket = storage.bucket('myID.appspot.com/');

your goal is to initialize the default bucket, you should just do
const bucket = storage.bucket();

since you have declared storage  as admin.storage()

UPDATE (following your comment about const border = bucket.file("border.png");)
In addition, by looking at the code of a similar Cloud Function (from the official samples, using ImageMagick and spawn) it appears that you should not pass to the spawn() method  some File objects created through the file() method of the Cloud Storage Node.js Client API (i.e. const border = bucket.file("border.png");) but some files that you have previously saved to a temp directory.
Look at the following excerpt from the Cloud Function example referred to above. They define some temporary directory and file paths (using the path module), download the files to this directory and use them to call the spawn() method.
  //....
  const filePath = object.name;
  const contentType = object.contentType; // This is the image MIME type
  const fileDir = path.dirname(filePath);
  const fileName = path.basename(filePath);
  const thumbFilePath = path.normalize(path.join(fileDir, `${THUMB_PREFIX}${fileName}`));   // <---------
  const tempLocalFile = path.join(os.tmpdir(), filePath);    // <---------
  const tempLocalDir = path.dirname(tempLocalFile);     // <---------
  const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);     // <---------

  //....

  // Cloud Storage files.
  const bucket = admin.storage().bucket(object.bucket);
  const file = bucket.file(filePath);
  const thumbFile = bucket.file(thumbFilePath);
  const metadata = {
    contentType: contentType,
    // To enable Client-side caching you can set the Cache-Control headers here. Uncomment below.
    // 'Cache-Control': 'public,max-age=3600',
  };

  // Create the temp directory where the storage file will be downloaded.
  await mkdirp(tempLocalDir)   // <---------
  // Download file from bucket.
  await file.download({destination: tempLocalFile});    // <---------
  console.log('The file has been downloaded to', tempLocalFile);
  // Generate a thumbnail using ImageMagick.
  await spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile], {capture: ['stdout', 'stderr']});
  //.....

A: You can't pass Cloud Storage File type objects to spawn.  You need to pass strings that will be used to create the command line. This means you need to download those files locally to /tmp before you can work with them - ImageMagick doesn't know how to work file in Cloud Storage.


text:
Q: Design guidelines for secure Java EE web applications and Seam I attend in process of designing Java EE web application. It consist of:

*

*backend module (EJB 3.0)

*3 web modules (JSF)

Our application must be secure, so some colleagues claim that it must be splitted into two or more separate servers - backend in one server, webapps in other(s). In our case performance isn't a problem but this architecure demands using remote interfaces in EJB layer.
We are planning also to incorporate Seam to simplify development, but there is one drawback. So we miss out some really cool features of Seam e.g. - extended persistence context in SFSB
Does the use of an architecture with two or more separate servers/machines for each layer of Java EE web application is really a must in aspects of high security? I didn't find resources explaining pros and cons of this configuration. What are other project configuration options/security patterns that I should consider that facilitate using Seam? In others words should we stick with this architecture and add Seam as it is or apply another solution?
If it helps we can use Spring instead of EJB, but EJB is more preferable.

A: Here's a simple answer to you're question.... Is it more secure to have your data hop across 3 network connections (Web->Web server  is 1, Web server ->remote EJB is 2, and remote EJB->DB is 3), or 2 network connections?
The 2 network connection is inherently safer, since there is less exposure to hostile listening on the wire.
If you're attacker is able to read the memory Java uses to scrape the data from your web server, you have far far bigger problems that a separate server just won't help with.


text:
Q:  can only be used on a single element <transition name="fade" mode="out-in">
  <keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
  </keep-alive>
  <router-view v-if="!$route.meta.keepAlive"></router-view>
</transition>

when i use the transition with keep-alive & router-view, like above code, it will cause vue warn: <transition> can only be used on a single element.
I know what caused the error, but I want to know how can i use the transition with keep-alive & router-view correctly ?

A: You can wrap all those elements inside <template> like following:
<transition name="fade" mode="out-in">
  <template>
  <keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
  </keep-alive>
  <router-view v-if="!$route.meta.keepAlive"></router-view>
  </template>
</transition>


text:
Q: Which is the correct design pattern for navigation? I have an application which collects data from a user through a series of screens. On each screen there is a next button. On each screen there is a back button. However the screens aren't always sequential and linear. For example if payment has already been taken and the user is on the confirmation screen, when they click back they should be taken to an edit booking screen. I decided I need an object called a 'StateMarshaller' which would understand things about the domain, and would expose next(string action) back(string currentLocation) functions. Then it would return a 'State' object and tell the app where to go.
I just wondered if anyone can recommend a good pattern to aim for as we build up our test cases and refactor, I was looking at the command or the iterator but not totally feeling them. I think part of the problem is that I am used to strong typing but am now using a dynamic language.

A: It seems that you can benefit from using the State Pattern.

The idea will be that you will have a State for every screen. Each screen will do its own checking to determine where the user would go to next when hitting the appropriate buttons.


text:
Q: TRichEdit color problems ans:= RichEdit1.Text
for i:=1 to Length(ans) do
begin
   RichEdit1.SelStart :=  i-1;
   RichEdit1.SelLength:= 1;
   if ans[i] = correct[i] then
      RichEdit1.SelAttributes.Color := clRed
   else
      RichEdit1.SelAttributes.Color := clBlue;

If the letter in ans matches the letter in the same position as the letter in correct string, it is colored red otherwise, it is blue.
My problem is when I type again the whole RichEdit1 text is colored as the same as the first letter (if the first letter of RichEdit1 is blue then the whole text becomes blue).
By the way, this is not the the actual code I just simplified it because there are mutiple TRichEdits.
The TRichEdits are read-only and I assign the letters by something like RichEdit1.Text := RichEdit1.Text+Key;
(doing this because it's a multiple keyboard program and I need to separate user inputs)
Is this the correct behavior? How can I stop my color changes from overriding the default color?

update: Solved it... in a sloppy way (applying the default color whenever someone types), but I'm keeping this open in case someone comes up with a better solution.

A: As you already discovered, you have to reset the default color when you are done, eg:
ans := RichEdit1.Text;
for i := 1 to Length(ans) do
begin
  RichEdit1.SelStart := i-1;
  RichEdit1.SelLength := 1;
  if ans[i] = correct[i] then
    RichEdit1.SelAttributes.Color := clRed
  else
    RichEdit1.SelAttributes.Color := clBlue;
end;
RichEdit1.SelStart := RichEdit1.GetTextLen;
RichEdit1.SelLength := 0;
RichEdit1.SelAttributes.Color := RichEdit1.Font.Color;

There are more efficient ways to handle this than coloring one letter at a time, eg:
const
  colors: array[Boolean] of TColor = (clRed, clBlue);
var
  ans: string;
  start, len: Integer;
  cur_state: Boolean;

  procedure ColorRange(AStart, ALength: Integer; AColor: TColor);
  begin
    RichEdit1.SelStart := AStart;
    RichEdit1.SelLength := ALength;
    RichEdit1.SelAttributes.Color := AColor;
  end;

begin
  RichEdit1.Lines.BeginUpdate;
  try
    ans := RichEdit1.Text;
    start := 0;
    len := 0;
    cur_start := False;

    for i := 1 to Length(ans) do
    begin
      if (ans[i] = correct[i]) = cur_state then
        Inc(len)
      else begin
        if len > 0 then
          ColorRange(start, len, colors[cur_state]);
        start := i-1;
        len := 1;
        cur_state := not cur_state;
      end;
    end;
    if len > 0 then
      ColorRange(start, len, colors[cur_state]);
    ColorRange(RichEdit1.GetTextLen, 0, RichEdit1.Font.Color);
  finally
    RichEdit1.Lines.EndUpdate;
  end;
end;

Also, using the Text property to append a single Char is very inefficient.  Use the SelText property instead, eg:
RichEdit1.SelStart := RichEdit1.GetTextLen;
RichEdit1.SelLength := 0;
RichEdit1.SelAttributes.Color := ...; // optional
RichEdit1.SelText := Key;


text:
Q: Upcast a POJO to a JPA Entity Class Consider an @Entity class A, and another class B that is a POJO and extends A.
Is there any way to force an upcast of B to A (Without Reflection)?
I have a method that receive an object of class A and persist that object.
Passing a reference to an object B, will cause JPA to fail because it still consider the object as an instance of class B, and B is not annotated with @Entity.

A: Look into the @Inheritance annotation which allow inheritance relationships in object models, it can be setup in a number of ways (table per class, single table).
I have created video tutorials detailing these two strategies.  The first video covers the single table strategy and the other covers table per class.
Using the single table strategy you would annotate class A as follows:
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@Table(name="TABLE_NAME")
@DiscriminatorColumn(name="DISCRIMINATOR_COLUMN", discriminatorType=DiscriminatorType.STRING)
@Entity
public class A {}

Then annotate class B:
@Entity
@Table(name = "TABLE_NAME")
@DiscriminatorValue(value="VALUE_TO_DISTINGUISH_B")
public class B{}

One thing to note is that in this case B is made an entity, which I believe will be required in any scenario.

A: Probably you do not want/can not add the B entity to the persistence.xml file. If so, you could use Jackson like this:
1.Create B's JSON representation:
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(instanceB);

2.Create an A-instance from the JSON String, ignoring the unknown properties. Use this setting for that.


text:
Q: JavaFX KeyCode for percent (%) I want to detect when certain keys are pressed. I can't seem to find a KeyCode for the percent (%) sign. I have scoured the JavaFX 8 JavaDoc, and there is no Enum constant for PERCENTlike I would expect. Google was not helpful either. Is there something special about % that I don't know about?
@FXML
private void keyPressed(KeyEvent evt) {
    if (evt.getCode().isDigitKey() && !evt.isShiftDown()) {
        String number = evt.getText();
        numberAction(number);
    }
    if (evt.getCode().equals(KeyCode.DECIMAL)) {
        decimalAction();
    }
    if (evt.getCode().equals(KeyCode.PERCENT)) {
        percentAction();
    }
}

The Enum KeyCode.PERCENT does not exist.

A: Rather than using the keyPressed event, use the keyTyped event and use KeyEvent.getCharacter to get the result independent from keyboard layout:
@FXML
private void keyTyped(KeyEvent evt) {
    ...
    if ("%".equals(evt.getCharacter())) {
        percentAction();
    }
}

(You need to modify your fxml file of course.)

A: Did u try this?
YOUR_CONTROLLER.setOnKeyPressed(event ->{
        if((event.getCode() == KeyCode.DIGIT5) && event.isShiftDown())
            System.out.println("It's work");

});

And yes, u can't find KeyCode for this symbol because to write it you should to press more then 1 key (:
UPDATE:
You also can try this:
YOUR_CONTROLLER.setOnKeyPressed(event ->{
        if((event.getText().equals("%"))
             System.out.println("It's work");
});


text:
Q: How to get rid of the space/ enter of the input buffer in vim?     #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

    struct st{
        char n[100];        //Name
        char d[100];    //lastname

    } arr[4];

    void add(int *c, struct st l[])
    {
        int i                   =*c;
        int arrSize             =sizeof(arr) / sizeof(arr[0]);

        if((*c)<arrSize)
        {
            printf("Enter a name :\n");
            fgets(l[i].n, 100,stdin);
            printf("Enter lastname :\n");
            fgets(l[i].d,100,stdin);
            printf(" SUCCESS. Person was added\n");
        }
    }

    int main(void)
    {
        int ct                               =0;
        int *ctPointer=&ct;
        char response                          ;
        char endWhileloop                   =0;

        while(endWhileloop==0)
        {
            printf("To add a person to the list hit 'a'  \n");
            printf("to end program enter 'q'\n");
            fgets(&response,2,stdin);
            fseek(stdin,0,SEEK_END);

            switch(response)
            {
            case 'a':
                add(&ct, arr);
                break;

            case 'Q':
                endWhileloop=1;
                break;
            }
        }
        printf("\nbye.");
        return 0;
    }

I am trying to run my code in an older version of Vim(maybe an older version of C) for my school. Unfortunately I am not certain what version they are running
Surprisingly, my code works from home using vim and eclipse. but not from school
:I tried--->    fgets,  scanf("%[^\n]s",name) , scan( %c,&name), fseek(stdin,0,SEEK_END),flush(stdin);

But nothing has worked for me. I would like to know of some possible solutions.
When I run my code from school(not home), after I enter  'a' my code prints: Enter  name..(line in between) Enter last name.
Without taking an input.

A: Place this line instead of fseek
After getting the option you are not clearing the input buffer. so this is the reason for the not getting the first input.
After entering the first input new line will be there in input buffer. After processing first input then buffer will give the \n.
So place this line after getting the option. Declare the variable int c;
while((c=getchar()) != '\n' && c!= EOF );

Then make the case into like this,
case 'a': case 'A':
         ...
         ...
case 'q': case 'Q':
         ...
         ...

For getting the option you can use simply the scanf like this.
 scanf(" %c",&response);


text:
Q: Why Python gives TypeError when trying to call a function that read text? So I have a code to give a position of a character in a text file, using my function code that looks like this
#this is defined function
def return_position(arr, search_for=[''], base=1):
    dim = ()
    arr = [str(arr) for arr in arr]
    for search in search_for:
        for sr in range(len(arr)):
            s = arr[sr]
            for cr in range(len(s)):
                c = s[cr]
                if c == search:
                    dim += [(cr+base, sr+base)]
    return dim

In order to get the list of file, I used .readlines() because it's containing a list and will get the expected result, so I did
#open the file and read it as a list
textlist = open('testfile.text', 'r').readlines()
#textlist = ['Build a machine\n', 'For the next generation']

#print the return_position as a lines
print(''.join(return_position(textlist, search_for=['a', 'b'])))

In testfile.txt
Build a machine
For the next generation

Expected result
(1, 1)
(7, 1)
(10, 1)
(19, 2)

But why it's returning

TypeError can only concatenate tuple (not "list") to tuple

A: dim += [(cr+base, sr+base)]

This line won't work if dim is a tuple.
Turn this
dim = ()

into
dim = []

A tuple is an immutable ordered sequence. You can't append stuff to it. So use a list.
Ref: https://docs.python.org/3/library/stdtypes.html#typesseq

A: In your code dim is a tuple and tuples are immutable (i.e. cannot be modified after they're constructed).
You'll need to turn dim into a list to be able to append to it:
dim = []

A: As the other answers point out already a tuple is immutable and can not be changed.
That, however, does not answer your question because you are not trying to change a tuple, you are trying to concatenate a tuple and a list. Python does not know whether you would want a tuple or a list as a result therefore it raises the TypeError.
Concatenating two tuples works:
(1,2) + (3,4)  # result: (1, 2, 3, 4)

Concatenating two lists works as well:
[1,2] + [3,4]  # result: [1, 2, 3, 4]

Only the mixture of tuple and list causes the problem:
[1,2] + (3,4)  # raises TypeError

Therefore (as the other answers point out already) changing the data type of either operand would solve the problem.
I would suggest using a list and append to it instead of concatenate for efficiency reasons:
def return_position(arr, search_for=[''], base=1):
    dim = []  # changed this line
    arr = [str(arr) for arr in arr]
    for search in search_for:
        for sr in range(len(arr)):
            s = arr[sr]
            for cr in range(len(s)):
                c = s[cr]
                if c == search:
                    dim.append((cr+base, sr+base))  # changed this line
    return dim

textlist = ['Build a machine\n', 'For the next generation']

#print the return_position as a line
print(''.join(str(return_position(textlist, search_for=['a', 'b']))))  # added explicit conversion to str

Your print was raising a type error as well because all elements of the iterable passed to str.join must be strings. It does not perform an explicit conversion like the print function.

EDIT:
Please note that the algorithm, although it does not raise an error anymore, is missing one of your expected results because the algorithm is case sensitive.
If you want it to be case insensitive use str.casefold or str.lower, see this answer.
I would not use casefold to make sure that an "ß" is not replaced with a "ss", possibly turning the word into a different word with different pronounciation and different meaning like in the example in the linked answer (e.g. "busse" should not equal "buße").


text:
Q: After installing Ubuntu 22.04 on a Dell Latitude, the system produces a `grub rescue` error after restarting After installing Ubuntu 22.04 on a Dell Latitude, the system produces a grub rescue error after restarting:
error: file '/boot/grub/i386-pc/normal.mod' not found.
Entering rescue mode...
grub rescue>


text:
Q: MySQL Nested FOR EACH in a single trigger instead of multiple triggers Lets say I have 3 tables:

*

*meals

*courses

*ingredients

Where meals have several courses and courses have several ingredients.
Right now if I delete a meal, there is a trigger to delete every courses linked to that meal, and a second trigger that will delete every ingredients linked to each course.
Is there a way to do this in a single trigger with say a FOR EACH inside a FOR EACH? Surely there is a way, I'm just not good enough with triggers. I searched for "nested triggers", "nested for each", maybe I'm looking at the wrong thing.
Please don't tell me I should not delete a course after deleting a meal as it might be used for another meal, same with ingredients. This is only a simplified example of what I'm really doing.

A: I would suggest you to use a foreign_key CONSTRAINT with ON DELETE CASCADE for both tables, but it will depend if you are using InnoDB or MyIsam engine.
See an example here: How do I use on delete cascade in mysql?


text:
Q: Recursive calls between two functions I need to recursive check two objects and keys need to be sorted, so I created two functions.
buildObj - get all uniq keys from object, sort them and call buildObjKey on each key
buildObjKey - if one of values is object call buildObj for these. Other returns is example and real code is more complex.
So question: I define  buildObj before buildObjKey and call buildObjKey while its not defined yet. This is bad practice, but if I move definition of buildObj after buildObjKey I will call buildObj before It was defined... This is possible to do recursive calls between two functions without this trouble?
const _ = require('lodash')

const example1 = {
  key3: 'foo',
  key1: {
    key4: {
      key6: 'boo'
    },
  },
}

const example2 = {
  key3: 'too',
  key1: {
    key4: {
      key6: 'hoo'
    },
  },
}

const buildObj = (obj1, obj2) => {
 return  _.uniq([...Object.keys(obj1), ...Object.keys(obj2)])
 .sort()
 .map(key => buildObjKey(key, obj1, obj2))
}

const buildObjKey = (key, obj1, obj2) => {
  const val1 = obj1[key];
  const val2 = obj2[key];
  if(val1 && val2){
    if(_.isObject(val1) && _.isObject(val2)){
      return buildObj(val1, val2)
    }
    if(_.isObject(val1)){
      return buildObj(val1, val1)
    }
    if(_.isObject(val2)){
      return buildObj(val2, val2)
    }
    return val1
  }
  return val1 || val2
}

buildObj(example1, example2)

Execution example
[ [ [ 'boo' ] ], 'foo' ]
The real code is doing diff of two object, i don't write it here because of complexity. Here is simple example of structure.

A: misunderstanding

I define buildObj before buildObjKey and call buildObjKey while its not defined yet... This is bad practice, but if I move definition of buildObj after buildObjKey I will call buildObj before It was defined...

That's untrue. buildObj is a function and it is not called before you define buildObjKey. The fact that buildObj contains a reference to buildObjKey does not mean that it tries to immediately call it. To demonstrate this concretely, let's see a simplified example below.
Notice how isEven and isOdd do not produce output until one of the functions is actually called -

function isEven (n)
{ console.log("isEven", n)
  if (n == 0)
    return true
  else
    return isOdd(n - 1)   // <- calls isOdd
}

function isOdd (n)
{ console.log("isOdd", n)
  if (n == 0)
    return false
  else
    return isEven(n - 1)  // <- calls isEven
}

console.log("first line of output")

console.log("result", isOdd(3))

first line of output
isOdd 3
isEven 2
isOdd 1
isEven 0
result true

possible and powerful

This is possible to do recursive calls between two functions without this trouble?

This is a massively powerful technique known as mutual recursion. Mutual recursion is an excellent way to process recursive trees like the deeply-nested objects you have in your program. You have good intuition to process them this way. See this Q&A for a practical example and explanation.

related
Coincidentally I wrote a generic object diffing function in this Q&A. This demonstrates the strength of generic functions and reusable code. Using the test1 and test2 inputs from your question, we can calculate a precise diff without any modification to the original code -
const test1 = {
  "common": {
    "setting1": "Value 1",
    "setting2": 200,
    "setting3": true,
    "setting6": {
      "key": "value",
      "doge": {
        "wow": ""
      }
    }
  },
  "group1": {
    "baz": "bas",
    "foo": "bar",
    "nest": {
      "key": "value"
    }
  },
  "group2": {
    "abc": 12345,
    "deep": {
      "id": 45
    }
  }
}

const test2 = {
  "common": {
    "follow": false,
    "setting1": "Value 1",
    "setting3": null,
    "setting4": "blah blah",
    "setting5": {
      "key5": "value5"
    },
    "setting6": {
      "key": "value",
      "ops": "vops",
      "doge": {
        "wow": "so much"
      }
    }
  },
  "group1": {
    "foo": "bar",
    "baz": "bars",
    "nest": "str"
  },
  "group3": {
    "fee": 100500,
    "deep": {
      "id": {
        "number": 45
      }
    }
  }
}

console.log(diff(test1, test2))

Expand the snippet below to verify the results of diff in your own browser -

const isObject = x =>
  Object(x) === x

const isArray =
  Array.isArray

const mut = (o, [ k, v ]) =>
  (o[k] = v, o)

const diff1 = (left = {}, right = {}, rel = "left") =>
  Object
    .entries(left)
    .map
      ( ([ k, v ]) =>
          isObject(v) && isObject(right[k])
            ? [ k, diff1(v, right[k], rel) ]
        : right[k] !== v
            ? [ k, { [rel]: v } ]
        : [ k, {} ]
      )
    .filter
      ( ([ _, v ]) =>
          Object.keys(v).length !== 0
      )
    .reduce
      ( mut
      , isArray(left) && isArray(right) ? [] : {}
      )

const merge = (left = {}, right = {}) =>
  Object
    .entries(right)
    .map
      ( ([ k, v ]) =>
          isObject(v) && isObject(left [k])
            ? [ k, merge(left [k], v) ]
            : [ k, v ]
      )
    .reduce(mut, left)

const diff = (x = {}, y = {}, rx = "left", ry = "right") =>
  merge
    ( diff1(x, y, rx)
    , diff1(y, x, ry)
    )

const test1 = {
  "common": {
    "setting1": "Value 1",
    "setting2": 200,
    "setting3": true,
    "setting6": {
      "key": "value",
      "doge": {
        "wow": ""
      }
    }
  },
  "group1": {
    "baz": "bas",
    "foo": "bar",
    "nest": {
      "key": "value"
    }
  },
  "group2": {
    "abc": 12345,
    "deep": {
      "id": 45
    }
  }
}

const test2 = {
  "common": {
    "follow": false,
    "setting1": "Value 1",
    "setting3": null,
    "setting4": "blah blah",
    "setting5": {
      "key5": "value5"
    },
    "setting6": {
      "key": "value",
      "ops": "vops",
      "doge": {
        "wow": "so much"
      }
    }
  },
  "group1": {
    "foo": "bar",
    "baz": "bars",
    "nest": "str"
  },
  "group3": {
    "fee": 100500,
    "deep": {
      "id": {
        "number": 45
      }
    }
  }
}

console.log(diff(test1, test2))

{
  "common": {
    "setting2": {
      "left": 200
    },
    "setting3": {
      "left": true,
      "right": null
    },
    "setting6": {
      "doge": {
        "wow": {
          "left": "",
          "right": "so much"
        }
      },
      "ops": {
        "right": "vops"
      }
    },
    "follow": {
      "right": false
    },
    "setting4": {
      "right": "blah blah"
    },
    "setting5": {
      "right": {
        "key5": "value5"
      }
    }
  },
  "group1": {
    "baz": {
      "left": "bas",
      "right": "bars"
    },
    "nest": {
      "left": {
        "key": "value"
      },
      "right": "str"
    }
  },
  "group2": {
    "left": {
      "abc": 12345,
      "deep": {
        "id": 45
      }
    }
  },
  "group3": {
    "right": {
      "fee": 100500,
      "deep": {
        "id": {
          "number": 45
        }
      }
    }
  }
}

A: So there are a number of ways you can get around this problem & I'd honestly say that it may depend on what you consider important, i.e. it may depend on your style of coding & what preferences you have.

Hoisting
A simple enough technique to use, feel free to read up more on MDN, but in a nutshell hoisting is where you declare a variable towards the start of the file, then use it at some later point. But with functions specifically all you need to do to make use of this concept is define them as traditional functions. The idea being that when you define a function using the keyword function, the function essentially gets defined before other variables within the scope.
Here's a little example:

test();

function test() {
  console.log("Hello! :)")
}

Currying
Personally I'm a big fan of currying, I think it's pretty damn great to be honest with you, so much so that I've even written about how currying works great with React. If you're unsure of what currying is, it's essentially where you have one method that accepts one argument & returns a result or a function that also takes one argument & so on. If you're new to this concept, maybe read through the likes of this post, I won't go on & on about it because I know that other people will do a better job of explaining it than I will! But that aside, you could essentially achieve something like this:

const fn1 = (arg) => (callback) => {
  if (callback === undefined || callback === null) {
    console.log(arg);
  } else if (typeof callback === "function") {
    callback(arg);
  } else {
    throw new Error("The callback argument must be defined, fn1(arg)(callback).");
  }
}

const fn2 = (arg) => {
  if (arg === "test") {
    fn1(arg)(() => {
      console.log(`This is a ${arg}`);
    });
  } else {
    fn1(arg)();
  }
};

fn2(5);
fn2("test");

I mean you could even use a more tried & tested method & make use of a call-back function without the currying if you so desired, i.e. you could pass in an object that contains an array of keys. Then based on what keys are present in the provided arguments, you could very easily do it that way if you desired.

Class Syntax
This is another simple way, where all of your functions are defined within a class, you could essentially make the class static/stateless if you desire, I mean it's a bit of a context specific subject matter I think, not to mention your coding style(s) & ideas. But anyway, you don't have to worry about the order in which you write your code or anything like that, you can just do something straight up simple & easy to maintain, like so:

class Test {
  run () {
    this.print();
  }

  print() {
    console.log("I ran!");
  }
}

new Test().run();

I mean this approach would make a bit more sense if you're using TypeScript as you can define print as a private method, thus you'd only be able to call the run method outside of the class, but I'm confident that you get the idea?

Conclusion
I think that it depends on your ESLint configuration also, but more importantly your style of coding & what you or your team value the most, I think it's reasonable to state that there are many ways you could solve this problem, it's just a matter of deciding what suits your needs best.
If anyone has anything to add, feel free to edit my answer or add a comment, but I think this is one of those matters where there's no one correct answer? Feel free to disagree! P.S. As you've tagged this question with functional-programming, I'd suggest you make use of currying, I for one love it!


text:
Q: Find an "upper bound" for a given sequence. Let $a_1=5$ and let $$a_{n+1}=\frac{a_n^2}{a_n^2-4a_n+6}$$
Find the biggest integer $m$ not bigger than $a_{2018}$, that is $m\leq a_{2018}$.
My go:
Apparently the limit must satisfy $$l=\frac{l^2}{l^2-4l+6}\Leftrightarrow l=0\vee l=3\vee l=2$$ Computing first few terms i see that $a_n\to 3$ as $n\to\infty$. The sequence seems to converge to 3, so i tried to show that $\forall n\geq 2,a_n\leq3$ proceeding by induction, we find that $a_1=5,a_2=25/11\approx2,27\leq3$. Now let $a_n\leq 3\Rightarrow a_{n+1}=\frac{a_n^2}{a_n^2-4a_n+6}\leq\frac{9}{a_n^2-4a_n+6}$ but here I'm stuck again, no idea what to do with the denominator. Any help appreciated.

A: Write $b_n=a_n-3$.
Then
$$b_{n+1}=-3+b_{n+1}=\frac{-2a_n^2+12a_n-18}{a_n^2-4a_n+6}
=\frac{-2b_n^2}{b_n^2-2b_n+3}.$$
If $b_n$ is near $0$, then $b_{n+1}$ is negative, and approximately
$-2b_2^2/3$, and so is even nearer zero. Therefore if the sequence $(a_n)$
comes anywhere near $3$, it will converge rapidly to $3$, from below.
It does. Therefore the integer part of $a_{2018}$ will be $2$.

A: Suppose we compute the fixed points of the iteration $x\mapsto\frac{x^2}{x^2-4x+6}$; those fixed points are 0, 2 and 3. Now analyse the stability of those fixed points; a fixed point $x_0$ of $x\mapsto f(x)$ is stable (attractive) if $|f'(x_0)|<1$.
The numerator of the derivative of the given map is
$$2x(x^2-4x+6)-x^2(2x-4)$$
and for $x=2$ this is 8, but for $x=3$ this is 0. Furthermore, this expression is non-negative over $[2,3]$. Therefore, since $2<a_2<3$, the sequence monotonically converges to 3 from below after $a_1$, so $m=2$.

A: Alt. hint: quite obviously $\;a_n \ne 0\,$, then inverting both sides gives:
$$
\frac{1}{a_{n+1}}=1 - 4 \frac{1}{a_n} + 6 \frac{1}{a_n^2} \quad\iff\quad b_{n+1} = 6 b_n^2 - 4b_n + 1 \quad \style{font-family:inherit}{\text{where}} \;\; b_{n} = \frac{1}{a_n}
$$
Multiplying by $\,6\,$ then gives:
$$
6 b_{n+1} = 36 b_n^2 - 24b_n + 6 = (6 b_n - 2)^2+2 \quad\iff\quad c_{n+1} = c_n^2 \quad \style{font-family:inherit}{\text{where}} \;\; c_{n} = 6 b_n - 2
$$
Since $|c_1| = | 6 / a_1 - 2| = 4/5 \lt 1$ it follows that $\,c_n \to 0\,$ from above, so $\,a_n \to 3\,$ from below, then the same argument already made in other answers applies to show that $\,m = 2\,$.


text:
Q: Race condition when generating data with a GenericInputFormat I'm trying Flink and wrote the following example program:
object IFJob {

  @SerialVersionUID(1L)
  final class StringInputFormat extends GenericInputFormat[String] {

    val N = 100
    var i = 0L

    override def reachedEnd(): Boolean = this.synchronized {
      i >= N
    }

    override def nextRecord(ot: String): String = this.synchronized {
      i += 1
      return (i % 2) + ""
    }
  }

  def main(args: Array[String]) {

    val env = ExecutionEnvironment.getExecutionEnvironment
    val text: DataSet[String] = env.createInput(new StringInputFormat())

    val map = text.map {
      (_, 1)
    }
    //        map.print()
    val by = map.groupBy(0)
    val aggregate: AggregateDataSet[(String, Int)] = by.aggregate(Aggregations.SUM, 1)
    aggregate.print()
  }
}

I am creating a StringInputFormat once and read it in parallel (with a default parallelism = 8).
When I run the above program, the results vary between executions, i.e., they are not deterministic. Results are duplicated 1-8x times.
For example I get the following results:
// first run
(0,150)
(1,150)

// second run
(0,50)
(1,50)

// third run
(0,200)
(1,200)

The expected result would be
(0,400)
(1,400)

Because there the StringInputFormat should generate 8 times 50 "0" and "1" records.
I even added synchronization to the input format, but it didn't help.
What am I missing in the Flink computation model?

A: The behavior you observe is the result of how Flink assigns work to an InputFormat. This works as follows:

*

*On the master (JobManager), the createInputSplits() method is called which returns an array of InputSplit. An InputSplit is a chunk of data to read (or generate). The GenericInputFormat creates one InputSplit for each parallel task instance. In your case, it creates 8 InputSplit objects and each InputSplit should generate 50 "1" and 50 "0" records.

*The parallel instances of a DataSourceTask are started on the workers (TaskManagers). Each DataSourceTask has an own instance of the InputFormat.

*Once started, a DataSourceTask requests an InputSplit from the master and calls the open() method of its InputFormat with the InputSplit. When the InputFormat finished processing the InputSplit, the DataSourceTask requests a new from the master.

In your case, each InputSplit is very quickly processed. Hence, there is a race between DataSourceTasks requesting InputSplits for their InputFormats and some InputFormats processes more than one InputSplit. Since an InputFormat does not reset its internal state (i.e., set i = 0) when is opens a new InputSplit it will only generate data for the first InputSplit it processes.
You can fix this by adding this method to the StringInputFormat:
override def open(split: GenericInputSplit): Unit = {
  super.open(split)
  i = 0
}


text:
Q: Mockito do not throw exception I have this method my repository method throws RepositoryException and service method throws Service exception i am mocking the repository and throwing repository exception but it is not throw any exception can anybody please explain what is going on here.
public class IndActivityTest {
    static BigDecimal offset;
    static SecurityContext userContext;
    SearchFilter filter = new SearchFilter();
    SearchFilterToDB filterToDB = new SearchFilterToDB();
    static BigDecimal limit;
    static User user = null;
    @Mock
    static UserRepository repository;
    @Mock
    static SearchRepository searchRepository;

    @InjectMocks
    static SearchApiServiceImpl  searchApiImple;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    @BeforeClass
    public static void setUp(){
        user = new User();
        String scheme="https";
        userContext = new ServiceSecurityContext(user, scheme);
    }
    @Test
    public void getIndActivitiesPositiveResponse() throws RepositoryException,ServiceException{
        List<IndActivityDetailEntity> activityDetailEntities = new ArrayList<>();
        when(searchRepository.getIndActivitiesFromDB(filterToDB,user)).thenReturn(activityDetailEntities);
        Response response = searchApiImple.getIndActivities(filter, userContext);
        assertEquals(response.getStatus(), 200);
    }
    @Test(expected=ServiceException.class)
    public void getIndActivitiesNegetiveResponse() throws RepositoryException,ServiceException{
        when(searchRepository.getIndActivitiesFromDB(filterToDB,user)).thenThrow(new RepositoryException());
        searchApiImple.getIndActivities(filter, userContext);
    }
}

public Response getIndActivities(SearchFilter searchFilter, SecurityContext securityContext)
        throws ServiceException {
    List<Activity> activities = new ArrayList<>();
    try {
        logger.info("Entering getActivities");
        List<IndActivityDetailEntity> activityDetailEntities = new ArrayList<>();
        User user = (User) securityContext.getUserPrincipal();
        SearchFilterToDB searchFilterToDB = newFilterToDB(searchFilter, user);
        activityDetailEntities = searchRepository.getIndActivitiesFromDB(searchFilterToDB, user);
        if (!activityDetailEntities.isEmpty())
            activities = SearchUtil.convertIndActivityToIndActivityDTO(activityDetailEntities, searchRepository);
        logger.info(" Exiting getActivities");
    } catch(Exception e){
        handleException(e);
    }
    return Response.status(200).entity(new InlineResponse200().data(activities)).build();
}

private void handleException(Exception e) throws ServiceException{
    logger.error("Service Exception "+e);
    if( e instanceof ServiceException)
        throw (ServiceException)e;
    if( e instanceof RepositoryException ){
        RepositoryException re = (RepositoryException)e;
        throw new ServiceException(re.getErrorCode(),re,re.getMessage());
    }else{
        throw new ServiceException(e.getMessage(), e,ServiceConstant.UNKNOWN);
    }
}

A: The issue is at the line new FilterToDB(searchFilter, user) in your getIndActivities() method of the service, because searchFilterToDB objects are different, the method call is NOT actually mocked.
So, to solve the problem, you need to extract new FilterToDB object creation to a separate class & mock the method call to that class.


text:
Q: how to back/forward user 's history by clicking the browser back/forward button in angularjs I have a angularjs page, it contains two part, the first part on the left is a navigation list with a list of news categories, the central content is the news list. so when people click one news category on the left, the central content will load the news list in ajax.
what I want to do now is,  when the user click the back or forward button on the browser, the browser could back / forward user to the last navigation link he clicked.
how can I  disable the browser back/ forward button 's default behavior and implement this in angular.js

A: Here is an example how to use $location
http://johan.driessen.se/posts/Manipulating-history-with-the-HTML5-History-API-and-AngularJS


text:
Q: How can I filter a column by multiples of a number? I have a Strava dataset with 5 columns: edge_id, year, day, hour, commute_count.
The day field is a numeric field which ranges between 1 and 365. However, because the count happens hourly and per edge (street), days are repeated (see image for clarity).
I  need to remove every record for saturday - sundays from the table. I thought I could filter out the multiples of 6 and 7 from the "day" column but I can't figure out how. Any help will be appreciated.

A: you could use the subset function and a condition based on modulo:
day %% 6 equals 0 if day is a multiple of 6.
Therefore, the condition day%%6 !=0 keep only values that are not multiple of 6.
new.df = subset(df, day%%6 !=0  & day%%7 != 0)


text:
Q: Debugging mxd crawler error? I found some conversation about listing the source paths for multiple mxd files and used the script provided at Crawling directory and listing all datasources using ArcPy?.
It worked great on one folder but on the other two folders I get this error:

Traceback (most recent call last):   File
  "\de1-s07\Q-Drive\Jobs\Missouri\I_70_PEL_StLouis\AECOM\Map_Docs_MxdCrawler\mxdcrawler.py",
  line 33, in
      main(folderPath, output)   File "\de1-s07\Q-Drive\Jobs\Missouri\I_70_PEL_StLouis\AECOM\Map_Docs_MxdCrawler\mxdcrawler.py",
  line 9, in main
      w.writerows(rows)   File "\de1-s07\Q-Drive\Jobs\Missouri\I_70_PEL_StLouis\AECOM\Map_Docs_MxdCrawler\mxdcrawler.py",
  line 18, in crawlmxds
      dataframes = arcpy.mapping.ListDataFrames(mxd)   File "C:\Program Files (x86)\ArcGIS\Desktop10.3\ArcPy\arcpy\utils.py", line 182, in fn_
      return fn(*args, **kw)   File "C:\Program Files (x86)\ArcGIS\Desktop10.3\ArcPy\arcpy\mapping.py", line 1496, in
  ListDataFrames
      result = mixins.MapDocumentMixin(map_document).listDataFrames(wildcard)   File
  "C:\Program Files
  (x86)\ArcGIS\Desktop10.3\ArcPy\arcpy\arcobjects\mixins.py", line 730,
  in listDataFrames

Each time I run the script it fails at a different point. One time it only read 2 files and this time it read 9 files. The python script is:
import arcpy, os, csv

def main(folder, outputfile):
    with open(outputfile, "wb") as f:
        w = csv.writer(f)
        header = ("Map Document", "MXD Path", "DataFrame Name", "DataFrame Description", "Layer name", "Layer Datasource")
        w.writerow(header)
        rows = crawlmxds(folder)
        w.writerows(rows)

def crawlmxds(folder):
    for root, dirs, files in os.walk(folder):
        for f in files:
            if f.lower().endswith(".mxd"):
                mxdName = os.path.splitext(f)[0]
                mxdPath = os.path.join(root, f)
                mxd = arcpy.mapping.MapDocument(mxdPath)
                dataframes = arcpy.mapping.ListDataFrames(mxd)
                for df in dataframes:
                    dfDesc = df.description if df.description != "" else "None"
                    layers = arcpy.mapping.ListLayers(mxd, "", df)
                    for lyr in layers:
                        lyrName = lyr.name
                        lyrDatasource = lyr.dataSource if lyr.supports("dataSource") else "N/A"
                        seq = (mxdName, mxdPath, df.name, dfDesc, lyrName, lyrDatasource);
                        yield seq
                print "running"
                del mxd

if __name__ == "__main__":
    folderPath = r"\\de1-s07\Q-Drive\Jobs\Missouri\I_70_PEL_StLouis\AECOM\Map_Docs\Restart" # or arcpy.GetParameterAsText(0)
    output = r"\\de1-s07\Q-Drive\Jobs\Missouri\I_70_PEL_StLouis\AECOM\Map_Docs\_mxdcrawler\mxdcrawler_Restart.csv" # or arcpy.GetParameterAsText(1)
    main(folderPath, output)

print "done"

What do I need to fix to get this to work?
I am using python 2.7.8 through ArcGIS 10.3 GUI.


text:
Q: Set SearchView width and hint color in XML I have added the SearchView functionality to the toolbar and I wanted to make it full width when expanded and also change the hint text color to white instead of black.
Finally I've been able to do it programmatically with this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setMaxWidth(4000);
    ((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text)).setHintTextColor(getResources().getColor(R.color.md_text_white));
    searchView.setIconifiedByDefault(false);
    return true;
}

Is there any way to achieve this through styling in xml or some other configuration? I prefer to have the functionality and styling independent.
I have tried with searchViewStyle and creating a custom style for SearchView but hasn't worked:
<style name="AppTheme" parent="Base.AppTheme">
    <item name="searchViewStyle">@style/SearchViewTheme</item>
</style>
<style name="SearchViewTheme" parent="Widget.AppCompat.Light.SearchView">
    <item name="android:maxWidth">10000dp</item>
</style>

This is my menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:orderInCategory="100"
        android:icon="@drawable/ic_action_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

A: Try this in the menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:title="@string/action_search"
        android:orderInCategory="100"
        android:icon="@drawable/ic_action_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionLayout="@layout/searchview_layout"
    />

</menu>

With this layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SearchView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/search_view_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/SearchViewTheme"/>

And this style:
<style name="SearchViewTheme" parent="Widget.AppCompat.Light.SearchView">
    <item name="android:maxWidth">10000dp</item>
    <item name="android:textColorHint">@android:color/white</item>
</style>


text:
Q: How many squares are in the chessboard? How to determine the numbers of squares in not only in chess board but also in a square figure like the chess. I need a general formula.
WHat I guess Is, I have 9 lines in both side  so I can have $9C2 \times 9C 2$?

A: Consider the following method for an $n\times n$ chessboard:

*

*Choose $1\times 1$ squares: there are obviously $n^2$ such squares.

*Choose $2\times 2$ squares: there are $(n - 1)^2$ such squares, because you have one less degree of freedom on each axis.

*Choose $3\times 3$ squares: there are $(n - 2)^2$ such squares, because you have two less degrees of freedom on each axis.

*And so on.

These are all mutually exclusive so you do not overcount any squares, and so the result is $$n^2 + (n-1)^2 + \cdots + 2^2 + 1^2,$$ which has a well known formula. For your case, it's 204.

A: What you look for is probably $\sum_{k=1}^nk^2=\frac{n(n+1)(2n+1)}{6}$, so for $n=8$ it's $204$.

A: You are correct that for an $n \times n$ chessboard you can choose the two rows in ${n+1\choose 2}$ ways, but then the vertical rows must be chosen to be the correct distance apart.  An easier way to get the count is to note that for an $i \times i$ square, you can set the left side in $n-i+1$ places and the top side in $n-i+1$ places.  So the total is $\sum_{i=1}^n (9-i)^2=\sum_{i=1}^n i^2=\frac {n\cdot (n+1) \cdot (2n+1)}6$, which for $n=8$ is $204$

A: No. It's harder I think. If you do it the way you said, I mean you choose $2$ lines from $9$ lines to form a row and a column then you're counting the number of rectangles in a chess board.
How about $1^2+2^2+\cdots+8^2$?

A: General agreement I see! However, if I regard the chessboard as a 9x9 grid of lines, do the points (1,0), (9,1), (8,9) and (0,8) not form a square?? And indeed the points (1,0), (2,1),(1,2),(0,1),....
Counting like this there are 540 squares (n different squares using the outer lines of each nxn subgrid - each such subgrid can be positioned in (9-n)x(9-n) locations).
To the person who deleted this answer: the answer I have provided is 540, or
1x8x8 + 2x7x7 + 3x6x6 + 4x5x5 + 5x4x4 + 6x3x3 + 7x2x2 + 8x1x1.
As a further clarification - the question is "How many squares are in a chessboard". The additional, diagonally oriented squares I have mentioned, which none of the previous answers refer to, are certainly "in" the chessboard.
I am happy for my answer to be debated mathematically, but not binned by a bureaucrat!

A: $$\sum_{i=0}^n (n-i)*(i+1)^2 = \frac{n(n+1)^2(n+2)}{12}$$
The formula.


text:
Q: Unlimited value for a select in form Symfony2 I want a select in my form, but the value of the select are dynamic (with ajax)
My entity:
 /**
 * @ORM\Column(type="string", nullable=true )
 * @Assert\NotBlank()
 */
private $city;

My form:
$builder->add('city', 'choice',array('empty_value' => 'choice city', 'choices' => array() ));

But, I have:

This value is not valid..

Because the city are not in the empty array!

A: Since the city field is a simple string and is not related to a table, simply:

*

*Render the field as a simple input text;

*Attach to the input field the Javascript for city-autocompletion through Ajax to fill the input

*Then you are ready to submit

or:

*

*Render the field as text.

*Hide it in the template

*Attach a select through javascript in place of the text-input

*Use that select to render the list of cities

*On submit get the value from the select and put it as value of the input field.

This approach can be used also to set value for visual widgets, like a star rating.

A: An other solution with extend form theme:
In my form:
$builder->add('city', 'text',array('data' => 'choice city'));

And in my twig template
{% form_theme form _self %}
{% block _template_defaultbundle_membertype_city_widget %}
   <select {{ block('widget_attributes') }} ><option>{{ value }}</option></select>
{% endblock %}

with "template_defaultbundle_membertype_city" is the id of the input


text:
Q: How to use Regex to change groups in string I am attempting to use C# Regex.Replace to automate a manual job of formatting strings in one structure into another. While I am able to identify and replace one sub-string, I have been unable to find examples of how to match and replace the rest of the string. I was wondering if there is a simple way to do this.
Say I have this search pattern that identifies the string to be transformed:
const string inputPattern1 = "SOC.\\d.\\d.\\d.PO \\d";

Is it possible to set up replacement rules for each of the parameters?
Here is a visual example of what I mean. Notice in the example that the string has a structure, so it's not a simple case of "replace any instance of X with Y".

This is what I have so far, using a C# console program to work out the methodology.
private static void Main()
{
    const string input1 = "SOC.6.1.1.PO 8";
    const string inputPattern1 = "SOC.";
    const string replacement1A = "SSHS-S0";

    // output should be: "SS06-S1C1-08"

    var output1 = Regex.Replace(input1, inputPattern1, replacement1A);

    Console.WriteLine("Input1: {0}",input1);
    Console.WriteLine("Output1: {0}", output1);
}

The result is:
Input1: SOC.6.1.1.PO 8
Output1: SSHS-S06.1.1.PO 8

A: Use capturing group numbers in your replacement string:
var res = Regex.Replace(
    "SOC.6.1.1.PO 8"
,  @"SOC\.(\d)\.(\d)\.(\d)\.PO (\d)"
,   "SS0$1-S$2C$3-0$4"
);

$1 through $4 represent the content of the input string matched by parenthesized groups.
Demo.


text:
Q: Cómo puedo poner una imagen en html que ocupe todo el ancho de la pantalla y sea responsive Estoy poniendo una imagen en mi web y quiero que me vaya de izquierda a derecha y ocupe toda la zona de la pantalla. Como se ve en la imagen solo aparece en un trozo y no sé que propiedades de css tengo que poner para que se ajuste de izquierda a derecha o si tengo que alargar los pixeles con algún programa. La imagen va justo debajo del header y encima del formulario. Adjunto código aunque la imagen no se verá. También tiene que ser responsive y se adapte a cualquier tipo de pantalla. Si me pudierais asesorar un poco. Muchas gracias.

REGISTRARME

Regístrate para disfrutar de múltiples funcionalidades

        <form action="../public/forms/registro.php" method="post">

NOMBRE

<input type="text" id="nombre" name="nombre" maxlength="30" size="29" required />

APELLIDOS

<input type="text" id="apellidos" name="apellidos" maxlength="30" required />

FECHA DE NACIMIENTO

<input type="date" id="fecha_nacimiento" name="fecha_nacimiento" required />

TELÉFONO

<input type="tel" id="telefono" name="telefono" required placeholder="XXXXXXXXX" pattern="[0-9]{9}" />

CIUDAD

<input type="text" id="ciudad" name="ciudad" maxlength="50" required />

EMAIL

<input type="text" id="email" name="email" placeholder="usuario@direccion.com" required maxlength="30" pattern="[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" />

                    La contraseña debe contener al menos un número, una mayúscula, una minúscula y un mínimo de 8 caracteres.

CONTRASEÑA

                <button id="mostrar_contrasenaregistro" type="button" onclick="mostrarContrasenaregistro()">  </button>

<input type="password" id="contrasena" name="contrasena" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" maxlength="40" required />

<input type="submit" name="usub" value="¡Quiero registrarme!" />

        </form>
        <?php include(__DIR__.'/../lib/inc/footer.php'); ?>

A: con el atributo width: 100%; el objeto se ensancha al tamaño del padre, añadeselo a la imagen


text:
Q: Alternate/better way of prepending an element using Scala I have a collection of lines, like in this snippet:
  def insertBeforeLine(text:String,whichLine:String,what:String) = {
    val lines = text.lines
    lines.foldLeft(ListBuffer[String]())((acumulator,element) => {
       acumulator ++ { if(element == whichLine) Array(what,element) else Array(element) }
    }).mkString("\n")
  }

I am trying to prepend something before every line that's equal to whichLine. Is there a better/cleaner way? For example if my input is:
line1
line2
line4

and I call my function like insertBeforeLine(input,"line4","line3") it will produce:
line1
line2
line3
line4

A: If you really have a string of lines (and you can include the end-of-line character, and it's consistent), you can use replace from java.lang.String:
text.replace(which,what+which)

but if you want something more general, something like
lines.flatMap(l => if (l==which) Seq(what,l) else Seq(l))

is a compact and clear way to express it (at least to those who know how flatMap works).
If you want something maximally efficient, then it's a long ugly answer with lots of while loops and probably some byte array intermediates.


text:
Q: splitting a text file based on number of words in bash I know to extract a subset of lines from a file I can do:
sed -n 2208202,2218201p file >>new

Is there a way in bash to extract a subset of a file (preserving the exact order) based on words? For example to extract the top 10k words of a file, or words from 10000 to 20000?

A: With this as the test file:
$ cat file
one two
three four five
six seven
eight nine
ten eleven twelve
thirteen
fourteen

Using GNU awk (gawk), let's select words 4 through 10:
$ awk -v RS='[[:space:]]+' '4<=NR && NR<=10{ printf "%s%s",$0,RT } END{print""}' file
four five
six seven
eight nine
ten

Note that this preserves the white space and line breaks of the the original file.
How it works

*

*-v RS='[[:space:]]+'
This sets awk's record separator to any combination of white space.

*4<=NR && NR<=10{ printf "%s%s",$0,RT }
For records 4 through 10, this prints the record with whatever whitespace followed it in the input file.  RT is not POSIX.

*END{print""}
This prints a final newline which is needed if the final word was not the last on a line.

A: Assuming that:

*

*you define word as any run of non-whitespace characters

*you use GNU Awk or Mawk

try:
awk -v from=10000 -v to=20000 -v RS='[[:space:]]+' 'NR < from {next} NR > to {exit} 1' file

- Simply omit -v from=... to start with the first word.
- This solution prints each word on its own line on output; if, by contrast, you want to preserve the original whitespace between words, see John1024's helpful answer.

*

*RS='[[:space:]]+' defines the input-record separator (RS) as any run of whitespace, which effectively makes each run of non-whitespace characters its own record.

*

*It it is the use of a multi-character RS value that makes this solution non-POSIX-compliant; BSD awk, as also used on OS X, stays close to the POSIX spec. and therefore doesn't support such an RS value.

*NR < from {next} skips input records as long as their 1-based record index NR is below the start index of the range.

*NR > to {exit} exits altogether once the record index exceeds the end index of the range. This can be an important optimization with large input files.

*1, a common shorthand for { print }, prints each word on its own line, because  print prints each input record followed by the value of ORS, the output-record separator, which defaults to \n.

*Caveat: A run of whitespace preceding the first word is reported as an empty word (record).

A: awk to the rescue!
this should work with other awks too
$ awk -v n=15 'sum<n && p{print p}
                         {p=$0; sum+=NF}
                   sum>=n{exit}
                      END{for(i=1;i<=n-sum+NF;i++) printf "%s ", $i;
                          print ""}' file.txt

this is the first n words script. Range can be implemented similarly.


text:
Q: can not access control inside asp.net updatepanel I use this official sample from Microsoft:
When I try to access the MyLabel from codebehind in the click event the MyLabel is NULL.
Why this?
<asp:ScriptManager ID="PageScriptManager" runat="server" />
<asp:Button ID="MyButton" Text="Click Me" runat="server" onClick="MyButton_Clicked" />
<asp:UpdatePanel ID="MyUpdatePanel" runat="server">
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="MyButton" EventName="Click" />
</Triggers>
    <ContentTemplate>
    <asp:Label ID="MyLabel" Text="OldText" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>

private void MyButton_Clicked(object sender, EventArgs e)
 {
  MyLabel.Text = "NewText!";
 }

UPDATE This code does not work Why? The MyLabel is always NULL on server side ??
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

  <asp:ScriptManager runat="server" ID="xx">
  </asp:ScriptManager>

 <asp:ImageButton OnClick="OnClickRefreshButton" ID="RefreshImageButton" runat="server" Width="100px" />
<asp:UpdatePanel ID="MyUpdatePanel" runat="server">
    <Triggers>
         <asp:AsyncPostBackTrigger ControlID="RefreshImageButton" EventName="Click" />
    </Triggers>
    <asp:ContentTemplate>
      <asp:Label ID="MyLabel" Text="OldText" runat="server" />
    </asp:ContentTemplate>
</asp:UpdatePanel>
</asp:Content>

protected void OnClickRefreshButton(Object sender, ImageClickEventArgs e)
        {

            MyLabel.Text = "NewText!";
        }

A: Try to change the function to protected and not private, it worked for me. hope it solved your problem

A: You can adjust  UpdateMode="Conditional" to your Updatepanel
LInk : http://msdn.microsoft.com/fr-fr/library/system.web.ui.updatepanel.updatemode.aspx


text:
Q: Convert passwords from htpasswd to htdigest On a Server I like to switch from Apache auth_basic to auth_digest for security reasons.
Is there a way to convert the old .htpasswd file to the htdigest format?

A: The htpasswd program usually creates encrypted passwords. If you used MD5, SHA1, bcrypt or crypt for encrypting passwords, you almost can't recover the original data. These cryptographic functions are called one-way: you can create a hash but you can't restore the original value. It's the main purpose of the one-way functions.
As I know, in the HTTP Digest algorithm, RFC2617, introduced so called realm, some [unique] string for a challenge. This information is used for hashing passwords. It's not possible to reuse a file with passwords because, for the Basic Authentication, these passwords were hashed without the realm information.
Try to ask your users to change their passwords after the first authentication.


text:
Q: The meaning of 'quirk aside' I read a sentence 'Some personality quirks aside,' in the following context

When I was a kid, our neighbors had two twin cats. They looked seem- ingly identical—the same charcoal fur and the same piercing green eyes.
Some personality **quirks aside**, you couldn't tell them apart just from looking at them.But of course, they were two different cats, two separate beings, even though they looked exactly the same.

Psersonality is a noun,so 'quirk' should be a verb.
In Oxford Dictionaries, it reads

1.Noun
  A peculiar aspect of a person's character or behaviour.
  2.Verb
  (with reference to a person's mouth or eyebrow) move or twist suddenly, especially to express surprise or amusement.

From the definition, a verb doesn't make sense. If a noun, I'm unable to parse its grammar and catch its meaning.

A:
Psersonality is a noun,so 'quirk' should be a verb.

Not that simple, unfortunately.  Commas do not necessarily end clauses in sentences.

Some personality quirks aside, you couldn't tell them apart just from looking at them.

The subject of this sentence is you and the verb is could not tell.
I think what is happening is that some personality quirks aside is an adverbial phrase - things that answer the question or provide more information toward the question how? are generally adverbs and modify/qualify the verb in the sentence.