text:
Q: Avoid calculating startIndex and endIndex when creating a document using Google Docs API I have proven to myself that I can insert text into a Google Docs document using this code:
function appendToDocument() {
    let offset = 12;
    let updateObject = {
        documentId: 'xxxxxxx',
        resource: {
            requests: [{
                "insertText": {
                    "text": "John Doe",
                    "location": {
                        "index": offset,
                    },
                },
            }],
        },
    };
    gapi.client.docs.documents.batchUpdate(updateObject).then(function(response) {
        appendPre('response =  ' + JSON.stringify(response));
    }, function(response) {
        appendPre('Error: ' + response.result.error.message);
    });
}

My next step is to create an entire, complex document using the api.  I am stunned by what appears to be the fact that I need to maintain locations into the documents, like this
new Location().setIndex(25)

I am informing myself of that opinion by reading this https://developers.google.com/docs/api/how-tos/move-text
The document I am trying to create is very dynamic and very complex, and handing the coding challenge to keeping track of index values to the api user, rather than the api designer, seems odd.
Is there an approach, or a higher level api, that allows me construct a document without this kind of house keeping?

A: Unfortunately, the short answer is no, there's no API that lets you bypass the index-tracking required of the base Google Docs API - at least when it comes to building tables.
I recently had to tackle this issue myself - a combination of template updating and document construction - and I basically ended up writing an intermediate API with helper functions to search for and insert by character indices.
For example, one trick I've been using for table creation is to first create a table of a specified size at a given index, and put some text in the first cell.  Then I can search the document object for the tableCells element that contains that text, and work back from there to get the table start index.
Another trick is that if you know how many specific kinds of objects (like tables) you have in your document, you can parse through the full document object and keep track of table counts, and stop when you get to the one you want to update/delete (you can use this approach for creating too but the target text approach is easier, I find).
From there with some JSON parsing and trial-and-error, you can figure out the start index of each cell in a table, and write functions to programmatically find and create/replace/delete.  If there's an easier way to do all this, I haven't found it.  There is one Github repo with a Google Docs API wrapper specifically for tables, and it does appear to be active, although I found it after I wrote everything on my own and I haven't used it.)
Here's a bit of code to get you started:
def get_target_table(doc, target_txt):
    """ Given a target string to be matched in the upper left column of a table
        of a Google Docs JSON object, return JSON representing that table. """
    body = doc["body"]["content"]
    for element in body:
        el_type = list(element.keys())[-1]
        if el_type == "table":
            header_txt = get_header_cell_text(element['table']).lower().strip()
            if target_txt.lower() in header_txt:
                return element
    return None

def get_header_cell_text(table):
    """ Given a table element in Google Docs API JSON, find the text of
        the first cell in the first row, which should be a column header. """
    return table['tableRows'][0]\
        ['tableCells'][0]\
        ['content'][0]\
        ['paragraph']['elements'][0]\
        ['textRun']['content']

Assuming you've already created a table with the target text in it: now, start by pulling the document JSON object from the API, and then use get_target_table() to find the chunk of JSON related to the table.
doc = build("docs", "v1", credentials=creds).documents().get(documentId=doc_id).execute()
table = get_target_table(doc, "my target")

From there you'll see the nested tableRows and tableCells objects, and the content inside each cell has a startIndex.  Construct a matrix of table cell start indices, and then, for populating them, work backwards from the bottom right cell to the upper left, to avoid displacing your stored indices (as suggested in the docs and in one of the comments).
It's definitely a bit of a slog.  And styling table cells is a whole 'nother beast, which is a dizzying maze of JSON options.  The interactive JSON constructor tool on the Docs API site is useful to get the syntax write.
Hope this helps, good luck!

A: The answer I arrived at: You can create Docs without using their JSON schema.
https://developers.google.com/drive/api/v3/manage-uploads#node.js_1
So, create the document in your format of choice (HTML, DocX, MD (you'd use pandoc to convert MD to another format)), and then upload that.


text:
Q: How to display a Route by default with React-Router I'm new to React and I would like to develop a Single Page Application, so I'm using react-router four routing.
Below the main.js, where I specify the routes
import React from 'react';
import {Router,Route} from 'react-router';
import {App} from './components/App';
import {Login} from './components/Login';
import {Home} from './components/Home';
import { history } from 'react-router';

React.render(
<Router history={history}>
    <Route path="/" component={App}>
        <Route path="home" component={Home}/>
        <Route path="login" component={Login}/>

    </Route>
</Router>,
document.getElementById('main')
);

And then the App.js, as you can see I want to have a fixed Header and Footer, and then to have the content of the page change dinamically depending on the route.
import React from 'react';
import {Header} from './Header';
import {Footer} from './Footer';

export class App extends React.Component {

render() {
    console.log(this.props.children);
    return (

            {this.props.children}

);
}

}

With this code, once the application is loaded with the path ("/"), I need to click on the link Home to display the home content, but I would like to be displayed by default, once the application is first loaded.
How can I achieve that?
Thank you!!

A: I think you probably want to use an IndexRoute as described here in the React Router documentation.
Your router would then look something like this:
<Router history={history}>
    <Route path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>

A: It's usefull when nested IndexRoute.

    <Redirect from="/" to="home"/>
    <Route path="/" component={App}>
        <Route path="home" component={Home}>
            <IndexRoute component={IndexView} />
            <Route path="other" component={OtherView}></Route>
        </Route>
        <Route path="about" component={About}></Route>

    </Route>

A: In later versions of react-router, you can use ÌndexRedirect. This way you're not obligated to put your home screen under the route "/". Users navigating to "/" will simply be redirected to "/home".
<Router history={history}>
    <Route path="/" component={App}>
        <IndexRedirect to="home"/>
        <Route path="home" component={Home}/>
        <Route path="login" component={Login}/>
    </Route>
</Router>

A: Things have changed a lot in React v6. I think you can now achieve what you want with the following  specification:
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} >
        <Route path="/home" element={<Home/>} />
        <Route path="/login" element={<Login />} />
        <Route path="/" element={<Home />} />
      </Route>
    </Routes>
  </BrowserRouter>

If the specification of the App component declares it as an Outlet, the Routes code above will always render it, irrespective of whether the path is "/", "/home" or "/login". Within the nested group, "/home" or "/login" paths will then add Home or Login displays as you would expect, but a "/" path will also add Home as a "default".
Alternatively, but perhaps less comprehensibly, you can use the "index" keyword to render a default Home component within the nested group:
       <Route index element={<Home />} />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weather API, Python or JavaScript I am trying to get weather API working. But how can I just get the C° and weather icon; nothing else?

A: Once you have installed pywapi with pip, open a ipython shell and explore what pywapi can do. Here's an example which actually gives you what you want:-
In [1]: import pywapi

In [2]: pywapi.
pywapi.GOOGLE_CITIES_URL                   pywapi.YAHOO_WEATHER_URL                   pywapi.get_weather_from_weather_com        pywapi.urlopen
pywapi.GOOGLE_COUNTRIES_URL                pywapi.getText                             pywapi.get_weather_from_yahoo              pywapi.wind_beaufort_scale
pywapi.NOAA_WEATHER_URL                    pywapi.get_cities_from_google              pywapi.minidom                             pywapi.wind_direction
pywapi.URLError                            pywapi.get_countries_from_google           pywapi.quote                               pywapi.xml_get_attrs
pywapi.WEATHER_COM_URL                     pywapi.get_everything_from_yahoo           pywapi.re                                  pywapi.xml_get_ns_yahoo_tag
pywapi.YAHOO_WEATHER_NS                    pywapi.get_weather_from_noaa               pywapi.sys                                 pywapi.yield_all_country_city_codes_yahoo

In [2]: pywapi.get_weather_from_yahoo?
Type:       function
String Form:<function get_weather_from_yahoo at 0x10daeb9b0>
File:       /Users/calvin/.virtualenvs/myweather/lib/python2.7/site-packages/pywapi.py
Definition: pywapi.get_weather_from_yahoo(location_id, units='metric')
Docstring:
Fetches weather report from Yahoo! Weather

Parameters:
  location_id: A five digit US zip code or location ID. To find your location ID,
  browse or search for your city from the Yahoo! Weather home page (http://weather.yahoo.com/)
  The weather ID is in the URL for the forecast page for that city. You can also get
  the location ID by entering your zip code on the home page. For example, if you
  search for Los Angeles on the Weather home page, the forecast page for that city
  is http://weather.yahoo.com/forecast/USCA0638.html. The location ID is USCA0638.

  units: type of units. 'metric' for metric and '' for non-metric
  Note that choosing metric units changes all the weather units to metric,
  for example, wind speed will be reported as kilometers per hour and
  barometric pressure as millibars.

Returns:
  weather_data: a dictionary of weather data that exists in XML feed.
  See http://developer.yahoo.com/weather/#channel

In [3]: pywapi.get_weather_from_yahoo('USCA0638')
Out[3]:
{'astronomy': {'sunrise': u'6:16 am', 'sunset': u'7:28 pm'},
 'atmosphere': {'humidity': u'67',
  'pressure': u'1013.7',
  'rising': u'1',
  'visibility': u'16.09'},
 'condition': {'code': u'33',
  'date': u'Sat, 20 Apr 2013 9:46 pm PDT',
  'temp': u'18',
  'text': u'Fair',
  'title': u'Conditions for Los Angeles, CA at 9:46 pm PDT'},
 'forecasts': [{'code': u'31',
   'date': u'20 Apr 2013',
   'day': u'Sat',
   'high': u'26',
   'low': u'15',
   'text': u'Clear'},
  {'code': u'32',
   'date': u'21 Apr 2013',
   'day': u'Sun',
   'high': u'26',
   'low': u'14',
   'text': u'Sunny'},
  {'code': u'34',
   'date': u'22 Apr 2013',
   'day': u'Mon',
   'high': u'22',
   'low': u'13',
   'text': u'Mostly Sunny'},
  {'code': u'30',
   'date': u'23 Apr 2013',
   'day': u'Tue',
   'high': u'21',
   'low': u'14',
   'text': u'Partly Cloudy'},
  {'code': u'30',
   'date': u'24 Apr 2013',
   'day': u'Wed',
   'high': u'19',
   'low': u'13',
   'text': u'Partly Cloudy'}],
 'geo': {'lat': u'34.05', 'long': u'-118.23'},
 'html_description': u'\n[![][5]][5]
\nCurrent Conditions:
\nFair, 18 C
\n
Forecast:
\nSat - Clear. High: 26 Low: 15
\nSun - Sunny. High: 26 Low: 14
\nMon - Mostly Sunny. High: 22 Low: 13
\nTue - Partly Cloudy. High: 21 Low: 14
\nWed - Partly Cloudy. High: 19 Low: 13
\n
\nFull Forecast at Yahoo! Weather

\n(provided by The Weather Channel)
\n',
 'link': u'http://us.rd.yahoo.com/dailynews/rss/weather/Los_Angeles__CA/*http://weather.yahoo.com/forecast/USCA0638_c.html',
 'location': {'city': u'Los Angeles', 'country': u'US', 'region': u'CA'},
 'title': u'Yahoo! Weather - Los Angeles, CA',
 'units': {'distance': u'km',
  'pressure': u'mb',
  'speed': u'km/h',
  'temperature': u'C'},
 'wind': {'chill': u'18', 'direction': u'0', 'speed': u'0'}}

As you can see in the results, you can get the weather icon in html_description (http://l.yimg.com/a/i/us/we/52/33.gif) and the temp.  Since the results returned to you is everything, you will need to extract/access it like you would do with a python dictionary.
UPDATE

*

*Go to http://weather.yahoo.com/ and type in your zip code (or your city).

*If there is more than one choice, pick the one you want.

*Locate the link "extended forecast" under "6-10 day" column. Click it.

*Look at the URL address bar and the numbers there is your city's zip code.

ALL CITY CODE
Here's the function that helps you get all country, city codes
In [4]: pywapi.yield_all_country_city_codes_yahoo?
Type:       function
String Form:<function yield_all_country_city_codes_yahoo at 0x10daebaa0>
File:       /Users/calvin/.virtualenvs/myweather/lib/python2.7/site-packages/pywapi.py
Definition: pywapi.yield_all_country_city_codes_yahoo(country_code, cities)
Docstring:
Yield all cities codes for a specific country.

Parameters:
  country_code: A four letter code of the necessary country. For example 'GMXX' or 'FRXX'.
  cities: The number of cities to yield

Returns:
  country_city_codes: A generator containing the city codes

A: You can use Metwit weather api.
If you can implement them client-side: 200 request/day (ip based throttling) no authentication required. Worldwide coverage, JSON and REST compliant. You can register for extra API calls for free and if you still need it to call them server side the basic plan is pretty cheap.
Here a little example in jQuery: http://jsbin.com/isukam/1 that use our weather resource.
Full disclosure: I own this sweet piece of API.


text:
Q: REST API Design: Where to create Resource that depends from other resource? If I have two resources where one is created from the other, where should I put the creation endpoint to?
Example:
I have two resources, A and B and I want to create a B.
B is a simple class which references an A and the user who created it, like this
public class B {
    private A a;
    private User user;
}

The user information is send implicitly with the HTTP request, so I dont need any params for that.
Solution 1:
Send a POST without any arguments to /A/123/B and return B. This means the Controller for A is responsible for creating B. Feels strange.
Solution 2:
Send a POST with id 123 to /B. This means I have to check in the Controller for B if an A with id 123 exists. Feels also strange.
What are the pros and cons for both solutions? Am I overthinking the API design?

A: You need to be clear about dependency.
Does A being composed of B? In other word does B exist out of A scope?

*

*If the answer is yes, B can be alive without A, it is better to have a separate resources:
POST ./B

You should avoid resource being place at different location path. Some may argue that REST does not force you to have a single endpoint for one resources but keeping consistency cross different endpoint is not that obvious. What would happen to B if you send a DELETE ./A/{id} ?

*If the response is no, meaning that B could not exist unless A exist, then it is better to have B as a sub-resource.
POST ./A/{id}/B

Speaking of controller, there is nothing that force you from managing B from an other controller. The whole point of REST is that call are not address to the controller but to the resource. Resources that you are creating are independent from the controller.


text:
Q: What is the exact way of using where clause in PostgreSQL 12? I am trying to query a table using where clause in Postgres 12
case 1
SELECT *
FROM schema.e_employee_table
WHERE FK_EMPLOYEE=100;

so when i query the above query i get "FK_EMPLOYEE" column is missing.
case2:
SELECT *
FROM schema.e_employee_table
WHERE "FK_EMPLOYEE"=100;

when i query the above one i got the query results
So can someone explain do we need to put our column name inside "",is it the syntax. If so where it is mentioned in the official documentation.
And I can also see the column name we are mentioning is case sensitive.


text:
Q: remove new line characters from txt file using php I have txt file its content like this
Hello
World
John
play
football

I want to delete the new line character when reading this text file, but I don't know how it look like
the file .txt and its encoding is utf-8

A: If your going to be putting the lines into an array, an assuming a reasonable file size you could try something like this.
$file = 'newline.txt';
$data = file_get_contents($file);
$lines = explode(PHP_EOL, $data);

/** Output would look like this

Array
(
    [0] => Hello
    [1] => World
    [2] => John
    [3] => play
    [4] => football
)

*/

A: Just use file function with FILE_IGNORE_NEW_LINES flag.
The file reads a whole file and returns an array contains all of the file lines.
Each line contains new line character at their end as default, but we can enforce trimming by FILE_IGNORE_NEW_LINES flag.
So it will be simply:
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

The result should be:
var_dump($lines);
array(5) {
    [0] => string(5) "Hello"
    [1] => string(5) "World"
    [2] => string(4) "John"
    [3] => string(4) "play"
    [4] => string(8) "football"
}

A: There are different kind of newlines. This will remove all 3 kinds in $string:
$string = str_replace(array("\r", "\n"), '', $string)

A: I note that the way it was pasted in the question, this text file appears to have space characters at the end of each line.  I'll assume that was accidental.
<?php

// Ooen the file
$fh = fopen("file.txt", "r");

// Whitespace between words (this can be blank, or anything you want)
$divider = " ";

// Read each line from the file, adding it to an output string
$output = "";
while ($line = fgets($fh, 40)) {
  $output .= $divider . trim($line);
}
fclose($fh);

// Trim off opening divider
$output=substr($output,1);

// Print our result
print $output . "\n";

A: For PHP's file() function, the FILE_IGNORE_NEW_LINES flag is the way to go. In case you get your array in another way, like with gzfile(), do this:
// file.txt
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

// file.txt.gz
$lines = gzfile('file.txt.gz');
$lines = array_map(function($e) { return rtrim($e, "\n\r"); }, $lines);


text:
Q: Reading an array with value at end of file I am trying to read this file that looks like this (gameboard with 6 rows, 7 columns), and want to store the last value in a variable int called nextMove.
0000000
0000000
0000000
0000000
0000000
0000000
1

I'm reading this input file with this code:
ifstream f;
f.open(input_file);

int n;

for (int i = 0; i < 6; i++) {
    vector<int> row;
    for (int j = 0; j < 7; j++) {
        f >> n;
        row.push_back(n);
    }
    gameBoard.push_back(row);
}

f >> nextMove;

f.close();

code to print the gameBoard:
for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            cout << gameBoard[i][j] << " ";
        }
        cout << endl;
    }

This is the output, and I do not understand why it gets fill with ones:
0 0 0 0 0 0 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1


text:
Q: Highcharts on rails app renders twice every time it's loaded I'm using Highcharts in a Rails 4 application.  Every time a chart is loaded, it is rendered twice.  For example, if I click a link to render the partial containing a particular chart, the chart will display once, and then display again.  The app is doing twice the work it should be doing, so I'd like to fix this double rendering issue
Here's an example call to one of the charts that's doing this:
View:
<button class="btn btn-default">
    <%= link_to "Cumulative Customers", cumulative_customers_path, id: "bookings_per_customer", remote: true %>
</button>

cumulative_customers.js.erb:
$('.chart-display').html("");
$('.chart-display').append("<%= j render :partial => 'cumulative_customer_chart' %>");
$('.chart-display').append("<%= j render :partial => 'cumulative_customer_scripts' %>");

_cumulative_customer_chart.html.erb:
<div class="col-sm-12">
    <%= content_tag :div, "", id: "cumulative_customers_chart" %>
</div>

_cumulative_customer_scripts.html.erb:
<script>
$(function () {
  new Highcharts.Chart({

    chart: {
        renderTo: 'cumulative_customers_chart',
        height: 600
    },
    credits: {
        enabled: false
    },

    title: { text: 'Customer Accounts by Day' },
    xAxis: { type: 'datetime' },
    yAxis: {
      title: { text: 'Customer Accounts' }
    },
     series: [
        {
            type: 'area',
        name: 'Customer Accounts',
      pointInterval: <%= 1.day * 1000 %>,
      pointStart: <%= get_point_start %>,
      data: <%= cumulative_customers_count(params[:filter_period]) %>
    }]

  });
});

I don't see anything to indicate that Highcharts is being queried more than once... Can anyone please provide some insight?

A: I've found the solution.  This only happens in development and not in production, and was caused by precompiling assets into public/assets for production.


text:
Q: 'An error occurred while trying to authenticate: Failed to validate signature.' While using `oauth-1.0a` and nodejs I'm getting this odd error in nodejs when I try to send a post request with oauth-1.0a and node.js.
Request:
Headers:
Authorization: OAuth <...>
Accept: 'application/xml',
Content-Type: 'application/xml'

Body:
<account>
    <firstName>${first}</firstName>
    <lastName>${last}</lastName>
    <email>${email}</email>
    <urlRedirect>${redirecturl}</urlRedirect>
</account>`

Response:
401
An error occurred while trying to authenticate: Failed to validate signature.

Code:

require('dotenv').config()
const request = require('request')
const OAuth = require('oauth-1.0a')
const crypto = require('crypto')
var first = "real";
var last = "person";
var email = "real@person.com";
var redirecturl = "http://google.com"
const oauth = OAuth({
    version: '1.0a',
    consumer: {
        key: process.env.CONSUMERKEY,
        secret: process.env.CONSUMERSECRET,
    },
    signature_method: 'HMAC-SHA1',
    hash_function(base_string, key) {
        return crypto
            .createHmac('sha1', key)
            .update(base_string)
            .digest('base64')
    },
})
console.log(oauth)
const token = {
    key: process.env.KEY,
    secret: process.env.SECRET,
}
const request_data = {
    url: `https://${process.env.CHURCHCODE}.fellowshiponeapi.com/v1/Accounts`,
    method: 'POST',
    data: `<account>
    <firstName>${first}</firstName>
    <lastName>${last}</lastName>
    <email>${email}</email>
    <urlRedirect>${redirecturl}</urlRedirect>
  </account>`
}
const headers = Object.assign( oauth.toHeader(oauth.authorize(request_data, token)), {
    Accept: 'application/xml',
    'Content-Type': 'application/xml'
});
console.log(headers);
request(
    {
        url: request_data.url,
        method: request_data.method,
        headers: headers
    },
    function(error, response, body) {
        console.log(response.statusCode)
        console.log(response.statusMessage)
     }
)

Why is this error occurring?
Edit: one of the more useful resources I used was this: https://oauth.net/core/1.0/#signing_process but I still can't figure this out.
Should also mention that this request does work, as in postman it successfully goes through.

A: You typically want to provide the token in a request using this header:
Authorization: Bearer <token>

Not
Authorization: OAuth <...>


text:
Q: Facebook connect approbation Context: For a Hackathon I building an app (web based - Ruby on Rails) that matches people based on their commun interests. For that I want to use Facebook connect and instantaneously get a person's likes so I can match him/her with someone with similar interests.
The problem: But apparently I can't access someone's likes through Facebook connect unless my app has been approved by Facebook. But without this login there is no app (and I can't wait 3-7 business days to have a working app).
Is there a way I can get my app to work (even if it's only with a set of approved users/testers)? Or do I have to come up with a an alternative page where my users will have to manually enter their interests?

A: No, there's no shortcut for the Login Review. What you can do is adding specific users (via your app's dashboard) you want to test your functionality with as admins/developers/testers of the specific app.
This will allow them to be able to grant your app extended permissions as user_likes without Login Review.
Also, I think Facebook already provides an endpoint for your use case:
/{user-id}?fields=context{mutual_likes}

which will produce something like
{
  "context": {
    "mutual_likes": {
      "data": [
        {
          "category": "Media/news/publishing",
          "name": "Mashable",
          "id": "18807449704"
        },
        {
          "category": "Food/beverages",
          "name": "Coca-Cola",
          "id": "40796308305"
        }
      ],
      "paging": {
        "cursors": {
          "before": "MTg4MDc0NDk3MDQ=",
          "after": "NDA3OTYzMDgzMDU="
        }
      },
      "summary": {
        "total_count": 2
      }
    }
  },
  "id": "123456789"
}

See

*

*https://developers.facebook.com/docs/graph-api/reference/v2.0/user.context/mutual_likes

*https://developers.facebook.com/docs/graph-api/reference/v2.0/page.context/friends_who_like

*https://developers.facebook.com/docs/facebook-login/review/how-to-submit#testpermissions

*https://developers.facebook.com/apps/{your_app_id}/roles/


text:
Q: Always return 0 exit code When running my Cypress tests I want to always return exit code 0. I run these tests after my release deployment so when it returns a non-zero exit code the test details doesn't report to the release summary. Many test runners have a configuration option to fail on an error or not, and so I am looking for that option. Haven't seen anything like that yet so please point me in that direction. If it doesn't exist I'll open a feature request.
Thanks!

A: Try this:
// likely want to do this in a support file
// so it's applied to all spec files
// cypress/support/index.js

Cypress.on('uncaught:exception', (err, runnable) => {
  // returning false here prevents Cypress from
  // failing the test
  return false
})

/api/events/catalog-of-events.html#Uncaught-Exceptions


text:
Q: Find a + b + c + bc. My math trainer friend ask my help to look for the shortest possible solution for this problem:
Let $a$, $b$ and $c$ be positive integers such that
$$\left \{\begin{matrix}a + b + ab = 15 \\
b + c + bc = 99 \\
c + a + ca = 399\end{matrix}\right. $$

Find $a + b + c + bc.$

I tried elimination but it took us for about 3 min to do it. This question was intended for 15 seconds only.

A: $(a+1)(b+1) = 16 $
$(b+1)(c+1) = 100$
$(c+1)(a+1) = 400$
Multiply all $3$ equations to get value of $(a+1)(b+1)(c+1) = 800$ then
$c+1 = 50,\quad a+1 = 8,\quad b+1 = 2$ , required is $a+(99) = 106$

A: Adding $1$ to each equation, we get that
$$\left \{\begin{matrix}a + b + ab +1 = 16 \\
b + c + bc+1 = 100 \\
c + a + ca+1 = 400\end{matrix}\right. $$
Factoring, we get
$$\left \{\begin{matrix}(b+1)(a+1) = 16 \\
(b+1)(c+1) = 100 \\
(c+1)(a+1) = 400\end{matrix}\right. $$
Dividing equation 2 from equation 3 and multiplying the result with equation 1, we get that $(a+1)^2=64$, meaning $a+1=8$. Equation one gives us $b+1=2$, and equation three gets us $c+1=50$, getting that
$$a+b+c+bc=7+1+49+49=106$$

A: Also elimination leads to the result (as the OP wanted), namely we obtain exactly two solutions over any field of characteristic zero:
$$
(a,b,c)=(-9,-3,-51),(7,1,49).
$$
Then $a+b+c+bc=7+1+49=106$, since only the positive solution was asked.


text:
Q: Does Chrome Frame work in the legacy IE browser ActiveX control? We have a legacy VB6 app that makes use of the IE browser ActiveX control (Shdocvw.dll).  Will Chrome Frame work correctly when a web page is requested via the ActiveX control as opposed to a full stand-alone IE instance?
Thanks


text:
Q: how to use with_items register.results I'm currently running a command as follows:
- name: "1. search directory"
  shell: find /var/ -name "directory"
  register: directoty

- name: "boucle"
  debug:
    msg: "{{item}}"
    with_items: "{{directory.stdout_lines}}"

- name: "2. check existance of file"
  stat:
   path: "{{item}}/file.log"
  with_items: "{{directory.stdout_lines}}"
  register: checkfile

- debug:
   msg: "file name {{item}} exists"
   with_items: {{checkfile.results}}
   when: checkfile.stat.exists

when i launch it i have error:
with_items: \"{{checkfile.results}}\"\n      ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes. Always quote template expression brackets when they\nstart a value. For instance:\n\n    with_items:\n      - {{ foo }}\n\nShould be written as:\n\n    with_items:\n      - \"{{ foo }}\"\n"}
what can i do to use with_items with stat register

A: There are a few issues with your last task.

*

*Add quotes " to the with_items: parameter value

*Use item in the when: parameter

*Use consistent spacing in YAML files (i.e. 2 space indentations)

Example below:
- name: "2. check existance of file"
  stat:
    path: "{{item}}/file.log"
  with_items: "{{directory.stdout_lines}}"
  register: checkfile

- debug:
    msg: "file name {{item}} exists"
    with_items: "{{checkfile.results}}"
    when: item.stat.exists


text:
Q: Why does a null value appear in string output? When I execute the following code the output is "nullHelloWorld". How does Java treat null?
import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str=null;
        str+="Hello World";
        System.out.println(str);
    }
}

A: When you try to concat null through + operator, it is effectively replaced by a String containing "null".
A nice thing about this is, that this way you can avoid the NullPointerException, that you would otherwise get, if you explicitly called .toString() method on a null variable.

A: You are attempting to concatenate a value to null.  This is governed by "String Conversion", which occurs when one operand is a String, and that is covered by the JLS, Section 5.1.11:

Now only reference values need to be considered:

*

*If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

A: Java treats null as nothing, it is the default value of a String. It appears in your String output because you use += to add "Hello World" to str.
String str=null;
str+="Hello World";
System.out.println(str);

You are basically telling Java: give my str variable the type of String and assign it the value null; now add and assign (+=) the String "Hello World" to the variable str; now print out str

A: my two cent:
    String str = null;
    str = str.concat("Hello World"); // Exception in thread "main" java.lang.NullPointerException

but
str += "Hello World";
System.out.println(str); // Hello World


text:
Q: How to get Typeface reference to a WebView system bundled font? (Georgia, Times New Roman..) I am making a reader type application which uses a webview to render text, user can change fonts, so say Georgia or Times New Roman, with seem to be bundled with the system (or webview atleast). This works well.
But I want to use Georgia on android view (settings button as to change the font). Is there a way to get a reference to "Georgia", or "Times New Roman" in android so it can be used on a TextView?
Typeface.create("Georgia", 0) doesnt work

A: Ok Ive figured it out, font name has to be lower case
Typeface.create("georgia", 0)
Typeface.create("times new roman", 0)


text:
Q: laravel mix : add dependency before run code I'm new to laravel webpack . This is my app.js :
require('./bootstrap');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
 el: '#app'
});

$(document).ready(function(){
$('.owl-carousel').owlCarousel();
});

and bootstrap.js :
window._ = require('lodash');

window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');

require('owl.carousel');

window.Vue = require('vue');

window.axios = require('axios');

window.axios.defaults.headers.common = {
 'X-CSRF-TOKEN': window.Laravel.csrfToken,
 'X-Requested-With': 'XMLHttpRequest'
};

I've added owl-carousel library in bootstrap.js and  initiated owl-carousel in last line of app.js .but when i run npm run watch and  check app.js (created in public/js
)through browser i see owl-carousel library is located after $('.owl-carousel').owlCarousel(); . So owl-carousel wont run . how may i manage this issue?


text:
Q: Context vs Config classes I am implementing some classes in my application and I am little bit confused on choosing AppContext vs AppConfiguration.
My application configs are in YAML files which are parsed in application startup. Currently we are planning AppContext for just simple properties and AppConfiguration for getting complex properties/arrays.

A: ApplicationContext is basically backbone of running Spring, while configuration is definition how to do that. So context must know how to instantiate a bean - that is why bean factory is mandatory. Also context can have parent context. There are some other things that context is responsible for - please read the doc.
Configuration can define context, or provide other static information used by the app to do what is needed. That information can be taken from many sources, can be refreshed, and so on - but still - that is more like parameter, input for context.


text:
Q: Perl not found in gdata package in R I get this error while using read.xls(),
Error in findPerl(verbose = verbose) :
perl executable not found. Use perl= argument to specify the correct path.
Error in file.exists(tfn) : invalid 'file' argument

How and where to download perl for gdata package in R?

A: use below thing to find the perl

*

*find the location of perl in the system and specify the exact path

read.xls(verbose=FALSE, perl="C:\Perl64\bin\perl.exe")


text:
Q: Issues in expanding expressions with formal sums I have a very long expression involving formal sums to infinity, unfixed functions and several variables.
In this very long expression, I need a typical term, like
$\frac{6 A \sigma  \sum _{n=0}^{\infty } \left(\frac{2 A (n+1)^2 e^{-\frac{A (n+1)}{w^2}} \left(\sum _{m=0}^{\infty } (m+1) (m+2) w^m \sigma ^n a(n+1,m+2)\right)}{w^3}+(n+1) e^{-\frac{A (n+1)}{w^2}} \left(\sum _{m=0}^{\infty } m (m+1) (m+2) w^{m-1} \sigma ^n a(n+1,m+2)\right)\right)}{w^3}$,
to be given like,
$\frac{6 A \sigma  \sum _{n=0}^{\infty } (n+1) e^{-\frac{A (n+1)}{w^2}} \sum _{m=0}^{\infty } m (m+1) (m+2) w^{m-1} \sigma ^n a(n+1,m+2)}{w^3}+\frac{2 A \sum _{n=0}^{\infty } (n+1)^2 e^{-\frac{A (n+1)}{w^2}} \sum _{m=0}^{\infty } (m+1) (m+2) w^m \sigma ^n a(n+1,m+2)}{w^6}$,
i.e to be expanded.
I need to do this for quite a lot of terms, and Mathematica's Expand or ExpandAll doesn't work.
Here's the code:
What I want is,
(6/w^3)*A*\[Sigma]*
  Sum[((1 + n)*
      Sum[m*(1 + m)*(2 + m)*w^(-1 + m)*\[Sigma]^n*
        a[1 + n, 2 + m], {m, 0, Infinity}])/E^((A*(1 + n))/w^2), {n,
    0, Infinity}] +
   (2/w^6)*A*
  Sum[((1 + n)^2*
      Sum[(1 + m)*(2 + m)*w^m*\[Sigma]^n*a[1 + n, 2 + m], {m, 0,
        Infinity}])/E^((A*(1 + n))/w^2), {n, 0, Infinity}]

What I have is,
(6*A*\[Sigma]*
   Sum[((1 + n)*
        Sum[m*(1 + m)*(2 + m)*w^(-1 + m)*\[Sigma]^n*
          a[1 + n, 2 + m], {m, 0, Infinity}])/E^((A*(1 + n))/w^2) +
          (2*A*(1 + n)^2*
        Sum[(1 + m)*(2 + m)*w^m*\[Sigma]^n*a[1 + n, 2 + m], {m, 0,
          Infinity}])/(E^((A*(1 + n))/w^2)*w^3), {n, 0, Infinity}])/
 w^3


text:
Q: What is considered as whitespace in HTTP header I've just been reading HTTP standard (propsed standard to be more precise) part 1 and got confused with what they consider as "whitespace" in section 3, second to last paragraph:
https://www.rfc-editor.org/rfc/rfc7230#section-3
Since returns (CRLFs) terminate HTTP header, the only whitespaces that may be implied are 0x20 'Space' characters. Wikipedia lists another kinds of whitespace ASCII symbols, like 'Non-breaking space' 0xA0, so I still don't understand this ("whitespace") concept.
Please, help me figure out what it really means in scope of this standard.

A: RFC 7230, which you linked to, defines EXACTLY what it considers to be whitespace in a header:

HTTP-message   = start-line
                 *( header-field CRLF )
                 CRLF
                 [ message-body ]

header-field   = field-name ":" OWS field-value OWS

field-name     = token
field-value    = *( field-content / obs-fold )
field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
field-vchar    = VCHAR / obs-text

obs-fold       = CRLF 1*( SP / HTAB )
               ; obsolete line folding
               ; see Section 3.2.4

obs-text       = %x80-FF

OWS            = *( SP / HTAB )
               ; optional whitespace

As you can see, SP (space) and HTAB (horizontal tab) are the only defined whitespace characters.  They are defined in RFC 5234 Appendix B.1, which RFC 7230 links to:

HTAB           =  %x09
               ; horizontal tab

SP             =  %x20

A: *

*See also https://www.rfc-editor.org/rfc/rfc7230#section-3.2.3.

*HTAB is also whitespace.

*In the context of Section 3, "A sender MUST NOT send whitespace between the start-line and the first header field." also refers to extra line breaks.


text:
Q: Reference: probability distribution of first meeting time of two random walks on a cycle graph I am looking for a reference or derivation for the following question:
Consider a cycle graph $G$ with $N$ vertices (see example here). Let two independent continuous-time random walkers$^\star$ start on node $i$ and node $j$. Let $T$ be the time when the two walkers meet for the first time.
What will be the probability density function of $T$?
I am looking for the exact expression of that pdf for finite $N$. I am sure this is a well known question with a precise formula but I have not been able to find a clear reference solving it. This is a new field for me so perhaps I am using the wrong vocabulary? With the hope that this post will help. Thanks!
($^\star$: each walker jumps to a neighboring vertex (chosen at random) with rate one.)

A: Assume that $i<j.$ You can reduce this to the following simpler-looking question: Consider a continuous-time RW on the integers, moving at rate two, started at $k:=j-i$. Let $T$ be the hitting time of $\{0,N\}$ by this walk, also known as as the exit time from $[1,N-1]$. Let $\tau$ denote  the hitting time of $\{0,N\}$ by discrete-time random walk. The distribution of $\tau$   can be determined from the arguments in Chapter 21 of [1]. (Spitzer gives the general method, and then provides all the details only for the case $k=N/2$.) Then you can deduce the distribution of $T$ via
$$P_k[T>q] = \sum_n P[{\rm Poisson}(2q)=m] \cdot P_k[\tau>m] \,.$$
See also [2].
[1] Spitzer, Frank. Principles of random walk. GTM Vol. 34. Second edition, Springer.
[2]https://www.researchgate.net/publication/254211645_Exit_times_for_a_class_of_random_Walks_Exact_distribution_results


text:
Q: Find number of consecutive different entries in a row for each entry I am attempting to automate a count showing how many consecutive different entries have been added in a row. For example, the first entry would return 1, while the second entry would return 1 if the same as the first or 2 if different. I am struggling to find a way of getting the formula to search 'backwards' along the row until it finds an entry it has already seen.
I am struggling to find a way of getting the formula to search 'backwards' along the row until it finds an entry it has already seen.
The closest I have got (which very much does not work and is only half a formula) is something along the lines of =IF(D2=C2,1,IF(COUNTIF($C2:D2,D2)=1,C6+1,"")) where the data is entered into row 2 starting in column B (the first two entries are trivial - it is after this I am struggling). The "" within my formula is where I think that some clever checking will occur, but I can't work out what it would be.
My aim is that the following could be obtained:
A A B C D E F G H I A A A J K L B M N O A A A P A Q R A A
1 1 2 3 4 5 6 7 8 9 9 1 1 2 3 4 5 6 7 8 8 1 1 2 2 3 4 3 1

However, my above formula only works until the run of 3x 'A's.
Many thanks for any help - this is my first question, so please be kind!

A: *

*type a 1 in cell A2

*in cell B2, use the following formula:
=IF(B1>A1,A2+1,1)

*Populate this formula until the last column

A: This should be OK now, in A3:
=MIN(IF(COUNTIFS($A1:A1,$A1:A1,$A2:A2,">="&A2-TRANSPOSE($A2:A2)+1)>1,TRANSPOSE(COLUMN($A2:A2)),99)-1,COLUMNS($A1:A1))

It does require an extra row with numbers 1-29 in it.
Must be entered as an array formula using CtrlShiftEnter

This starts off with the normal countif with an array. If you consider this for columns A-D, so COUNTIF($A1:D1,$A1:D1) you would get
2 2 1 1

(a row array) because of the repeated A's in A1 and B1.
I have used COUNTIFS and added another condition, to only take into account the current column (D), then add the column before it (C:D), then B:D and finally A:D. So you get a 2D array:
0 0 0 1

0 0 1 1

1 1 1 1

2 2 1 1

Then substitute anything larger than 1 with a large number (say 99), anything else with the row number of the array:
99 99 99 99
99 99 99 99
99 99 99 99
 4  4 99 99

Find the smallest number in the array and subtract 1.
If array contains all 99's,take the number of columns up to the current column.
Because Count and Countif only work with actual ranges, I couldn't think of a way of using them without creating a helper row containing the column numbers.


text:
Q: When Can Integration and Expectation be Exchanged? When is it possible to move expectations into integrals?
I want to find the expectation of a random variable that is defined as an integral. I want to bring the expectation inside the integral, but I'm not sure if/when that is possible.

A: Generally speaking, the expected value of an integral is an iterated integral, and so the normal mathematical rules for interchange of integrals apply.  To see this more clearly, we first note that the expectation operator is an integration operation.  Formally, a random variable $X$ in the probability space $(\Omega, \mathscr{G}, P)$ has expected value defined by the Lebesgue integral:
$$\mathbb{E}(X) \equiv \int_\Omega X(\omega) dP(\omega).$$
Now, suppose we have a random variable that is an integral over some other function:
$$X(\omega) = \int_\mathbb{R} H(r,\omega) dr.$$
In this case, the expected value can be written as an iterated integral as follows:
$$\mathbb{E}(X) = \int_\Omega \Bigg( \int_\mathbb{R} H(r,\omega) dr \Bigg) dP(\omega).$$
Now, there are a number of theorems relating to when you are allowed to interchange the order of integration in this kind of iterated integral, but the most important is Fubini's theorem.  (If $H$ is a measureable function in the above expression and $\mathbb{E}|H|$ is finite then you will be able to interchange the order of integration under this theorem.)  This is a large subject, so I will not attempt to set it out fully here.  Instead, I will refer you to books on integration and measure theory, which deal with the basis of Lebesgue integration and the application of iterated integrals.  Good luck with your explorations!


text:
Q: Software suddenly not starting, doesn't show up in System Monitor Specifically, I'm trying to get RStudio to work on Ubuntu 12.04. Yesterday it was working fine, but now when I either click or try to start it from terminal, exactly nothing happens. The prompt returns nothing, the click produces nothing. What could have caused this and how do I fix it?

A: Found the issue.
For some reason, locale issues were causing it. When trying to run r from terminal, there was some locale related error message, so I just generated and reconfigured a new one as described here:
How do I fix my locale issue?
Suddenly RStudio was working fine.

A: Try putting apparmor in complain mode. this may allow Rstudio to work as well as give clues as to why it's throwing that DENIED at you.
see this


text:
Q: I want my bot to only recognize commands that start with a capital letter exports.run = async (bot,message,args) => {
    if (!args.length) {
        return (message.channel.send('no card was requested'))
    }

    message.channel.send(`https://metazoospellbook.com/image/${args.join('%20')}KS.png`)

}

exports.help = {
    name: 'card'

I have this portion working fine, but I only want it to read arguments that start with a capital letter i.e. 'Bookmark" instead of 'bookmark'

A: test if message.content [ 0 ] is the same as message.content [ 0 ].toUpperCase ( )

A: includes method of string can help you if you test a string with full upercase char.

const uppercases = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

console.log("isUppercase ?", uppercases.includes("a"))
console.log("isUppercase ?", uppercases.includes("A"))

will give you "true" if the letter is a uppercase.
So you can use a split and filter function to only take argument that start with an uppercase.
Here is a solution :

const uppercases = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

function checkUppercase(word) {
  return uppercases.includes(word[0])
}

function getOnlyUppercaseArgs(args) {
  return args.split(" ").filter(word => checkUppercase(word))
}

const args = "Here is My argument In lower And upper Case"

console.log(getOnlyUppercaseArgs(args))


text:
Q: How add annotation to semilogx in Matlab? I would like to add desciption on the curves in Matlab using annotation, but I always see the below error
Error using annotation
Unknown argument.

Error in del (line 5)
annotation('textarrow',Q,y,'String','y = x ')

May I get some assistance, please? Doesn't annotation work with semilogx?
Q = [16,32,64,128,256,512,1024];
y = [9     9     9     9     5     0     0]*0.25;
y1 = [45    37    25    21     5     0     0]*0.25;
semilogx(Q,y,Q,y1)
annotation('textarrow',Q,y,'String','\theta =0 ')
annotation('textarrow',Q,y1,'String','\theta = 10 ')
xlabel('Q oder');
ylabel('Coverage area m^2');
grid on;

A: annotation creates a line between two points.
The input to annotation must be on the format
x = [0.3 0.5];
y = [0.6 0.5];
annotation('textarrow',x,y,'String','\theta =0 ')

where x and y are selected by you. This is typically a bit of trial and error to make it look nice.


text:
Q: Print/Save autoencoder generated features in Keras I have this autoencoder:
input_dim = Input(shape=(10,))
encoded1 = Dense(30, activation = 'relu')(input_dim)
encoded2 = Dense(20, activation = 'relu')(encoded1)
encoded3 = Dense(10, activation = 'relu')(encoded2)
encoded4 = Dense(6, activation = 'relu')(encoded3)
decoded1 = Dense(10, activation = 'relu')(encoded4)
decoded2 = Dense(20, activation = 'relu')(decoded1)
decoded3 = Dense(30, activation = 'relu')(decoded2)
decoded4 = Dense(ncol, activation = 'sigmoid')(decoded3)
autoencoder = Model(input = input_dim, output = decoded4)
autoencoder.compile(-...)
autoencoder.fit(...)

Now I would like print or save the features generate in encoded4.
Basically, starting from a huge dataset I would like to extract the features generated by autoencoder, after the training part, to obtain a restricted representation of my dataset.
Could you help me?

A: You can do it by creating the "encoder" model:
encoder = Model(input = input_dim, output = encoded4)

This will use the same layers instances that you trained with the autoencoder and should be producing the feature if you use it in "inference mode" like encoder.predict()
I hope this helps :)

A: So, basically, by creating an encoder like this:
 encoder = Model (input_dim,encoded4)
 encoded_input=Input(shape=(6,))

and then using:
 encoded_data=encoder.predict(data)

where the data within the predict function is the dataset, the output generate by
 print encoded_data

is the restricted representation of my dataset.
It is right?
Thanks


text:
Q: What steps can you take to ensure sane build environments when compiling software? I'm having a horrible time getting a piece of software to compile on a CentOS box, and the problem I've listed below is specific, but I'm hoping the correct approach that comes out of this is one that can be applied to similar problems, as this doesn't seem to be one that's specific to just this piece of software. Getting to the point though...
I've been stuck with a compilation problem when building a standardised virtual machine on CentOS 5.4, and I'm in the dark here as to a) why this error is occurring, and b) how to fix it, and in the hope that someone else stumbles across this problem too, I'm hoping someone can help me find the solution here.
I'm getting a configure: error: newly created file is older than distributed files! error when trying to compile Ruby Enterprise like below when I try to run the installer, and the solutions offered to on the forums (of checking the tine, and touching the files to update the time associated with them) don't seem to be helping here.
What steps can I take to work out what the cause of this problem?
[vagrant@vagrant-centos-5 ruby-enterprise-1.8.7-2009.10]$ sudo ./installer
Welcome to the Ruby Enterprise Edition installer
This installer will help you install Ruby Enterprise Edition 1.8.7-2009.10.
Don't worry, none of your system files will be touched if you don't want them
to, so there is no risk that things will screw up.

You can expect this from the installation process:

  1. Ruby Enterprise Edition will be compiled and optimized for speed for this
     system.
  2. Ruby on Rails will be installed for Ruby Enterprise Edition.
  3. You will learn how to tell Phusion Passenger to use Ruby Enterprise
     Edition instead of regular Ruby.

Press Enter to continue, or Ctrl-C to abort.

Checking for required software...

 * C compiler... found at /usr/bin/gcc
 * C++ compiler... found at /usr/bin/g++
 * The 'make' tool... found at /usr/bin/make
 * Zlib development headers... found
 * OpenSSL development headers... found
 * GNU Readline development headers... found
--------------------------------------------
Target directory

Where would you like to install Ruby Enterprise Edition to?
(All Ruby Enterprise Edition files will be put inside that directory.)

[/opt/ruby-enterprise] :
--------------------------------------------
Compiling and optimizing the memory allocator for Ruby Enterprise Edition
In the mean time, feel free to grab a cup of coffee.

./configure --prefix=/opt/ruby-enterprise --disable-dependency-tracking
checking build system type... i686-pc-linux-gnu
checking host system type... i686-pc-linux-gnu
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... configure: error: newly created file is older than distributed files!
Check your system clock

This is a virtual machine running on virtualbox, and the time of the host and the virtual machine are identical, and up to date. I've also tried running this after updating time with an ntp-client, so no avail. I tried this after reading this post here of someone having a similar problem
[vagrant@vagrant-centos-5 ruby-enterprise-1.8.7-2009.10]$ date
Tue Apr 27 08:09:05 BST 2010

The other approach I've tried is to touch the top level the files in the build folder like suggested here, but this hasn't worked either (an to be honest, I'm not sure why it would have worked either)
[vagrant@vagrant-centos-5 ruby-enterprise-1.8.7-2009.10]$ sudo touch ruby-enterprise-1.8.7-2009.10/*

I'm not sure what I can do next here - the problem seems to be the bash configure script that returns this error error: newly created file is older than distributed files!, at line :2214
{ echo "$as_me:$LINENO: checking whether build environment is sane" >&5
echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6; }
# Just in case
sleep 1
echo timestamp > conftest.file
# Do `set' in a subshell so we don't clobber the current shell's
# arguments.  Must try -L first in case configure is actually a
# symlink; some systems play weird games with the mod time of symlinks
# (eg FreeBSD returns the mod time of the symlink's containing
# directory).
if (
   set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
   if test "$*" = "X"; then
      # -L didn't work.
      set X `ls -t $srcdir/configure conftest.file`
   fi
   rm -f conftest.file
   if test "$*" != "X $srcdir/configure conftest.file" \
      && test "$*" != "X conftest.file $srcdir/configure"; then

      # If neither matched, then we have a broken ls.  This can happen
      # if, for instance, CONFIG_SHELL is bash and it inherits a
      # broken ls alias from the environment.  This has actually
      # happened.  Such a system could not be considered "sane".
      { { echo "$as_me:$LINENO: error: ls -t appears to fail.  Make sure there is not a broken
alias in your environment" >&5
echo "$as_me: error: ls -t appears to fail.  Make sure there is not a broken
alias in your environment" >&2;}
   { (exit 1); exit 1; }; }
   fi
   ### PROBLEM LINE ####
   # this line is the problem line - this is returned true, sometimes it isn't and I can't
   # see a pattern that that determines when this will test will pass or not.
   test "$2" = conftest.file
   )
then
   # Ok.
   :
else
   { { echo "$as_me:$LINENO: error: newly created file is older than distributed files!
Check your system clock" >&5
echo "$as_me: error: newly created file is older than distributed files!
Check your system clock" >&2;}
   { (exit 1); exit 1; }; }
fi

the thing that makes this really frustrating is that this script works sometimes, when the VM has been running for an hour or so it works, but not at boot. There's nothing I see in the crontab that suggests any hourly tasks are run that might change the state of the system enough make a difference to this script working.
I'm totally at a loss when it comes to debugging beyond here. What's the best approach to take here?
Thanks

A: The "date sanity check" in that configure shell script looks borked to me, it needs fixing. Look at this:
echo timestamp > conftest.file
# Do `set' in a subshell so we don't clobber the current shell's
# arguments.  Must try -L first in case configure is actually a
# symlink; some systems play weird games with the mod time of symlinks
# (eg FreeBSD returns the mod time of the symlink's containing
# directory).
if (
   set X `ls -Lt $srcdir/configure conftest.file 2> /dev/null`
   if test "$*" = "X"; then
      # -L didn't work.
      set X `ls -t $srcdir/configure conftest.file`
   fi
   rm -f conftest.file
   if test "$*" != "X $srcdir/configure conftest.file" \
      && test "$*" != "X conftest.file $srcdir/configure"; then

So it touches a file and then tries to find out whether its mtime is newer than the mtime of $srcdir/configure, and is does so by invoking ls and then comparing the output to a fixed string. The authors write
  # If neither matched, then we have a broken ls.  This can happen
  # if, for instance, CONFIG_SHELL is bash and it inherits a
  # broken ls alias from the environment.  This has actually
  # happened.  Such a system could not be considered "sane".

but i think that is rubbish. There are too many versions/flavours of ls and ways to alter ls' output (they even name one) to be sure about ls' output format.
Anyway, there are way more elegant ways of doing this. E.g. in bash (see help test):
if [ $FILE1 -nt $FILE2 ] ; then
    echo "$FILE1 is newer than $FILE2"
elif [ $FILE2 -nt $FILE1 ] ; then
    echo "$FILE2 is newer than $FILE1"
else
    echo "$FILE1 and $FILE2 are equally new"
fi

Or find out whether some mtime is in the future directly!
find -L $FILE -newermt now -exec echo THE FILE {} IS COMING FROM THE FUTURE \;

or
find -L $FILE -mtime -0 -exec echo THE FILE {} IS COMING FROM THE PRESENT OR THE FUTURE \;

Now write the patch yourself :-)

A: Today I experienced exactly this problem on a newly installed box while installing ree-1.8.7-2011.03.
After configuring ntpd, checking the hardware clock and excluding actual problems with the clock and tima the error message still persisted. Finally I traced down this error to the included google-perftools directory. After touching that configure script, the problem just resolved and Ruby Enterprise Edition installed without any problem.
[mark@host347 ~]$ cd src/ree-1.8.7-2011.03/source/
[mark@host347 source]$ touch ./distro/google-perftools-1.7/configure

A: You don't talk much about your system clock performance.  Rather than looking at the compile issue, how about testing the system clock performance?  NTP can help with clock drift, but it won't fix something erratic.  If the hardware clock is busted, you might need a new motherboard.  Here is a test that might help:
for i in `seq 1 60`
do
date
sleep 60
done

This should output the date exactly every minute.  If the output
does not look like the below:
    Tue Apr 27 13:33:28 ADT 2010
    Tue Apr 27 13:34:28 ADT 2010
    Tue Apr 27 13:35:28 ADT 2010
...

then you have a hardware clock problem.  Fighting it with
tools like NTP might not work.  Hardware is the best fix if
you have a hardware problem.


text:
Q: Exception handling in Obj-C I have been reading about exception handling on the Apple developer docs, but I was wondering why exceptions by standard C operations are not caught?
E.g. the code below still crashes the application, without catching the div by zero.  Will the @try/@catch block only catch Obj-C code?
@try {
    int i = 10 / 0;
}
@catch (NSException * e) {
    NSLog(@"Div by zero!");
}
@finally {
    // Nothing...
}

A: Division by zero isn't an exception of type NSException. In fact, it's not really an "exception" in terms of a programming language, either. C itself doesn't have any exceptions in the same way that C++, Java, etc., do. When division by 0 in C occurs, an "exception" is "thrown" by the processor, and handling for that error happens at a much lower level.


text:
Q: Is there any limit to Gmail SMTP server requests/ sec? I am trying to send email using Gmail SMTP server from java (deployed in tomcat). When doing load testing if the number of request / sec to SMTP server grows more (>20) I get this exception
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;

nested exception is:java.net.ConnectException: Connection timed out

Is there any limitations in access rate for Gmail SMTP server ? Should I introduce delay between each request ?

A: After some searching, introducing a delay between every email getting sent is the way to go if you want to keep using the SMTP servers from Google. However, from what I read, a significant delay is required for these SMTP servers in order for them not to forcibly close your connection and actively drop new connections (by significant delay, I mean delays of more than 60 seconds). Load testing is out of the question this way: modern computers should be able to process sending an email within 60 seconds without any problems.
Bottom line: don't use Gmail SMTP for load testing. I would recommend setting up your own SMTP server which you can use, or maybe (temporarily) get an account at a professional mailing service. Keep in mind though, that if you host your own SMTP server, there is a possibility that your software performs the way it should, but that the SMTP server can have spam protection (by default).


text:
Q: How to make a for loop slower? setInterval(()=>{
    for (j = 0; j < obj.length; j++) {
    }
})

I have this loop setup, is there any way to make the for loop go slower? obj length can be as big as 200-400 arrays. Jquery answers accepted.

A: Promise based delay:

const delay = x => new Promise(res => setTimeout(res, x));
(async () => {
    for (let j = 0; j < 10; j++) {
        console.log(j);

        await delay(1000);
    }
})();

(Furthermore, i believe that jQuery should never be used.)


text:
Q: fullcalendar settings via ajax I would like to pass fullcalendar settings (i.e. startTime, endTime) via ajax. I would like to have something similar to this:
eventSources:
[
"events.php",
"settings.php"
]

where events.php holds events array, settings.php holds settings array. If this approach works, how can i use settings values? If settings.php generates json: [{"minTime":"0","maxTime":"17"}], how to pass this settings to fullcalendar?
Thanks

A: Maybe you could take a look at this:
http://www.feyasoft.com/myCalendar
"It is capable of rendering dynamic, calendar-style views of event data from JSON data"

A: you might be able to use a custom function instead to do something like this
http://arshaw.com/fullcalendar/docs/event_data/events_function/
where you have a manual getJSON call, and strip out your settings data, and pass only the event data to the callback.
HOWEVER, fullcalendar's settings cannot yet be modified after the calendar loads, so this would be impossible.
http://code.google.com/p/fullcalendar/issues/detail?id=293
version 1.5 will likely have this "feature"


text:
Q: elastic: query the sum of a filtered subset of nested documents Consider a document (post) like this in elasticsearch index:
    {
      title: "I love ice cream!"
      comments: [
        {
          body: "me too!",
          reaction: 'positive',
          likes: 20
        },
        {
          body: "huh!",
          reaction: 'sarcastic',
          likes: 5
        }
      ]
    }

The comments is a field of nested type.
How can elastic answer this:
Give me all posts, where the total sum of likes on "sarcastic" comments is greater than 100.
I'm open to any other way of modelling data which helps answer such queries.

A: This can be solved using bucket selector aggregation.
Mapping:
{
  "index1" : {
    "mappings" : {
      "properties" : {
        "comments" : {
          "type" : "nested",
          "properties" : {
            "body" : {
              "type" : "text"
            },
            "likes" : {
              "type" : "integer"
            },
            "reaction" : {
              "type" : "text"
            }
          }
        },
        "title" : {
          "type" : "keyword"
        }
      }
    }
  }
}

Data:
  "hits" : [
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "p0y9DGsBfPdKzuAGdQrm",
        "_score" : 1.0,
        "_source" : {
          "title" : "I love ice cream!",
          "comments" : [
            {
              "body" : "me too!",
              "reaction" : "positive",
              "likes" : 20
            },
            {
              "body" : "huh!",
              "reaction" : "sarcastic",
              "likes" : 5
            }
          ]
        }
      },
      {
        "_index" : "index1",
        "_type" : "_doc",
        "_id" : "qEy9DGsBfPdKzuAGnwox",
        "_score" : 1.0,
        "_source" : {
          "title" : "I hate ice cream!",
          "comments" : [
            {
              "body" : "me too!",
              "reaction" : "positive",
              "likes" : 10
            },
            {
              "body" : "huh!",
              "reaction" : "sarcastic",
              "likes" : 5
            }
          ]
        }
      }
    ]
  }

Query:
GET index1/_search
{
  "size": 0,
  "aggs": {
    "title": {
      "terms": {
        "field": "title"
      },
      "aggs": {
        "comments": {
          "nested": {
            "path": "comments"
          },
          "aggs": {
            "reaction": {
              "filter": {
                "term": {
                  "comments.reaction": "positive"
                }
              },
              "aggs": {
                "total_likes": {
                  "sum": {
                    "field": "comments.likes"
                  }
                }
              }
            }
          }
        },
        "total_likes_filter": {
          "bucket_selector": {
            "buckets_path": {
              "likes": "comments>reaction>total_likes"
            },
            "script": "params.likes > 15"
          }
        }
      }
    }
  }
}

Result:
  "aggregations" : {
    "title" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "I love ice cream!",
          "doc_count" : 1,
          "comments" : {
            "doc_count" : 2,
            "reaction" : {
              "doc_count" : 1,
              "total_likes" : {
                "value" : 20.0
              }
            }
          }
        }
      ]
    }
  }
}

Bucket contains only "I love ice cream!" where total likes for reaction positive  is greater than 20.
I hate ice cream! has total sum 5 for positive reaction so it is not included.


text:
Q: Regex Extract Valid Arabic Date I have this string date  السبت 18 سبتمبر/أيلول 2021
how can I use regex to extract valid date without day and month after slash
dd-month-yyyy

example of data:

الثلاثاء 21 سبتمبر/أيلول 2021

الأربعاء 22 سبتمبر/أيلول 2021

A: To extract the whole date expression, e.g., عاء 22 سبتمبر/أيلول 2021 try this:
(?<=>).*[^ -~]+\\s\\d+

where [^ -~] is shorthand for non-ASCII characters
To extract just the first part prior to the slash, e.g., أيلول 2021, try this:
[^ -~]+\\s\\d+


text:
Q: RSpec - Get Described Class How can I get the main class that is being described in RSpec 3? For example, I have the following spec:
describe User do
  describe "fetching" do
    describe "all" do
      subject { described_class.new }
    end
  end
end

subject currently returns something similar to User::fetching::all but I want it to return User only.

A: Not sure I'm understanding your question correctly, but as far as I can see, if you just want to get the class name constant within your test, just using described_class (without .new) should get you what you want:
class User; end

describe User do
  subject { described_class }
  it { is_expected.to eq(User) }
end


text:
Q: C++ std::list: Erasing / removing elements while iterating
Possible Duplicate:
Can you remove elements from a std::list while iterating through it?

I have a loop in a function, that iterates over an std::list from begin to end.
In each cycle, I perform some checks and maybe do a few manipulations on the current list entry, and in some cases I want to remove it from the list.
Now, as expected my iterator gets invalidated.

*

*Is there any way to work around this, to remove elements from a list while iterating over it?

A: Catch the return value of erase and use it as your iterator. The return value is an iterator to the next valid location after the erasure.
if(ShouldErase)
{
    iter = list.erase(iter);
}
else
{
    ++iter;
}

Reference
Excerpt:
Return value
A bidirectional iterator pointing to the new location of the element that followed the last element erased by the function call, which is the list end if the operation erased the last element in the sequence.

A: Use postfix increment.
list.erase(it++);

it is increased, so it no longer refers to the erased element, then the previous value of it is given to list.erase. Make sure that you either do list.erase(it++) or ++it in your loop - doing both will skip elements and potentially increment past end of the list.

A: Have you considered using the list::remove_if algorithm?


text:
Q: How to load pages inside split view content's frame passing parameters on UWP? Here is my MainPage.xaml
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BibleApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Domain="using:BibleApp.Domain"
x:Class="BibleApp.MainPage">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <RelativePanel>
            <Button Name="HamburgerButton"
                    FontFamily="Segoe MDL2 Assets"
                    Content="" FontSize="14"
                    Click="HamburgerButton_Click"/>
        </RelativePanel>

        <SplitView Name="MySplitView"
                   Grid.Row="1"
                   DisplayMode="CompactOverlay"
                   OpenPaneLength="200"
                   CompactPaneLength="34"
                   HorizontalAlignment="Left">
            <SplitView.Pane>
                <ListBox Name="IconsListBox" SelectionMode="Single" SelectionChanged="IconsListBox_SelectionChanged">
                    <ListBoxItem Name="Biblia">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets" Text="" FontSize="18"/>
                            <TextBlock Text="Bíblia" FontSize="12" Margin="15,0,0,0"/>
                        </StackPanel>
                    </ListBoxItem>

                    <ListBoxItem Name="PesquisarPalavraChave">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets" Text="" FontSize="18"/>
                            <TextBlock Text="Pesquisar palavra chave" FontSize="12" Margin="15,0,0,0"/>
                        </StackPanel>
                    </ListBoxItem>

                    <ListBoxItem Name="PesquisarAssunto">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontFamily="Segoe MDL2 Assets" Text="" FontSize="18"/>
                            <TextBlock Text="Pesquisar assunto" FontSize="12" Margin="15,0,0,0"/>
                        </StackPanel>
                    </ListBoxItem>
                </ListBox>
            </SplitView.Pane>
            <SplitView.Content>
                <Frame Name="MyFrame"/>
            </SplitView.Content>
        </SplitView>
    </Grid>
</Page>

Here is it's code behind of MainPage:
private void IconsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MyFrame = this.Frame;
    if (Biblia.IsSelected) { Frame.Navigate(typeof(View.BiblePage), bible);}
    else if (PesquisarPalavraChave.IsSelected) {Frame.Navigate(typeof(View.SearchWordPage));}
    else if (PesquisarAssunto.IsSelected) { Frame.Navigate(typeof(View.SearchMatterPage)); }
}

Here is BiblePage OnNavigatedTo event:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    bible = (Bible)e.Parameter;
}

The problem is that BiblePage's "OnNavigatedTo" evento is not triggered so I can't transport my "bible" variable from MainPage to BiblePage.
When I do this procedure outside the splitview's content it works perfectly.
How can I load xaml pages inside my MainPage's splitview content passing parameters?

A: Please perform the following test // just tested and didn't get any issue.
1/ MainPage.xaml
<Page
x:Class="App3.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App3"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <SplitView DisplayMode="Inline" Background="Black" IsPaneOpen="True" OpenPaneLength="360" >
        <SplitView.Pane>
            <Button Content="GoToPage" Click="GoToPage_Click" Foreground="White"/>
        </SplitView.Pane>
        <SplitView.Content>
            <Frame x:Name="contentFrame"/>
        </SplitView.Content>
    </SplitView>
</Grid>
</Page>

2/ MainPage.xaml.cs
namespace App3
{
/// <summary>
/// Une page vide peut être utilisée seule ou constituer une page de destination au sein d'un frame.
/// </summary>
public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private void GoToPage_Click(object sender, RoutedEventArgs e)
    {
        contentFrame.Navigate(typeof(SecondPage), new Params() { MyProperty = 42 });
    }
}

public class Params
{
    public int MyProperty { get; set; }
}
}

3/ SecondPage.xaml.cs
namespace App3
{

public sealed partial class SecondPage : Page
{
    public SecondPage()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        Params result = (Params)e.Parameter;
        base.OnNavigatedTo(e);
    }
}
}

A: I think the problem is in your BiblePage as the code should work OK.
I created the following GitHub repo based on your code samples: https://github.com/mikoskinen/uwp-frame-datapassing.
If you clone the code and run the app, you can see that the OnNavigatedTo is executed and the parameter is passed to the SecondPage correctly. This works in both Windows 10 Mobile Emulator and on local machine.

Couple things to check from your code:

*

*Make sure that you create the BiblePage using the Blank Page template

*Make sure that your BiblePage's XAML contains the x:Class attribute.

A: First you shoud use x:Name instead of Name in your XAML to declear a nama of an element.
And since you declear a name in your .xaml, you can directly access it in .xaml.cs by it's name, like:

var frame=this.MyFrame;

And importantly, this.Frame refers to the Frame that hosts this page,which  in this case it's RootFrame. So here is some key points that helps you:

*

*A page can place many frames;

*Any frames can be used to navigate to a new page just as: MyFrame.Navigate(typeof(NewPage),null);

*So a page could be inside a page;

A: Actually I had an piece of code executing on my BiblePage's constructor that was trying to use the variable passed as parameter before it was instanciated by the "OnNavigatedTo" event.
This way I was getting an error on other function before the "OnNavigatedTo" event gets triggered.
Thanks a lot.


text:
Q: Angular redirect to an empty page after the button is clicked I have a home  page with  one button , when the user click in the button  the user must be redirected to another page.
I try to make it like this but nothing happen when i click the button:
app.component.ts

import { Component } from '@angular/core';
import {Router} from '@angular/router'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'SaveWorld';
  constructor(private router:Router){}

 onClick(){
this.router.navigateByUrl('/saveWorld');
   }
}

Button code :
<button  click)="onClick()"type="button" class="button" >Make a change</button>

routes
import {NgModule} from  '@angular/core';
import {Routes,RouterModule} from  '@angular/router';
import {HomePageComponent} from  '../app/home-page/home-page.component'

const routes:Routes=[

     {path:'HomePage',component:HomePageComponent},
    {path:'saveWorld',component:SaveWorldComponent},
    {path:'',redirectTo:'/HomePage',pathMatch:'full'}
];

@NgModule({
    imports:[RouterModule.forChild(routes)],
    exports:[RouterModule]
})
export class AppRoutingModule {}

Can you please help me?
Update:
Now when  i click the button  works but not how i want to work,didn't redirect me to a new empty page.
https://i.stack.imgur.com/QYSMw.jpg

A: You have typo in your path/goto. Change it to HomePage or homePage, but not mixed.

A: You have to add <router-outlet></router-outlet> in your app.component.html.
Take a look on this https://angular.io/guide/router, it might help you.


text:
Q: Using correct IP with PHP I know that there are already a lot of questions about this but I didn't find any answers that suits me...
I am creating a site where you can identify yourself to access a specific page. I am doing the authentication with Angular (so, by calling a REST API). I'm planning to use SSL to avoid sniffing but I'd like to prevent a user to make a tons of call to the REST API to find the password of someone (using brute force for example).
So I told myself that I could simply put a maximum number of attempt by 15' for a specified account, but I don't want an account to be blocked for the real user because someone else is trying to hack it. So I'd like to identify attempts with the IP address of the user but apparently, the only IP I can trust is $_SERVER["REMOTE_ADDR"] but I also read that if the user uses a proxy, the IP will be the proxy one so it's not really what I want. I guess that a good hacker could easily change its proxy IP and then be able to resume his attack...
So what would be the best way to prevent that ?


text:
Q: select first sql I have the following selection:
$selectSql2 = "SELECT FIRST(selector_buttongroup_classes) AS data_car_type
               FROM cars WHERE selector_isactive = 1 AND publish = 1;";

I know selector_buttongroup_classes has data because I use it in another array.  But it is returning a value of null for each data_car_type in the array when I return it to my function.
So I am assuming the issue has to do with using FIRST??

A: If you are talking about sql, you have mistaken it with First() function in MS Access. There are no First() function in SQL. I think you want to get the first record of specified column.
So the workaround in sql is use TOP as follows
$selectSql2 = "SELECT TOP 1 selector_buttongroup_classes AS data_car_type FROM cars WHERE selector_isactive = 1 AND publish = 1;";

I guess this is what you are looking for

A: I am using MySQL,  For each row of about 100 rows, I need the first item in a list of items inside a column in a table.  So if the column in the first row contained         honda convertible four-wheel drive
I would need to pick off Honda.  And if the next row and same column contained
mazda hardtop two-wheel drive
I would need to pick off mazda.
I was trying to do it in the ajax call which is where my select call above came in.  But perhaps a better solution would be to do it in the function that gets the data after the return.  Since one of the items I am returning is all of the data in that particular column (in addition to other columns in the array).  The column is selector_buttongroup_classes.  Here is my function:
displayCars();

function displayCars () {

    $.ajax({
        type : 'GET',
        url : '/modules/crm/selector-ajax.php',
        data : {
            'action' : 'get-images'
        },
    dataType: 'json',
    success : function(data) {
       var resultArray = data.isotopecubes;
       var resultArray2 = data.isotopecubes2;
       var selectorDiv = $('#boat_isotope_gallery');
       var divHtml = '';

          var i = 0;

          for (i = 0; i < resultArray.length; i++) {

              divHtml +=  "

" + resultArray[i].product_name + "

";
          }

        selectorDiv.html(divHtml);
    },
    error : function(err) {
        console.log('ajax failure');
    }
});

}
}); // end of document ready


text:
Q: How to solve linux subdirectories number limit? I have a website which will store user profile images. Each image is stored in a directory (Linux) specific to the user. Currently I have a customer base of 30+, which means I will have 30+ folders. But my current Linux box (ext2/ext3) doesn't support creating more than 32000 directories. How do I get past this?  Even YouTube guys have got the same problem, with video thumbnails.  But they solved it by moving to ReiserFS. Can't we have a better solution?
Update:When asked in IRC, people were asking about upgrading it to ext4, which has 64k limit and of course you can even get past that too. Or kernel hacking to change the limit.
Update:How about splitting the user base into folders based on the userid range. Meaning 1-1000 in one folder, 1000-2000 in the other like that. This seems to be simple. What do you say, guys?
Frankly, isn't there any other way?

A: If you are bound to ext2/ext3 the only possibility I see is to partition your data.
 Find a criterion that splits your data into manageable chunks of similar size.
If it's only about the profile images I'd do:

*

*Use a hash (e.g SHA1) of the image

*Use the SHA1 as file and directory name

For example the SQUID cache does it this way:
f/4b/353ac7303854033
Top level directory is the first hex-digit, second level is the next two hex-digits,
and the file name is the remaining hex-digits.

A:
Cant we have a better solution?

You do have a better solution - use a different filesystem, there are plenty available, many of which are optimised for different tasks. As you pointed out ReiserFS is optimised for handling lots of files in a directory.
See here for a comparison of filesystems.
Just be glad you're not stuck with NTFS which is truly abysmal for lots of files in a directory. I'd recommend JFS as a replacement if you don't fancy using the relatively new (but apparently stable) ext4 FS.

A: That limit is per-directory, not for the whole filesystem, so you could work around it by further sub-dividing things. For instance instead of having all the user subdirectories in the same directory split them per the first two characters of the name so you have something like:
top_level_dir
|---aa
|   |---aardvark1
|   |---aardvark2
|---da
|   |---dan
|   |---david
|---do
    |---don

Even better would be to create some form of hash of the names and use that for the division. This way you'll get a better spread amongst the directories instead of, with the initial letters example, "da" being very full and "zz" completely empty. For instance if you take the CRC or MD5 the name and use the first 8 bits you'll get somethnig like:
top_level_dir
|---00
|   |---some_username
|   |---some_username
|---01
|   |---some_username
...
|---FF
|   |---some_username

This can be extended to further depths as needed, for instance like so if using the username not a hash value:
top_level_dir
|---a
|   |---a
|       |---aardvark1
|       |---aardvark2
|---d
    |---a
    |   |---dan
    |   |---david
    |---o
        |---don

This method is used in many places like squid's cache, to copy Ludwig's example, and the local caches of web browsers.
One important thing to note is that with ext2/3 you will start to hit performance issues before you get close to the 32,000 limit anyway, as directories are searched linearly. Moving to another filesystem (ext4 or reiser for instance) will remove this inefficiency (reiser searches directories with a binary-split algorimth so long directories are handled much more efficiently, ext4 may do too) as well as the fixed limit per directory.

A: I've hacked together a small web gallery, where I ended up with a variation of this problem; I "only" had ~30.000 images in the cache directory, which turned out to be quite slow (ext2 uses linked lists for directory indices, as I remember it).
I ended up doing something along these lines:
def key2path(key):
    hash = md5(key)
    return os.path.join(hash[0], hash[1], key)

This will partition the data in 256 directories, which gives a fast directory lookup for each of the three levels.

*

*I've chosen to use MD5 over SHA-1, as MD5 guarantees a different output if you change any 12 bits of 32, so I find it a nice fit to hash user names, directories and other short stuff. And it's fast, too...

*I do not include the entire hash, as it will produce way too many directories and effectively trash the disk-cache over and over.

A: Is the profile image small?  What about putting it in the database with the rest of the profile data?  This might not be the best option for you, but worth considering...
Here is a ( older ) Microsoft whitepaper on the topic: To BLOB or not to BLOB.

A: Generally you want to avoid having directories with a large number of files/directories in it.  Primary reason is that wildcard expansion on the command line, will result in "Too many arguments" errors resulting in much pain when trying to work with these directories.
Go for a solution that makes a deeper but narrower tree, e.g. by creating subfolders like others have described.

A: Not an immediate answer to your problem, but something to watch for future reference is the OpenBSD linked project called 'Epitome'
Epitome is an engine which provides Single Instance Storage, Content Addressable Storage and Deduplication services.
All of your data is stored in a data store as hashed blocks, removing non-unique blocks to cut down on space usage, and allows you to essentially forget about the storage mechanism as you can simply request the content from the data store by UUID.
Epitome is currently experimental, but something to watch for the future.

A: We had a similar problem, the solution - as mentioned previously - is to create a hierarchy of directories.
Of course if you have a complex application which relies on a flat directory structure, you'll probably need a lot of patching. So it's good to know that there is a workaround, use symlinks which doesn't have the mentioned 32k limit. Then you have plenty of time to fix the app...

A: Why not use a timestamp approach, and then have an overflow option.
For Example
So lets say your timestamp is: 1366587600
Omit the last 2 digits (or else it just gets slightly ridiculous). Separate the stamp into sets of 4 (the directory count shouldn't reach more than 9999 - if you want to you could separate it differently).
This should leave you with something like this:
/files/1366/5876/

Then also check the amount within the dir before uploading, if it's getting a large number of uploads (i.e. 32000 + per 100 secs), then iterate the directory by the second or a letter, for example:
/files/1366/5876/a/file.txt

or
/files/1366/5876/00/file.txt

Then log the timestamp + letter or the full path code into a db along with the user and you should be set.
pathstamp: 1366587600 or 13665876a (if your using letters).
This does end up with a large number of directories, but it can be really useful for handling file revisions. For example, if a user wants to use a new profile picture, you still have the old timestamped version of the older one in-case they wish to undo the changes (its not just over-written).

A: I'd suggest deciding how many maximum subdirectories you want to (or can) have in the parent folder.
Then you need to convert your user id so they start from 1.
Then you can do:
modulo = currentId % numberOfSubdirectories
modulo will now contain your subdirectory number that will be never greater than numberOfSubdirectories you have chosen.
Do whatever you want with modulo, hash it, for example.
Also this way subdirectories will be filled linearly.


text:
Q: Response Object coming null for get request for rest api I am trying to implement nexmoverify REST API for OTP implementation but response object comig null.I checked in Postman and able to get stringify object from of response object.
var app = angular.module('angularjs-starter', []);
app.config(['$httpProvider', function($httpProvider) {
   $httpProvider.defaults.useXDomain = true;
   delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);

app.controller('MainCtrl', function($scope, $http) {

   $scope.addNewChoice = function () {
      console.log('aaaa');
      $scope.res=$http.get("https://api.nexmo.com/verify/json?api_key=56a9b1af&api_secret=XXXXXX&number=919650298011&brand=stayuncle").
         success(function (response) {
            $scope.res = response.data;

         }).
      error(function (response){
            console.log(response);

            $scope.res = response.data;

         });

   };

Code Flow: code flow coming to error() section and then printing null in web console.
Error :
Response object coming null as well as getting this error in web console

XMLHttpRequest cannot load https://api.nexmo.com/verify/json?api_key=56X9b1af&api_secret=d3XXXX&number=91XX50298011&brand=stayuncle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Can someone help me to solve this problem.

A: The error tells you the problem.

No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8080' is therefore not allowed
  access.

The REST API server is not configured for CORS, therefore, you are not allowed to access that URL from any origin other than the https://api.nexmo.com/ domain. However, aren't you supposed to be using JSONP?
Reference on CORS
Reference on JSONP


text:
Q: Soundex or Metaphone algorithm for typos in search term In our search we need to return results which match searched term with Levensthein distance max of 2. The problem is that we need to apply Levensthein distance algorithm for every row in table which has millions of rows and then query is very slow.
SOUNDEX and Metaphone are great because they produce a hash which can be stored in database and compared to searched string. But they're phonetical based not 'typo' based. They work for some cases, but not for all.
I am aware that it does not seem to be possible to generate Levensthein hash and store it, because we do not know the search term.
So the question is whether is there any algorithm like SOUNDEX or Metaphone which is 'typo' oriented.
We use MariaDB database and PHP so implementing any should be feasible in PHP.


text:
Q: Change gridview dataitem property in row databound event I would like to do a string replace on one of a gridview's dataitem properties in the rowdatabound event (i.e. I would like for it to show up in the gridview slightly different than what it actually is).
in the rowdatabound event I have the following:
???? = (DataBinder.Eval(rowData, "SummaryId") as string).Replace("&", "").Replace("@", "");

What should the left half of the expression be?

A: I never do it that way but, if you have to, I would say:
if (e.Row.RowType == DataControlRowType.DataRow)
{
    e.Row.Cells[n].Text = e.Row.Cells[n].Text.Replace("&", "").Replace("@", "");
}

where n is the column index.


text:
Q: Good example of Spring Configuration using java.util.prefs or Commons Configuration One application I'm working on has several URLs and other information that is instance specific.  The first pass uses a typical Spring PropertyPlaceholderConfigurer with a properties file:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:application.properties"/>
</bean>

The main issue with this is of course the property file is an artifact that must be checked in, and for starting a new instance would require updating that artifact.  For a streamline deployment, I would like to have the ApplicationContext bootstrap itself based on database table(s).  I have seen solutions like this forum post, does anyone here know of better tools or is this defacto approach to this problem?  I would also like to be able to update/reload the settings at runtime using JMX or other facilities, but having to restart the app after changes to the database would still be a better solution to the current one.

A: The way we did it was to put some configuration information in the environment and then pull the relevant info from there.
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="searchSystemEnvironment" value="true" />
</bean>

If configuration changes then the app will need to be restarted. Can also put all the different configurations into the environment and nest the variables like the following:
<bean id="db" class="org.DataSource"
        p:databaseServer="${${MODE}_DBSERVER}"
        p:databaseName="${${MODE}_DBNAME}" />

where $MODE = dev, qa, etc.


text:
Q: MVC Table sorting I'm currently playing around with the Tablesorter jQuery plugin in one of the sites I'm working on. It seems to be fairly straight forward, but for some reason the headers don't sort. Clicking on them doesn't even produce any visible response (the cursor doesn't change). I suspect this may have something to do with the fact that the table is dynamic in that it is populated by data pulled from a database table (edit: confirmed that this is not the issue by testing using static, manually entered data). The other possibility is that my jQuery code is in the wrong location or there's a problem with my reference.
Any ideas?
The project is done in MVC, by the way.
View Page Source result:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>

    Execution History

</title><link href="../Content/Site.css" rel="stylesheet" type="text/css" />

Execution History

                Run ID

                Date Ran

                Ran By

                Run Time

                Result

                    1

                    7/25/2011 11:25:01 AM

                    Laura

                    145.49849999696

                    PASS

                    2

                    8/3/2011 6:23:01 PM

                    Laura

                    140.616000004113

                    PASS

                    3

                    8/3/2011 6:26:00 PM

                    Laura

                    141.592500001192

                    PASS

                    4

                    8/4/2011 8:04:00 PM

                    Kevin

                    260.725500002503

                    FAIL

                    5

                    10/5/2011 4:05:50 PM

                    Kevin

                    2749796.658

                    PASS

                    6

                    10/5/2011 5:31:18 PM

                    Kevin

                    2777489.2215

                    PASS

A: Found the solution. It was indeed a file reference problem. The code works fine on localhost, but I do most of my testing on IIS since this is a deployed site. Thus, a mapping is required for IIS to actually find the referenced jquery scripts. Url.Content does exactly this.


text:
Q: Is it possible to use the mousedown and mouseup event on the same button? This project involves controlling a toy car over LAN.
On my html page, there are 5 "buttons";up, down, left, right, stop.
My code works like this: Say the user clicks on "up", a value gets sent to a php page for processing and the processed string gets printed on another php page for an arduino to read.
For the car to stop, the user has to click on stop.

<form name="motorform" action="motorboardprocess.php" method="post">

Motor Shield

    <input id="forward" type="image" src="up.png" name="forward">

    <input id="left" type="image" src="left.png"  name="left">
    <input id="stop"type="image" src="stop.png"  name="stop">
    <input id="right" type="image" src="right.png" name="right">

    <input id="backward" type="image" src="down.png" name="backward">

</form>

and the said php...
<?php

if (isset($_POST['forward_x'], $_POST['forward_y'])){
    $myFile = "mtboardcom.php";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = "<?php\n";
    fwrite($fh, $stringData);
    $stringData = "echo ".'"<forward>"'."\n";
            fwrite($fh, $stringData);
    $stringData = "?>\n";
            fwrite($fh, $stringData);
    fclose($fh);
}

else if (isset($_POST['left_x'], $_POST['left_y'])){
    $myFile = "mtboardcom.php";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = "<?php\n";
    fwrite($fh, $stringData);
    $stringData = "echo ".'"<left>"'."\n";
            fwrite($fh, $stringData);
    $stringData = "?>\n";
            fwrite($fh, $stringData);
    fclose($fh);
}
//and so on.....

the arduino reads:
<?php
    echo "<forward>"
?>

So the question is, how do I make use of the mousedown and mouseup events from jquery
to remove the stop 'button'.
Or another scenario: the user holds down the button to move the car and releases the button to stop the car.
On mousedown, a string 'forward' is read by the arduino.
mouseup on the same button, string 'stop' is read by the arduino.

A: Of course you can subscribe to two different events in Javascript. just hook into the events:
var field = document.getElementsById('#idName');

field.onmousedown = function(){

}

field.onmouseup = function(){

}

Or for jquery:
var field = $('#idName');

field.mousedown(function(){

}).mouseup(function(){

});

A: Using jQuery, this is very simple:
$('#element').mousedown(function (event) {
    // process mouse down
});
$('#element').mouseup(function (event) {
    // process mouse up
});

You can also chain them with
$('#element').mousedown(function(event) {
    /* code */
}).mouseup(function (event) {
    /* code */
});

During these events, you can ping your URL with a $.ajax call. But do note that because AJAX is asynchronous, you could be looking at race conditions if you're not careful. Because they are coming from 1 client, you should be fine, but there could be other issues that could cause slight delays or differences in response times.

A: You can use the following jquery code. Added a demo here
    <!DOCTYPE html>

Click

A: Yes, you can catch both mousedown and mouseup events, but you need to use AJAX calls to send the information to the server so that you don't do a postback that reloads the page.
Also, you don't automatically get a mouseup event that corresponds to each mousedown event. The user might move the mouse outside the button before releasing the button, and even move it to a different button. You should store which button was pressed in a Javascript variable, and catch the mouseup event for the entire page instead of for the buttons, and send a stop signal if the last click was on a button.