text:
Q: replacing args in docker file is not working I have the following docker file
FROM alpine:3.10 as builder

# CAMUNDA VARIABLES
ARG VERSION=7.12.0
ARG DISTRO=tomcat
ARG SNAPSHOT=false
ARG EE=true

#Understand difference between ARG and ENV:
#https://vsupalov.com/docker-arg-vs-env/

#AZURE SQL VARIABLES, DEFAULT SETTINS ARE DEV DB Environment
#Be sure database and tables are created upfront
#Use docker build . -t xx/camundawithbasicdev
#Use docker build . -t xx/camundawithbasicauthqa --build-arg SQLSERVER=a_value DBPASSWORD=a_value DBUSERNAME=a_value
#Use docker build . -t xx/camundawithbasicauthprod --build-arg some_variable_name=a_value
#And replace variables as needed.

ARG SQLSERVER=xx
ARG DBPASSWORD=Hxx
ARG DBUSERNAME=xx
ARG DATABASENAME=xx

RUN apk add --no-cache \
        ca-certificates \
        maven \
        tar \
        wget \
        xmlstarlet

COPY settings.xml download.sh camunda-tomcat.sh camunda-wildfly.sh  /tmp/

RUN /tmp/download.sh

#Enable Basic AUTH
COPY web.xml /camunda/webapps/engine-rest/WEB-INF/web.xml

##### FINAL IMAGE #####

FROM alpine:3.10

ARG VERSION=7.12.0

ENV CAMUNDA_VERSION=${VERSION}
ENV DB_DRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver
ENV DB_URL=jdbc:sqlserver://${SQLSERVER}.database.windows.net:1433;database=${DATABASENAME};user=${DBUSERNAME};password={DBPASSWORD};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
ENV DB_USERNAME=${DBUSERNAME}
ENV DB_PASSWORD=${DBPASSWORD}
ENV DB_CONN_MAXACTIVE=20
ENV DB_CONN_MINIDLE=5
ENV DB_CONN_MAXIDLE=20
ENV DB_VALIDATE_ON_BORROW=true
ENV DB_VALIDATION_QUERY="SELECT 1"
ENV SKIP_DB_CONFIG=
ENV WAIT_FOR=
ENV WAIT_FOR_TIMEOUT=120
ENV TZ=UTC
ENV DEBUG=TRUE
ENV JAVA_OPTS="-Xmx768m -XX:MaxMetaspaceSize=256m"
ENV JMX_PROMETHEUS=false

EXPOSE 8080 8000

# Downgrading wait-for-it is necessary until this PR is merged
# https://github.com/vishnubob/wait-for-it/pull/68
RUN apk add --no-cache \
        bash \
        ca-certificates \
        openjdk11-jre-headless \
        tzdata \
        tini \
        xmlstarlet \
    && wget -O  /usr/local/bin/wait-for-it.sh \
      "https://raw.githubusercontent.com/vishnubob/wait-for-it/a454892f3c2ebbc22bd15e446415b8fcb7c1cfa4/wait-for-it.sh" --no-check-certificate \
    && chmod +x /usr/local/bin/wait-for-it.sh

RUN addgroup -g 1000 -S camunda && \
    adduser -u 1000 -S camunda -G camunda -h /camunda -s /bin/bash -D camunda

# end ssh config
WORKDIR /camunda
USER camunda

#MSSQL SERVER JDBC DRIVER INSTALL
COPY mssql-jdbc-7.2.2.jre11.jar /camunda/lib/

ENTRYPOINT ["/sbin/tini", "--"]
CMD "./camunda.sh"

COPY --chown=camunda:camunda --from=builder /camunda .

However when I run the image, it looks like the variables are not replaced on the connection string part
what am I missing?

A: You're setting the arguments on a different stage. As far as I know, it's not possible to pass them between stages. For example:
This won't work
FROM alpine:3.10 as builder

ARG TEST1=1234

FROM alpine:3.10
ENV TEST2=blablah-${TEST1}

if you print TEST2 you'll get blablah-
This will:
FROM alpine:3.10 as builder

ARG TEST1=1234

FROM alpine:3.10
ARG TEST1=98765
ENV TEST2=blablah-${TEST1}

if you print TEST2 you'll get `blahblah-98765
However, I would strongly advice against this way as it'll store your passwords and so on as default env vars in the Docker image you're building. I would pass the connection details when you run docker either with docker run -e TEST1=1234 or even better, with a docker-compose file.
I would have Dockerfile like this one (very simplified, only with the env vars) Normally, when I need to construct variables like that I do so in the entrypoint.sh
So my entrypoint looks like:
#!/bin/bash

export DB_URL="jdbc:sqlserver://${SQLSERVER}.database.windows.net:1433;database=${DB_NAME};user=${DB_USERNAME};password=${DB_PASSWORD};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=0;"

echo $DB_URL

echo "Running: '$@'"
exec $@

My Dockerfile looks like:
FROM alpine:3.10 as builder

ARG VERSION
ARG DISTRO
ARG SNAPSHOT
ARG EE

FROM alpine:3.10
ARG VERSION

ENV CAMUNDA_VERSION=${VERSION}
ENV DB_DRIVER=com.microsoft.sqlserver.jdbc.SQLServerDriver

ENV DB_CONN_MAXACTIVE=20
ENV DB_CONN_MINIDLE=5
ENV DB_CONN_MAXIDLE=20
ENV DB_VALIDATE_ON_BORROW=true
ENV DB_VALIDATION_QUERY="SELECT 1"
ENV SKIP_DB_CONFIG=
ENV WAIT_FOR=
ENV WAIT_FOR_TIMEOUT=120
ENV TZ=UTC
ENV DEBUG=TRUE
ENV JAVA_OPTS="-Xmx768m -XX:MaxMetaspaceSize=256m"
ENV JMX_PROMETHEUS=false

RUN apk update && apk add bash

ADD entrypoint.sh /
ENTRYPOINT ["/entrypoint.sh"]

And my docker-compose.yml
version: '2.3'

services:
  so-example:
    image: stackoverflow-example
    build:
      context: .
      args:
        - VERSION
        - DISTRO
        - SNAPSHOT
    environment:
      - SQLSERVER
      - DB_USERNAME
      - DB_PASSWORD
      - DB_NAME

Then, to build the new image I run:
docker-compose build --build-arg VERSION=7.12.0 --build-arg DISTRO=tomcat --build-arg SNAPSHOT=false --build-arg EE=true
When I need to run it I export the values I need. For instance:
export SQLSERVER=myhost
export DB_USERNAME=db_user
export DB_PASSWORD=mysecretpassword
export DB_NAME=mydb

And then run it with compose. For example, if I run
docker-compose run so-example env
you should see that DB_URL is
jdbc:sqlserver://myhost.database.windows.net:1433;database=mydb;user=db_user;password=mysecretpassword;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=0;
I hope this helps


text:
Q: How to Implement LockService in Google App Script The Right Way? Currently, I'm trying lockservice in Google App Script to handle concurrency on my webapp. However, when I implement it, it did not work.
Description of my webapp:

Whenever a user click on the button, it will get the website address value in the google sheet and open a new window to go to the website. Then, it will update the value in my google sheet with the value of a new website address.
on this webapp, it will cycle through 3 websites Google -> Youtube -> Facebook
The problem:
When I tried testing it for concurrency with clicking the button fast, it will return the same website. For example, if I clicked it twice, it will open 2 new window of Google, but the value in the google sheet will be updated to Facebook, which skip the Youtube.
I tried implement lockservice but it did not work, maybe I implement it wrongly.
this is my HTML code:

    <base target="_top">

Please Click Below

    <button class="button" id = "btn" type="submit" >Open Window</button>

My code.gs:
    var url = "google sheet url";
var web = "";

function doGet(e) {

  let tmp = HtmlService.createTemplateFromFile("index");
  let output = tmp.evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1');
  return output;

}

function setWebsite () {
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("website");
  web = ws.getRange(1,1,1,1).getValue();
  var lock = LockService.getScriptLock(); //del
  lock.tryLock(5000); //del
  if (lock.hasLock()) { //del
    if (web === "Google") {
      ws.getRange(1,1,1,1).setValue("Youtube");
    }
      else if (web === "Youtube") {
      ws.getRange(1,1,1,1).setValue("Facebook");
    }
      else {
      ws.getRange(1,1,1,1).setValue("Google");
    }

    var xs = ss.getSheetByName("data");
    xs.appendRow([new Date(), web]);
    lock.releaseLock(); //del
    }
  } //del

function getWebsite() {
  var lock = LockService.getScriptLock();
  lock.tryLock(5000); // wait 5 seconds try to get lock

  if (lock.hasLock()) {
  var ss = SpreadsheetApp.openByUrl(url);
    var ws = ss.getSheetByName("website");
    var web = ws.getRange(1,1,1,1).getValue();
    lock.releaseLock();
    return web;
    }
  }

// function getWebsite() {
//   var lock = LockService.getScriptLock();
//   try {
//     lock.waitLock(5000); // wait 5 seconds try to get lock
//   } catch (e) {
//     Logger.log('Could not obtain lock after 5 seconds.');
//   }
//     Utilities.sleep(1000);
//     var ss = SpreadsheetApp.openByUrl(url);
//     var ws = ss.getSheetByName("website");
//     var web = ws.getRange(1,1,1,1).getValue();
//     lock.releaseLock();
//     return web;
//     //lock.releaseLock();
//     }

ps. I tried two different ways (on the comment part in code.gs) that I can find on Stackoverflow and youtube but still no success.
Please help. Thank you.

A: I thought that in your script, when the button is clicked, google.script.run.withSuccessHandler(openWebsite).getWebsite() is run and also google.script.run.setWebsite() is run in the function openWebsite. In this case, the LockService is used for each function of getWebsite() and setWebsite(). I thought that this might be the reason of your issue. So, in your script, how about the following modification? In this modification, one LockService is used for the functions of getWebsite() and setWebsite().
HTML&Javascript side:
Please modify openWebsite(web) in your Javascript side as follows.
From:
google.script.run.setWebsite();

To:
// google.script.run.setWebsite();

*

*In this modification, google.script.run.setWebsite(); is removed.

Google Apps Script side:
Please modify getWebsite() in your Google Apps Script side as follows.
From:
var web = ws.getRange(1,1,1,1).getValue();
lock.releaseLock();

To:
var web = ws.getRange(1, 1, 1, 1).getValue();
setWebsite(); // Added
lock.releaseLock();

*

*In this modification, google.script.run.setWebsite(); is removed.

Note:

*

*When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

*You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing Zimbra email routing I am an experienced Exim user and just recently testing Zimbra Open Source, and I am loving it already.
However, I am used to this command whenever I wanted to test email routing in the email server, whether I am testing for the routing of local users, local email addresses and external email addresses:
root@localhost# exim -bt alias@localdomain.com
user@thishost.com
    <-- alias@localdomain.com
  router = localuser, transport = local_delivery

root@localhost# exim -bt user@thishost.com
user@thishost.com
  router = localuser, transport = local_delivery

root@localhost# exim -bt user@remotehost.com
  router = lookuphost, transport = remote_smtp
  host mail.remotehost.com [1.2.3.4] MX=0

Got the above cheatsheet years ago from http://bradthemad.org/tech/notes/exim_cheatsheet.php.
How can I do this with Zimbra/Postfix? I am searching everywhere on how to do this, but couldn't found any.
Thanks!

A: Zimbra uses postfix for delivering the mail to external addresses. So you can use a lot of the commands on http://www.postfix.org/DEBUG_README.html
For example. Log in as the zimbra user and the command to give you a delivery report on a specific destination would be:
sendmail -bv micha@kovoks.nl

The result will be sent to the zimbra user, so you need to have the zimbra@ mail address configured in your system, for example as an alias on your own account.

A: Try this command
/usr/sbin/sendmail -bv address.

sendmail binary from postfix has special options -bv
-bv    Do not collect or deliver a  message.  Instead,  send  an  email
       report  after  verifying each recipient address.  This is useful
       for testing address rewriting and routing configurations.

This command also can be found in postfix documentation:

*

*Debugging your address manipulations.

*Debugging Postfix from inside
Excerpt from the page

Postfix version 2.1 and later can produce mail delivery reports for debugging purposes. These reports not only show sender/recipient addresses after address rewriting and alias expansion or forwarding, they also show information about delivery to mailbox, delivery to non-Postfix command, responses from remote SMTP servers, and so on.

Unlike utility from exim which give result in the stdout, postfix will send the report to user who invoke above command. Also zimbra will place sendmail binary in its unusual directory, so you must invoke it by issuing the full path command.
/opt/zimbra/postfix/sbin/sendmail -bv address

A: you can use telnet or sendmail commands from the zimbra user and keep checking the log output (/var/log/mail.log).


text:
Q: How to fully utilise server capacity for Node.js Web Apps Does the latest Node.js version(4.2.3) supports multi threading now? Hard to find useful answers as most relevant discussions are from years ago.
How would a node.js cloud server handle node.js Web App requests? Say a 2-Core server runs a node.js app, does that mean no matter how heavy the traffic is, they all go through via a single core and the other core is always idle?
If the answer is yes, any recommendations of some third party libs could possibly achieve multi-threading for node.js Web Apps?

Thanks for the helps. In addition to the above question. I adopted the cluster code into an Express.js web app, it turns out the else block is not executed in the below code section.
    var app = require('../app');
    var debug = require('debug')('NewExpress:server');
    var http = require('http');
    var cluster = require('cluster');
    var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {

    /**
     * Get port from environment and store in Express.
     */

    var port = normalizePort(process.env.PORT || '3000');
    app.set('port', port);

    /**
     * Create HTTP server.
     */

    var server = http.createServer(app);

    /**
     * Listen on provided port, on all network interfaces.
     */

    server.listen(port);
    server.on('error', onError);
    server.on('listening', onListening);
}

Any ideas how should I implement cluster in here?

A: You can use each of your cpus like this:
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  startServer();
}

Update
To give a fuller example, you can throw this in index.js:
var express = require('express');
var app = express();
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
} else {
  startServer();
}

function startServer() {
  var server = app.listen(3000, function () {
      var port = server.address().port;
      console.log('Example app listening at %s', port);
    });
}

run node index.js in a terminal to start it up.
and it will log this with my 8 cpu monster:
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000
Example app listening at 3000

Update 2
After seeing the question edit, I adapted your example. This should work
var http = require('http');
var express = require('express');
var app = express();
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    console.log('in else statement');
    var port = '3000';
    app.set('port', port);
    var server = http.createServer(app);
    server.listen(port);
}

and it should show this in the console
in else statement
in else statement
in else statement
in else statement
in else statement
in else statement
in else statement
in else statement

Let me know if this is not running for you.


text:
Q: find number of customers added each month customer_id  transaction_id    month  year
          1    3                7     2014
          1    4                7     2014
          2    5                7     2014
          2    6                8     2014
          1    7                8     2014
          3    8                9     2015
          1    9                9     2015
          4    10               9     2015
          5    11               9     2015
          2    12               9     2015

I am well familiar with R basics. Any help will be appreciated.
the expected output should look like following:
month   year  number_unique_customers_added
 7      2014     2
 8      2014     0
 9      2015     3

In the month 7 and year 2014, only customers_id 1 and 2 are present, so number of customers added is two. In the month 8 and year 2014, no new customer ids are added. So there should be zero customers added in this period. Finally in year 2015 and month 9, customer_ids 3,4 and 5 are the new ones added. So new number of customers added in this period is 3.

A: Using data.table:
require(data.table)

dt[, .SD[1,], by = customer_id][, uniqueN(customer_id), by = .(year, month)]

Explanation: We first remove all subsequent transactions of each customer (we're interested in the first one, when she is a "new customer"), and then count unique customers by each combination of year and month.

A: Using dplyr we can first create a column which indicates if a customer is duplicate or not and then we group_by month and year to count the new customers in each group.
library(dplyr)
df %>%
  mutate(unique_customers = !duplicated(customer_id)) %>%
  group_by(month, year) %>%
  summarise(unique_customers = sum(unique_customers))

#  month  year unique_customers
#  <int> <int>            <int>
#1     7  2014                2
#2     8  2014                0
#3     9  2015                3


text:
Q: Connect to Facebook chat using PHP? I'd like to make a bot that periodically logs into facebook's chat network and stores snapshots of the roster. I'm aiming for a dataset that can tell me which of my friends are online when / how often as a demonstration of the privacy risks of facebook.
Is there a library I can use to connect to Facebook's XMPP chat network using PHP?

A: There are several Jabber PHP client classes you can glean from:
http://www.google.com/search?q=php+jabber


text:
Q: finding the string between two sets of alternate strings with overlapping occurence I have a number of strings look like:
str1="Quantity and price: 120 units;the total amount:12000.00"
str2="Quantity:100, amount:10000.00"
str3="Quantity:100, price: 10000 USD"
str4="Parcel A: Quantity:100, amount:$10000.00,Parcel B: Quantity:90, amount:$9000.00"
strlist=[str1,str2,str3,str4]

I want to match tha amount $12000, $10000, 10000 in the first 3 strings and both $10000 and $9000.00 in the last string. However, in the first string there are both "price" and "amount". I thought by using "|"   regex would search from left to right, so I want regex to look "amount" first, if it is not presented then look for "price". I tried the following code:
amount_p = re.compile(r'(?:amount|price):(.*?)(?:USD|\.00)')
for i in strlist:
    amount=re.findall(amount_p,i)
    print(amount)
[' 120 units;the total amount:$12000']
['10000']
[' 10000 ']
['$10000', '$9000']

Somehow the regex ignored "amount" and only looked for "price" in the first string. Then I tried following:
amount_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')

which gives me
['12000']
['10000']
[' 10000 ']
['$9000']

In this case, regex only matched $9000 in the last string and ignored $10000. So my question is what is the function of .* at the begining and is there anyway to solve my problem? Looking for numbers doesn't work because in my actual data there are many other numbers in one text.
Thank you all in advance!!!!

A: With the first statement:
amount_p = re.compile(r'(?:amount|price):(.*?)(?:USD|\.00)')

You didn't group the string properly as you meant to do (i believe you meant to group by ':'), so you still had you string existing as one. You were only able to get your figures out  in str2 and str3 because '.USD' and '.00' came to your rescue.
With the second statement:
amount_p = re.compile(r'.*(?:amount|price):(.*?)(?:USD|\.00)')

You were able to split your strings properly using the ':'. As such, str1 one then looks like:

Portion1: "Quantity and price"
and
Portion2: "120 units;the total amount:12000.00"

and so you were able to extract your values.
You may view it as doing something like this:
strlist=[str1.split(';')[1],str2,str3,str4]

which when combined with your first pattern gives the same result as the second
Reference: https://www.tutorialspoint.com/python/python_reg_expressions.htm

A: You may use
re.findall(r'(?:price|amount):\s*\$?(\d+)(?:\.\d+|\s*USD)', text)

See the regex demo
Details

*

*(?:price|amount) - price or amount

*: - a colon

*\s* - 0+ whitespaces

*\$? - an optional dollar sign

*(\d+) - Group 1: one or more digits

*(?:\.\d+|\s*USD) -- a non-capturing group matching either . and 1+ digits or 0+ whitespaces and then USD substring.


text:
Q: C++ Excel::RangePtr range_dataFloat - Expression must be a pointer to a complete object type I am trying to export the below data to excel but it shows an error at the last line under range_dataFloat. This is the error I get:

Excel::RangePtr - Expression must be a pointer to a complete object type

The rest of the code is working and connected to excel, but the problem is with this part:
int SW1 [2] = { 0, 0 }; // South-West coordinate of the first square
int SE1 [2] = { 1, 0 }; // South-East coordinate of the first square
int NW1 [2] = { 0, 1 }; // North-West coordinate of the first square
int NE1 [2] = { 1, 1 }; // North-East coordinate of the first square

Excel::RangePtr range_dataFloat;

range_dataFloat = sheet_input -> GetRange (L"Coordinates");

int Square_Coordinates [i][j];

for ( i = 0 ; i < n_squares ; i++ ) // For loop to move to the next row
{
    int p = 1;

    // Changing the coordinates of the first square in each row
    SW1 [1] = i;
    SE1 [1] = i;
    NW1 [1] = i+1;
    NE1 [1] = i+1;

    range_dataFloat -> Item [p][p] = SW1[0];


text:
Q: pg gem not possible to be installed with bundle install or at all i'm trying to install pg gem. I'm a total beginner to ruby on rails and to programming at all. I'm trying to figure that error out since yesterday and already looked at many places for a solution. hope you can help me. thanks
using mac mountain lion
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
and used to use rails 4.0
Marcs-MacBook-Pro:smartforce marcboehle$ rails -v
Could not find pg-0.16.0 in any of the sources
Run bundle install to install missing gems.
I already tried:
Marcs-MacBook-Pro:smartforce marcboehle$ bundle install
Fetching gem metadata from http://rubygems.org/..........
Fetching gem metadata from http://rubygems.org/..
Resolving dependencies...
Enter your password to install the bundled RubyGems to your system:
Using rake (10.1.0)
Using i18n (0.6.5)
Using minitest (4.7.5)
Using multi_json (1.7.9)
Using atomic (1.1.13)
Using thread_safe (0.1.2)
Using tzinfo (0.3.37)
Using activesupport (4.0.0)
Using builder (3.1.4)
Using erubis (2.7.0)
Using rack (1.5.2)
Using rack-test (0.6.2)
Using actionpack (4.0.0)
Using mime-types (1.24)
Using polyglot (0.3.3)
Using treetop (1.4.15)
Using mail (2.5.4)
Using actionmailer (4.0.0)
Using activemodel (4.0.0)
Using activerecord-deprecated_finders (1.0.3)
Using arel (4.0.0)
Using activerecord (4.0.0)
Using bundler (1.3.5)
Installing coffee-script-source (1.6.3)
Installing execjs (2.0.0)
Installing coffee-script (2.2.0)
Using thor (0.18.1)
Using railties (4.0.0)
Installing coffee-rails (4.0.0)
Using hike (1.2.3)
Installing jbuilder (1.5.0)
Installing jquery-rails (3.0.4)
Installing json (1.8.0)
Installing pg (0.16.0)
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

    /usr/local/rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /usr/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for pg_config_manual.h... yes
checking for PQconnectdb() in -lpq... yes
checking for PQconnectionUsedPassword()... yes
checking for PQisthreadsafe()... yes
checking for PQprepare()... yes
checking for PQexecParams()... yes
checking for PQescapeString()... yes
checking for PQescapeStringConn()... yes
checking for PQescapeLiteral()... yes
checking for PQescapeIdentifier()... yes
checking for PQgetCancel()... yes
checking for lo_create()... yes
checking for pg_encoding_to_char()... yes
checking for pg_char_to_encoding()... yes
checking for PQsetClientEncoding()... yes
checking for PQlibVersion()... yes
checking for PQping()... yes
checking for PQsetSingleRowMode()... no
checking for rb_encdb_alias()... yes
checking for rb_enc_alias()... yes
checking for rb_thread_call_without_gvl()... yes
checking for rb_thread_call_with_gvl()... yes
checking for rb_thread_fd_select()... yes
checking for rb_w32_wrap_io_handle()... no
checking for PGRES_COPY_BOTH in libpq-fe.h... no
checking for PGRES_SINGLE_TUPLE in libpq-fe.h... no
checking for PG_DIAG_TABLE_NAME in libpq-fe.h... no
checking for struct pgNotify.extra in libpq-fe.h... yes
checking for unistd.h... yes
checking for ruby/st.h... yes
creating extconf.h
creating Makefile

make "DESTDIR="
compiling gvl_wrappers.c
compiling pg.c
pg.c:272:9: warning: implicit declaration of function 'PQlibVersion' is invalid in C99 [-Wimplicit-function-declaration]
        return INT2NUM(PQlibVersion());
               ^
In file included from pg.c:48:
In file included from ./pg.h:17:
In file included from /usr/local/rvm/rubies/ruby-2.0.0-p247/include/ruby-2.0.0/ruby.h:33:
/usr/local/rvm/rubies/ruby-2.0.0-p247/include/ruby-2.0.0/ruby/ruby.h:1167:21: note: instantiated from:
# define INT2NUM(v) INT2FIX((int)(v))
                    ^
pg.c:272:9: note: instantiated from:
        return INT2NUM(PQlibVersion());
               ^
pg.c:272:17: note: instantiated from:
        return INT2NUM(PQlibVersion());
                       ^
pg.c:375:48: error: use of undeclared identifier 'PQPING_OK'
        rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK));
                                                      ^
pg.c:375:56: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK));
                                                              ^
pg.c:377:52: error: use of undeclared identifier 'PQPING_REJECT'
        rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT));
                                                          ^
pg.c:377:60: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT));
                                                                  ^
pg.c:379:57: error: use of undeclared identifier 'PQPING_NO_RESPONSE'
        rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE));
                                                               ^
pg.c:379:65: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE));
                                                                       ^
pg.c:381:56: error: use of undeclared identifier 'PQPING_NO_ATTEMPT'
        rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT));
                                                              ^
pg.c:381:64: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT));
                                                                      ^
1 warning and 4 errors generated.
make: *** [pg.o] Error 1

Gem files will remain installed in /Users/marcboehle/.bundler/tmp/25873/gems/pg-0.16.0 for inspection.
Results logged to /Users/marcboehle/.bundler/tmp/25873/gems/pg-0.16.0/ext/gem_make.out

An error occurred while installing pg (0.16.0), and Bundler cannot continue.
Make sure that `gem install pg -v '0.16.0'` succeeds before bundling.

next i tried:
Marcs-MacBook-Pro:smartforce marcboehle$ sudo gem install pg
Password:
Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

    /usr/local/rvm/rubies/ruby-2.0.0-p247/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /usr/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for pg_config_manual.h... yes
checking for PQconnectdb() in -lpq... yes
checking for PQconnectionUsedPassword()... yes
checking for PQisthreadsafe()... yes
checking for PQprepare()... yes
checking for PQexecParams()... yes
checking for PQescapeString()... yes
checking for PQescapeStringConn()... yes
checking for PQescapeLiteral()... yes
checking for PQescapeIdentifier()... yes
checking for PQgetCancel()... yes
checking for lo_create()... yes
checking for pg_encoding_to_char()... yes
checking for pg_char_to_encoding()... yes
checking for PQsetClientEncoding()... yes
checking for PQlibVersion()... yes
checking for PQping()... yes
checking for PQsetSingleRowMode()... no
checking for rb_encdb_alias()... yes
checking for rb_enc_alias()... yes
checking for rb_thread_call_without_gvl()... yes
checking for rb_thread_call_with_gvl()... yes
checking for rb_thread_fd_select()... yes
checking for rb_w32_wrap_io_handle()... no
checking for PGRES_COPY_BOTH in libpq-fe.h... no
checking for PGRES_SINGLE_TUPLE in libpq-fe.h... no
checking for PG_DIAG_TABLE_NAME in libpq-fe.h... no
checking for struct pgNotify.extra in libpq-fe.h... yes
checking for unistd.h... yes
checking for ruby/st.h... yes
creating extconf.h
creating Makefile

make "DESTDIR="
compiling gvl_wrappers.c
compiling pg.c
pg.c:272:9: warning: implicit declaration of function 'PQlibVersion' is invalid in C99 [-Wimplicit-function-declaration]
        return INT2NUM(PQlibVersion());
               ^
In file included from pg.c:48:
In file included from ./pg.h:17:
In file included from /usr/local/rvm/rubies/ruby-2.0.0-p247/include/ruby-2.0.0/ruby.h:33:
/usr/local/rvm/rubies/ruby-2.0.0-p247/include/ruby-2.0.0/ruby/ruby.h:1167:21: note: instantiated from:
# define INT2NUM(v) INT2FIX((int)(v))
                    ^
pg.c:272:9: note: instantiated from:
        return INT2NUM(PQlibVersion());
               ^
pg.c:272:17: note: instantiated from:
        return INT2NUM(PQlibVersion());
                       ^
pg.c:375:48: error: use of undeclared identifier 'PQPING_OK'
        rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK));
                                                      ^
pg.c:375:56: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_OK", INT2FIX(PQPING_OK));
                                                              ^
pg.c:377:52: error: use of undeclared identifier 'PQPING_REJECT'
        rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT));
                                                          ^
pg.c:377:60: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_REJECT", INT2FIX(PQPING_REJECT));
                                                                  ^
pg.c:379:57: error: use of undeclared identifier 'PQPING_NO_RESPONSE'
        rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE));
                                                               ^
pg.c:379:65: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_NO_RESPONSE", INT2FIX(PQPING_NO_RESPONSE));
                                                                       ^
pg.c:381:56: error: use of undeclared identifier 'PQPING_NO_ATTEMPT'
        rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT));
                                                              ^
pg.c:381:64: note: instantiated from:
        rb_define_const(rb_mPGconstants, "PQPING_NO_ATTEMPT", INT2FIX(PQPING_NO_ATTEMPT));
                                                                      ^
1 warning and 4 errors generated.
make: *** [pg.o] Error 1

Gem files will remain installed in /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/gems/2.0.0/gems/pg-0.16.0 for inspection.
Results logged to /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/gems/2.0.0/gems/pg-0.16.0/ext/gem_make.out

and then i gave the following a try:
Marcs-MacBook-Pro:smartforce marcboehle$ which pg_config
/usr/bin/pg_config
Marcs-MacBook-Pro:smartforce marcboehle$ gem install pg -- --with-pg-config= '/usr/bin/pg_config'
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied - /usr/local/rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/.gemtest
Marcs-MacBook-Pro:smartforce marcboehle$ sudo apt-get install libpq-dev
Password:
sudo: apt-get: command not found
Marcs-MacBook-Pro:smartforce marcboehle$ sudo install libpq-dev
usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 file2
       install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]
               [-o owner] file1 ... fileN directory
       install -d [-v] [-g group] [-m mode] [-o owner] directory ...
Marcs-MacBook-Pro:smartforce marcboehle$ sudo apt-get install postgresql-client libpq5 libpq-dev
sudo: apt-get: command not found
Marcs-MacBook-Pro:smartforce marcboehle$ sudo gem install pg
ERROR:  Could not find a valid gem 'pg' (>= 0), here is why:
          Unable to download data from https://rubygems.org/ - SSL_connect SYSCALL returned=5 errno=0 state=SSLv3 read server session ticket A (https://rubygems.org/latest_specs.4.8.gz)
ERROR:  Possible alternatives: pg
Marcs-MacBook-Pro:smartforce marcboehle$ rails -v
Could not find pg-0.16.0 in any of the sources
Run `bundle install` to install missing gems.
Marcs-MacBook-Pro:smartforce marcboehle$ ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
Marcs-MacBook-Pro:smartforce marcboehle$ rails -v
Could not find pg-0.16.0 in any of the sources
Run `bundle install` to install missing gems.

EDIT
Thanks for your comments, i tried to install postgres which led to the following problems. any suggestions or can you recommend a tutorial how i can delete everything connected to the whole ruby on rails, rvm, homebrew and whatever i installed.
Then i would love to reinstall everything clean from the beginning.
otherwise can you help me out with a explanation what i need to do with the "Path" i need to do anything with. i'm a total rooky.
An error occurred while installing pg (0.16.0), and Bundler cannot continue.
Make sure that `gem install pg -v '0.16.0'` succeeds before bundling.
Marcs-MacBook-Pro:smartforce marcboehle$ brew update
Updated Homebrew from 424c84c5 to 9e01e61d.
==> New Formulae
clojurescript       libgsm      snzip           voltdb
dmalloc         libresample     stlviewer
dtrx            randomize-lines tlassemble
juju            reaver      tractorgen
==> Updated Formulae
abcl                    isl
ace                 iso-codes
aircrack-ng             ispc
appledoc                ispell
aspell                  jenkins
autoconf                jsvc
automake                klavaro
bash                    kytea
boost                   lcdf-typetools
botan                   ldid
bullet                  leiningen
calc                    lesstif
camlp5                  libcouchbase
cantera                 libdiscid
casperjs                libdlna
chruby                  libfreenect
classads                libmagic
cpanminus               libquvi
cppcheck                llvm
css-crush               logentries
csync                   lpc21isp
cyassl                  mackup
denominator             macvim
djvulibre               madplay
drush                   mariadb
dub                 matlab2tikz
duti                    mksh
eet                 mlton
eina                    mongodb
ejabberd                monotone
elixir                  mr
embryo                  mspdebug
eprover                 mysql
exiftool                mysql-cluster
fb-client               mysql-connector-odbc
fdk-aac                 nasm
findbugs                netcdf
flac                    netpbm
fontforge               nexus
fox                 node
fwknop                  open-scene-graph
gdal                    openssl
gearman                 parrot
geos                    passenger
getmail                 pcre++
gettext                 percona-server
gfortran                perl-build
git                 pgbadger
gle                 pgtap
glm                 pngquant
gnupg2                  poppler
go                  postgis
gobject-introspection           postgresql
gpg-agent               proguard
grass                   py2cairo
gst-libav               pypy
gst-plugins-bad             python
gst-plugins-base            python3
gst-plugins-good            qemu
gst-plugins-ugly            quantlib
gstreamer               rabbitmq
hevea                   rabbitmq-c
hiredis                 reattach-to-user-namespace
hydra                   redis
icu4c                   rethinkdb
ircd-hybrid             riak
rpm                 tiger-vnc
rrdtool                 transmission
rtmpdump                uwsgi
ruby                    vifm
saxon                   vimpc
sbcl                    voldemort
sdl2                    watchman
ser2net                 wine
serf                    wkhtmltopdf
silk                    wxmac
smartmontools               xmlto
socat                   xpa
sonar                   xrootd
sonar-runner                yarp
sqsh                    yaws
ssdeep                  ydict
storm                   youtube-dl
subversion              zabbix
svtplay-dl              zookeeper
swi-prolog              zsh-completions
tbb                 zsh-syntax-highlighting
terminal-notifier
==> Deleted Formulae
clojure
Marcs-MacBook-Pro:smartforce marcboehle$ brew doctor
Warning: Some directories in /usr/local/share/man aren't writable.
This can happen if you "sudo make install" software that isn't managed
by Homebrew. If a brew tries to add locale information to one of these
directories, then the install will fail during the link step.
You should probably `chown` them:

    /usr/local/share/man/man7

Warning: "config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.

Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:

    /opt/sm/pkg/active/bin/curl-config
    /opt/sm/pkg/active/bin/ncurses5-config
    /opt/sm/pkg/active/bin/ncursesw5-config
    /opt/sm/pkg/active/bin/pkg-config
    /opt/sm/pkg/active/bin/xml2-config
    /opt/sm/pkg/active/bin/xslt-config

Warning: An outdated version of Git was detected in your PATH.
Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub.
Please upgrade: brew upgrade git

Warning: You have MacPorts or Fink installed:
  /opt/local/bin/port

This can cause trouble. You don't have to uninstall them, but you may want to
temporarily move them out of the way, e.g.

  sudo mv /opt/local ~/macports

Warning: Your compilers are different from the standard versions for your Xcode.
If you have Xcode 4.3 or newer, you should install the Command Line Tools for
Xcode from within Xcode's Download preferences.
Otherwise, you should reinstall Xcode.

Warning: /usr/bin occurs before /usr/local/bin
This means that system-provided programs will be used instead of those
provided by Homebrew. The following tools exist at both paths:

    git
    git-cvsserver
    git-receive-pack
    git-shell
    git-upload-archive
    git-upload-pack

Consider amending your PATH so that /usr/local/bin
occurs before /usr/bin in your PATH.
Marcs-MacBook-Pro:smartforce marcboehle$ brew upgrade git
Warning: It appears you have MacPorts or Fink installed.
Software installed with other package managers causes known problems for
Homebrew. If a formula fails to build, uninstall MacPorts/Fink and try again.
Error: git not installed
Marcs-MacBook-Pro:smartforce marcboehle$ sudo mv /opt/local ~/macports
Marcs-MacBook-Pro:smartforce marcboehle$ brew upgrade git
Error: git not installed
Marcs-MacBook-Pro:smartforce marcboehle$ brew install git
==> Downloading http://git-core.googlecode.com/files/git-1.8.3.4.tar.gz
######################################################################## 100,0%
==> make prefix=/usr/local/Cellar/git/1.8.3.4 sysconfdir=/usr/local/etc CC=cc CF
==> make CC=cc CFLAGS= LDFLAGS=
git-credential-osxkeychain.c:131: error: 'protocol' undeclared (first use in this function)
git-credential-osxkeychain.c:131: error: 'kSecProtocolTypeHTTPS' undeclared (first use in this function)
git-credential-osxkeychain.c:133: error: 'kSecProtocolTypeHTTP' undeclared (first use in this function)
git-credential-osxkeychain.c:141: error: 'port' undeclared (first use in this function)
make: *** [git-credential-osxkeychain.o] Error 1

READ THIS: https://github.com/mxcl/homebrew/wiki/troubleshooting

These open issues may also help:
    https://github.com/mxcl/homebrew/issues/21998
    https://github.com/mxcl/homebrew/issues/21530
    https://github.com/mxcl/homebrew/pull/17713
    https://github.com/mxcl/homebrew/pull/20260
Marcs-MacBook-Pro:smartforce marcboehle$ brew upgrade git
Error: git not installed
Marcs-MacBook-Pro:smartforce marcboehle$

A: Try installing the packet libpq-dev

A: First, a recommendation to try using sqlite3 as your database provider if you're new...  It's just a single file, MUCH simpler to deal with compared to postgres.
It sounds like you don't have postgres or it's out of date.  Installing applications on the system itself is not recommended, instead you can install them for your use using Homebrew.  It looks like you tried a debian/ubuntu apt-get command, it's similar to those management systems, but for OS X.
Make sure you have XCode installed, and install the command line tools using it (there's a button in XCode's preferences to do so easily).


text:
Q: Is it possible to use the L'hopital rule for computing the derivative of this function at x=0? The function
\begin{equation}
f(x)=\begin{cases} \cos(1/x) & x\neq 0\\ 0 & x=0\end{cases}.
\end{equation}
and the function $F(x)=\displaystyle \int ^x_0 f $
And I know that by considering another function $g(x)$, it's possible to solve that $F'(0)=0$
However, I wonder why I can't use the L'hopital rule for this question.
More specifically, If I want to find the derivative of $F(x)$ at $x=0$, based on the definition of the derivative, I can use
$\displaystyle \lim_{x\to0} \frac{F(x)-F(0)}{x-0}=\lim_{x\to0} \frac{F(x)}{x}=\lim_{x\to0}\frac{\displaystyle \int ^x_0 f }{x}=F'(0)$ and since this is a $0/0$, then I use the L'hopital rule to the nominator and the denominator.
The result will be $\displaystyle \lim_{x\to0} \cos \frac{1}{x}$ which indicates that $F'(0)$ doesn't exist.
I wonder why this is a wrong procedure, I kind of doubt that $\displaystyle \lim_{x\to 0}\int^x_0 \cos \frac{1}{x}$ is not 0. Is this true? Or are there some other problems with this?

A: The rule says (under some assumptions) that if $f'/g' \to A$, then $f/g \to A$. In your case $f'/g'$ doesn't tend to anything, so the rule simply doesn't apply.


text:
Q: Unable to process binding afterRender error return on Checkout Page in Magento 2.4 In Magento 2.4, Checkout page I faced error.
TypeError : Unable to process binding "afterRender: function () {return renderReCaptcha() }"

How to solve this error?

A: Create requiejs-config.js file and add this mixin :

app/code/Vendor/Module/view/frontend/requirejs-config.js

var config = {
    config: {
        mixins: {
            'Magento_ReCaptchaFrontendUi/js/reCaptcha' : {
                'Vendor_Module/js/reCaptcha-mixin' : true
            }
        }
    }
};

Create reCaptcha-mixin.js file and add below code :

app/code/Vendor/Module/view/frontend/web/js/reCaptcha-mixin.js

define([
    'uiComponent',
    'jquery',
    'ko',
    'underscore',
    'Magento_ReCaptchaFrontendUi/js/registry',
    'Magento_ReCaptchaFrontendUi/js/reCaptchaScriptLoader',
    'Magento_ReCaptchaFrontendUi/js/nonInlineReCaptchaRenderer'
], function (Component, $, ko, _, registry, reCaptchaLoader, nonInlineReCaptchaRenderer) {
    'use strict';

    return function(Component) {
        return Component.extend({
            initCaptcha: function () {
                if (typeof this.settings === 'undefined') {
                    return;
                }
                this._super();
            },

            getIsInvisibleRecaptcha: function () {
                if (typeof this.settings === 'undefined') {
                    return;
                }
                return this.settings.invisible;
            }
        });
    }
});

Now, Just need to deploy and clean cache.


text:
Q: Encode string fields in OData output I have an OData controller that want to encode string fields of its output. OData output result is sent back to client as clear data but I want to encrypt them before sending it to client.
It seems that the best way is to use a customized OData serializer or a feed serializer to achieve my goal. But I'm not sure which class to customize. Is it better to override some methods or implement my own customized version of a serializing class.
Any help is appreciated.

A: Find a way to do it. I did it by customizing serializer by help of this guide. Final code:
using Microsoft.Data.Edm;
using Microsoft.Data.OData;
using System.Web.Http.OData.Formatter.Serialization;

namespace MyProj
{
    public class CustomODataEntityTypeSerializer : ODataEntityTypeSerializer
    {
        public CustomODataEntityTypeSerializer(ODataSerializerProvider serializerProvider) : base(serializerProvider)
        {
        }

        public override void WriteObjectInline(object graph, IEdmTypeReference expectedType, ODataWriter writer, ODataSerializerContext writeContext)
        {
            //http://odata.github.io/WebApi/#06-03-costomize-odata-formatter

            if (graph is CompanyDto)
            {
                var company = (CompanyDto)graph;

                company.FirstName = Encrypt(company.FirstName);
                company.LastName = Encrypt(company.LastName);
            }

            base.WriteObjectInline(graph, expectedType, writer, writeContext);
        }
    }
}

And this class:
using Microsoft.Data.Edm;
using System.Web.Http.OData.Formatter.Serialization;

namespace MyProj
{
    public class CustomDefaultODataSerializerProvider : DefaultODataSerializerProvider
    {
        CustomODataEntityTypeSerializer _customODataEntityTypeSerializer;

        public CustomDefaultODataSerializerProvider()
        {
            _customODataEntityTypeSerializer = new CustomODataEntityTypeSerializer(this);
        }

        public override ODataEdmTypeSerializer GetEdmTypeSerializer(IEdmTypeReference edmType)
        {
            if (edmType.IsEntity())
            {
                return _customODataEntityTypeSerializer;
            }

            return base.GetEdmTypeSerializer(edmType);
        }
    }
}

And initializing it as follow:
            var odataFormatters = ODataMediaTypeFormatters.Create(new CustomDefaultODataSerializerProvider(), new DefaultODataDeserializerProvider());
        config.Formatters.InsertRange(0, odataFormatters);


text:
Q: How can I resolve these vbulletin 404 errors using htaccess? I have a very big forum (230k threads, 3 million posts) that has a large number of 404 pages reported on Google Webmaster Tools, to the tune of about 14,000 404 URLs. Google is probably showing these 404s because I have incoming links to them, meaning I'm losing a lot of SEO benefit by not having these links follow through to the actual page.
I know why I have this problem, a year ago the URLs on my site were changed back to vBulletin default so that they look like this:
http://www.domain.com/showthread.php?t=323653&p=4230256

I would like to keep them this way since they've been that way for a year. The problem is that there were two previous formats that are showing 404 errors:
These:
http://www.domain.com/forums/showthread.php?t=21461

http://www.domain.com/forums/showthread.php?t=16187

Which just need to have forums/ removed from the URL, and these:
http://www.domain.com/forums/f8/39840-infractions_system_how_works.html

http://www.domain.com/forums/f11/67410-viewing_ijji_gunz_replays_while_offline.html

Which are a funky URL structure that was created back when I had vbSEO installed.
/forums/ needs to be removed and I think that the numbers 39840 and 67410 are probably the thread id. I think there's everything we need in the URL to rewrite but I'm not entirely sure how to achieve it using htaccess.

A: Assuming, your .htaccess is located at website root "/"
RewriteEngine on
RewriteBase /

# removes "forums/"
RewriteCond %{REQUEST_URI} !^/showthread.php$ [NC]
RewriteRule ^forums/([^/]+)$ $1 [R=301,NC,L]

# parses thread id
RewriteCond %{REQUEST_URI} !^/showthread.php$ [NC]
RewriteRule ^forums/[^/]+/(\d+)-.*$ showthread.php?t=$1 [R=301,NC,L]

A: Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# to redirect /forums/f8/39840-something.html to
# /showthread.php?t=39840
RewriteRule ^forums/[^/]+/([^-]+)-[^.]+\.html$ /showthread.php?t=$1 [R=301,NC,L,QSA]

# to redirect /forums//showthread.php?t=39840 to
# /showthread.php?t=39840
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^forums/([^/]+)/?$ /$1 [R=301,NC,L]


text:
Q: Anchor Element moves in the DOM My source looks like this:

<title>Southwest Pumps: Fire Pump Sales and Services</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"     href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link href="https://fonts.googleapis.com/css?family=Montserrat"     rel="stylesheet">
<link rel="stylesheet" type="text/css" href="/stylesheets/style.css">

Create New Job Entry

Customer Name
Job Name
Last Edited
Editor
Link to Job

Customer
Job
<input type="hidden" id="inputdate0" value="Tue Jul 10 2018 21:21:47     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

Customer
Job
<input type="hidden" id="inputdate1" value="Tue Jul 10 2018 21:22:27     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

Customer
Job
<input type="hidden" id="inputdate2" value="Tue Jul 10 2018 21:23:40     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

Customer
Job
<input type="hidden" id="inputdate3" value="Tue Jul 10 2018 21:30:46     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

Customer
Job
<input type="hidden" id="inputdate4" value="Tue Jul 10 2018 21:33:22     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

Customer
Job
<input type="hidden" id="inputdate5" value="Mon Jul 09 2018 18:58:16     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

Customer
Job
<input type="hidden" id="inputdate6" value="Tue Jul 10 2018 21:33:34     GMT+0000 (UTC)"></input>
LeslieSmooth
Link

But the DOM moves all my anchor elements above the TABLE and it ends up looking like this for some reason.
My goal is to make the whole row of the table an anchor element that links to a particular database id. I am totally clueless as to what is going on. Any help is appreciated!
...

Create New Job Entry

Customer Name
Job Name
Last Edited
Editor
Link to Job

...

I'm using Bootstrap. And I'm generating the anchor tags with NodeJS/Express and using EJS.
JIC my EJS code looks like this:
...

Create New Job Entry

Customer Name
Job Name
Last Edited
Editor
Link to Job

<% for (var i = 0; i < jobs.length; i++) { %>
<a href="/sales/<%= jobs[i]._id %>" style="display: block;">

<%= jobs[i].customer %>
<%= jobs[i].name %>
<input type="hidden" id="inputdate<%= [i] %>" value="<%=     jobs[i].lastEdited %>"></input><span class="date-class" id="spandate<%= [i] %>">
<%= jobs[i].editors[jobs[i].editors.length - 1].username %>
<a class="btn btn-xs btn-primary" href="/sales/<%= jobs[i]._id     %>">Link

<% } %>

...


text:
Q: App Engine: Does put(java.lang.Iterable entities) reduce the number of write operations? Does calling the put(java.lang.Iterable<Entity> entities) which performs a batch put of the list of entities reduces the number of datastore write operations to just one as compared to calling put(Entity entity) n number of times?

A: No, it does not affect the write operations. As described at Billable Resource Unit Costs in the App Engine documentation, the write operations count per entity that is stored in the datastore.
What makes a difference is the total time needed to perform all operations as in batch operations the response time from datastore is minimized compared to a series of standalone opoerations.
Hope this helps!


text:
Q: Makes downloads go to Word Every time I try to download it goes to Word and will not open up up the file. I am using Firefox as my browser. I have gone to Options > Applications to make the correct changes.

A: Seems like you need to reset your file extension association defaults. On windows this can be achieved by:

*

*Open the Control Panel (icons view), and click on the Default Programs icon.

*Click on the Set your default programs link.

*In the left column, select (highlight a listed program that you want to change it's default file associations for.

*To Set the Program as the Default Program for All of it's Associations
A) Click on Set this program as default. (See screenshot below step 3A)
B) Go to step 6.

*To Manually Choose Default Associations to be Associated with the Program
A) Click on Choose defaults for this program. (See screenshot below step 3A)
B) Check the file extensions you want this program to be associated to open by default. NOTE: These are the default settings for each listed default program. You will only be able to uncheck the file extenstions that you just checked and were not already checked before doing step 5A.

A: Reset your Firefox: https://support.mozilla.org/en-US/kb/refresh-firefox-reset-add-ons-and-settings

If you're having problems with Firefox, refreshing it can help. The
  refresh feature fixes many issues by restoring Firefox to its default
  state while saving your essential information like bookmarks,
  passwords, and open tabs.


text:
Q: MPI Address not mapped in C I have trouble with MPI_Recv when using malloc? Is there any suggestion to receive a two dimensional array created with malloc?
Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>

#define SIZE 2000
/* Tags defines message from_to */
#define TO_SLAVE_TAG 1
#define TO_MASTER_TAG 5

void createMatrices();
/* Matrices */
int** first;
/* MPI_WORLD rank and size */
int rank, size;

MPI_Status status;
/*
 * matrixSize: current matrix size
 * lower_bound: lower bound of the number of rows of [first matrix] allocated to a slave
 * upper_bound: upper bound of the number of rows of [first matrix] allocated to a slave
 * portion: number of the rows of [first matrix] allocated to a slave according to the number of processors
 * count: number of data will pass with mpi functions
 */
int matrixSize, lower_bound, upper_bound, portion, count;
int sum = 0;
clock_t t, start_time, end_time;

int main( int argc, char **argv ) {

  /* Initialize the MPI execution environment */
  MPI_Init( &argc, &argv );
  /* Determines the size of the group */
  MPI_Comm_size( MPI_COMM_WORLD, &size );
  /* Determines the rank of the calling process */
  MPI_Comm_rank( MPI_COMM_WORLD, &rank );

  if (rank == 0)
    {
      for (matrixSize = 500; matrixSize <= SIZE; matrixSize += 500) {
    createMatrices(matrixSize);
    /*
     * Master processor divides [first matrix] elements
     * and send them to proper slave processors.
     * We can start time at this point.
     */
    start_time = clock();

    /* Define bounds for each processor except master */
    for (int i = 1; i < size; ++i)
      {
        /* Calculate portion for each slave */
        portion = (matrixSize / (size - 1));
        lower_bound = (i-1) * portion;
        if (((i+1)==size) && (matrixSize % (size-1) != 0)) {
          upper_bound = matrixSize;
        } else {
          upper_bound = lower_bound + portion;
        }
        /* send matrix size to ith slave */
        MPI_Send(&matrixSize, 1, MPI_INT, i, TO_SLAVE_TAG, MPI_COMM_WORLD);
        /* send lower bount to ith slave */
        MPI_Send(&lower_bound, 1, MPI_INT, i, TO_SLAVE_TAG + 1, MPI_COMM_WORLD);
        /* send upper bount to ith slave */
        MPI_Send(&upper_bound, 1, MPI_INT, i, TO_SLAVE_TAG + 2, MPI_COMM_WORLD);
        /* send allocated row of [first matrix] to ith slave */
        count = (upper_bound - lower_bound) * matrixSize;
        printf("Count: %d\n", count);
        MPI_Send(&(first[lower_bound][0]), count, MPI_DOUBLE, i, TO_SLAVE_TAG + 3, MPI_COMM_WORLD);
      }
      }
    }
  if (rank > 0)
    {
      //receive low bound from the master
      MPI_Recv(&matrixSize, 1, MPI_INT, 0, TO_SLAVE_TAG, MPI_COMM_WORLD, &status);
      printf("Matrix size: %d\n", matrixSize);
      //receive low bound from the master
      MPI_Recv(&lower_bound, 1, MPI_INT, 0, TO_SLAVE_TAG + 1, MPI_COMM_WORLD, &status);
      printf("Lower bound: %d\n", lower_bound);
      //next receive upper bound from the master
      MPI_Recv(&upper_bound, 1, MPI_INT, 0, TO_SLAVE_TAG + 2, MPI_COMM_WORLD, &status);
      printf("Upper bound: %d\n", upper_bound);
      //finally receive row portion of [A] to be processed from the master
      count = (upper_bound - lower_bound) * matrixSize;
      printf("Count: %d\n", count);

      MPI_Recv(&first[lower_bound][0], count, MPI_INT, 0, TO_SLAVE_TAG + 3, MPI_COMM_WORLD, &status);
      printf("first[0][0]: %d\n", first[0][0]);
    }
  MPI_Finalize();
  return 0;
}

void createMatrices(int mSize) {
  /* matrix cols */
  first = malloc(mSize * sizeof(int*));
  /* matrix rows */
  for (int i = 0; i < mSize; ++i)
    first[i] = malloc(mSize * sizeof(int));

  srand(time(NULL));
  for (int i = 0; i < mSize; ++i)
    for (int j = 0; j < mSize; ++j)
      first[i][j] = rand()%2;
}

And problem is:
*** Process received signal ***
Signal: Segmentation fault: 11 (11)
Signal code: Address not mapped (1)
Failing at address: 0x0
[ 0] 0   libsystem_platform.dylib            0x00007fff89cc8f1a _sigtramp + 26
[ 1] 0   libsystem_c.dylib                   0x00007fff73857070 __stack_chk_guard + 0
[ 2] 0   libdyld.dylib                       0x00007fff90f535c9 start + 1
[ 3] 0   ???                                 0x0000000000000001 0x0 + 1
*** End of error message ***

A: To avoid (possibly high) latency costs of sending each row individual you need to create a matrix in linear memory. This is done by allocating enough memory for the entire matrix and setting up pointers to each row. Here is your function modified to do so.
void createMatrices(int mSize) {
  /* initialize enough linear memory to store whole matrix */
  raw_data=malloc(mSize*mSize*sizeof(int*));

  /* matrix row pointers i.e. they point to each consecutive row */
  first = malloc(mSize * sizeof(int*));

  /* set the pointers to the appropriate address */
  for (int i = 0; i < mSize; ++i)
    first[i] = raw_data + mSize*i;

  /* initialize with random values */
  srand(time(NULL));
  for (int i = 0; i < mSize; ++i)
    for (int j = 0; j < mSize; ++j)
      first[i][j] = rand()%2;
}

The other major problem you are facing is proper memory handling. You should free your matrices before allocating new ones on the root rank.
You also need to allocate memory for a matrix on the slave ranks before trying to copy over the data. That also needs to be in linear memory as done in the above function.


text:
Q: Difference between creating javascript objects When creating an object to use JS in an OO manner, is there any difference within a JS engine between (with the exception of being able to define a constructor:
var Uploader = Uploader || {};

and
var Uploader = function() {

}

and
function Uploader() {

}

Especially when later, you wish to do something along the lines of
Uploader.DOM = {
    Create: function(file) {

    }
};

Is it all down to personal preference? Or is there a real difference?

A: Objects:
var MyObj = {
    myArr: [1,2,3],
    find: function(/*some arguments*/) {
        //some logic that finds something in this.myArr
    }
}

In MyObj.find function this keyword will point to MyObj (which somewhat resembles how this works in languages those have classes). You can use this functionality to do mix-ins:
var MyObj2 = {
    myArr: [4,2,6]
}

MyObj2.find = MyObj.find;

In MyObj2.find function this keyword will point to MyObj2.
Also objects support getters and setters (works on IE9+ and all good browsers):
var MyObj = {
    myArr: [1,2,3],
    find: function(/*some arguments*/) {
        //some logic that finds something in this.myArr
    },
    get maxValue() {
        return Math.max.apply(null, this.myArr);// maxValue is calculated on the fly
    },
    a_: null,
    get a () {
        return this.a_;
    },
    set a (val) {
        //fire a change event, do input validation
        this.a_ = val;
    }
}

Now max value in the array can be accessed like this: MyObj.maxValue. I also added a property a_. It can't be named the same as its getter and setter so appended an underscore. Appending or prepending underscores is a naming convention for private variables which should not be accessed directly.
var qwe = MyObj.a // get a_
MyObj.a = 'something'; //set a_

Functions:
var u = new Uploader(); // will throw an exception
var Uploader = function() { }

Uploader is defined in runtime here. It does not exist yet when I try to instantiate it.
var u = new Uploader(); //will work
function Uploader() {}

Uploader is defined in compilation time here so it will work.
Functions can be used with revealing pattern to conceal some members. Functions don't support getters and setters but you can put objects inside functions.
function myFunc() {
    function privateFunc() {};
    function publicFunc() {};
    var obj = {
        //members, getters, setters
    };
    return {
       publicFunc: publicFunc,
       obj: obj
    }
}

You can call muFunc.publicFunc() outside of myFunc because it is returned. But you can not use privateFunc outside because it is not returned.
Revealing pattern functions are not meant to be instantiated usually. This is because when you instantiate it everything inside will be copied to a new instance. So it will use up more memory than if you would add functions using prototype.
myFunc.prototype.someFunc = function() {};

Like this all instances of myFunc will share the same instance of someFunc.
Conclusion: with functions you can simulate a private access modifier but in objects the this keyword acts somewhat similar of what you'd expect in a language that have classes. But you always can use call, apply and bind to change the context (i.e. what 'this' keyword will be) of the function.


text:
Q: Can´t assign query result to a python variable I have this query:
import mysql.connector
cnx = mysql.connector.connect(user='root', password='xxx',
                              host='127.0.0.1',
                              database='xxxx')
cursor = cnx.cursor()
query = ("SELECT app_id FROM op_ids")
cursor.execute(query)
LATCH_APP_ID=cursor.fetchall()

cursor.close()
cnx.close()

The value of app_id on the database is ybDWvzU4iijnqqX8xAxx but when I run the python script , it returns [(u'ybDWvzU4iijnqqX8xAxx',)], so I can't use it in other method because I get the following error:
TypeError: cannot concatenate 'str' and 'list' objects

If a use a variable like this:
LATCH_APP_ID = "ybDWvzU4iijnqqX8xAxx"

The script runs OK
Can anybody help me?

A: It seems that cursor.fetchall() has returned:
[(u'ybDWvzU4iijnqqX8xAxx',)]

So you only need to extract the string from with in the structures:
result = cursor.fetchall()

t = result[0]        # fetch the tuple from the first item in the list

LATCH_APP_ID = t[0]  # fetch the string from the first (only) item in the tuple


text:
Q: Adding dummies as control variables change the coefficient It has been difficult to formulate a title for this question. But here is something that is puzzling me. I have an ordinal probit model with a bunch of covariates. One of the covariates is the number of ratified human rights conventions (ranges from 0 to 7). This variable is time-varying and coded for each state in the dataset.
So let's say that this is my model: oprobit<-porl(y~x1+x2+x3+ratification, data=mydata, Hess=TRUE, method="probit")
The coefficient of the "ratification" variable is positively correlated with the dependent variable and significant.
Then, I insert dummies for each of the 7 ratified conventions (coded country-year).
So: oprobit2<-porl(y~x1+x2+x3+ratification+con1+con2+con3+con4+con5+con6+con7, data=mydata, Hess=TRUE, method="probit")
All dummies are also positively correlated with the dependent variable, however, the "ratification" variable is now negatively correlated and significant.
I know that there might be many reasons for this. However, I am sure that this is not an unusual "problem". What is it that I am observing here? Shall I keep the dummies in the model or not?


text:
Q: open file dialog via oncontextmenu event I tried to open file dialog by 'oncontextmenu' event, but it didn't work! I can do this by other event, but only 'oncontextmenu' didn't work.
<html>
  <head>
    <script type="text/javascript">
     function wrapper(ev)
     {
       ev.preventDefault();
       document.getElementById('file').click();
       return false;
     }
    </script>
  </head>
  <body>

  <input id="button" type="button" oncontextmenu="wrapper(event)">
  <input id="file" type="file">

  </body>
</html>

I want to know solution or why it doesn't work.
Thanks for reading.

A: It doesn't work because some browsers disallow triggering file input programatically. See this question for numerous attempts of this with questionable success.


text:
Q: How to read JSON data from a remote URL to a file in the local file store using JavaScript? I want to hit a remote URL
After googling, I decided to use dojo.io.script.get, as cross-channel calls are supported only in that. But, I keep getting the below error in my FF browser, but the correct response is also shown thr.

syntax error
  http://reviews.apitestcustomer.bazaarvoice.com/bvstaging/data/reviews.json?callback=%3F&Filter=ProductId%3A14151&PassKey=t5sv9b3nvawhkljtlmegk8d6s&apiversion=5.0
  Line 1
?({"Includes":{},"HasErrors":false,"Offset":0,"TotalResults":2,"Locale":"en_US","Errors":[],"Results":[{"TagDimensions":{},"TagDimensionsOrder":[],"AdditionalFieldsOrder":[],"Cons":null,"IsRecommended":null,"IsRatingsOnly":false,"UserNickname":null,"Pros":null,"Photos":[],"ContextDataValues":{},"Videos":[],"ContextDataValuesOrder":[],"LastModificationTime":"2012-01-10T09:10:33.000-06:00","SubmissionId":"ex7csdrwiorg3tbgpshbfcljd","TotalFeedbackCount":0,"TotalPositiveFeedbackCount":0,"BadgesOrder":[],"UserLocation":null,"Badges":{},"AuthorId":"shiji_sk","SecondaryRatingsOrder":[],"IsFeatured":false,"ProductRecommendationIds":[],"Title":"test title","ProductId":"14151","AdditionalFields":{},"CampaignId":null,"Helpfulness":null,"TotalNegativeFeedbackCount":0,"SubmissionTime":"2012-01-09T05:55:58.000-06:00","ContentLocale":"en_US","Rating":5,"RatingRange":5,"TotalCommentCount":0,"ReviewText":"test test test test test test test test test test test test test test test test test test test test","ModerationStatus":"APPROVED","ClientResponses":[],"Id":"759582","SecondaryRatings":{},"CommentIds":[],"LastModeratedTime":"2012-01-10T09:10:33.000-06:00"},{"TagDimensions":{},"TagDimensionsOrder":[],"AdditionalFieldsOrder":[],"Cons":null,"IsRecommended":null,"IsRatingsOnly":false,"UserNickname":null,"Pros":null,"Photos":[],"ContextDataValues":{},"Videos":[],"ContextDataValuesOrder":[],"LastModificationTime":"2012-01-10T09:10:33.000-06:00","SubmissionId":"p6q13u5vgiqjfyk1xl5mktuvp","TotalFeedbackCount":0,"TotalPositiveFeedbackCount":0,"BadgesOrder":[],"UserLocation":null,"Badges":{},"AuthorId":"shiji","SecondaryRatingsOrder":[],"IsFeatured":false,"ProductRecommendationIds":[],"Title":"white review title","ProductId":"14151","AdditionalFields":{},"CampaignId":null,"Helpfulness":null,"TotalNegativeFeedbackCount":0,"SubmissionTime":"2012-01-09T04:16:40.000-06:00","ContentLocale":"en_US","Rating":5,"RatingRange":5,"TotalCommentCount":0,"ReviewText":"review for White Fabric Roll Arm Chaise & Contemporary Upholstered Armchair:\nGood one :-)","ModerationStatus":"APPROVED","ClientResponses":[],"Id":"759547","SecondaryRatings":{},"CommentIds":[],"LastModeratedTime":"2012-01-10T09:10:33.000-06:00"}],"Limit":10});

This is my script:
_invokeCrossSiteService: function(url, method, content, catEntryId, callbackFunction, appData, refresh)
{
    alert("in _invokeCrossSiteService..........................");
    if (content != null) {
        var temp = content;
        content = dojo.toJson(temp,false);
    }

     dojo.io.script.get({
         // The URL to get JSON from Twitter
         url: "http://reviews.apitestcustomer.bazaarvoice.com/bvstaging/data/reviews.json",
         // The callback paramater
         //callbackParamName: "callback",
         // The content to send
         content: {
                    callback: "?",
                    Filter: "ProductId\:"+catEntryId, // Searching for catEntryId
                    PassKey: "t5sv9b3nvawhkljtlmegk8d6s",
                    apiversion: "5.0"
                },
         // The success callback
         load: function(resp) {

            alert("resp in _invokeCrossSiteService - "+resp);
            callbackFunction(status, data, appData);
         },
         error: function(resp){
             alert("in error - "+resp);
         }
    });
}

Can someone pls help me out here??

A: Change:
callback: "?",

To
callbackParamName: "callback",

A: The problem is here:
callback: "?"

You're using JSON-P (not just JSON). The way JSON-P works is by adding a script element to your page with the given URL; the script is then loaded from the remote endpoint, and (by JSON-P's general contract) it consists entirely of a call to the function name you provide, passing in a JavaScript object literal (JSON is a subset of object literal syntax).
So you need to give the endpoint you're calling the name of the function it should call once the resource has been loaded, as this is how JSON-P works. So for instance:
callback: "dataReady"

...where you have this global function on the page:
function dataReady(data) {
}

Note how what you get back is in the form ?(...) — because the name you're giving the function is ?.
I expect Dojo may well have a means of handling the function name and such for you, it may be worth looking at the docs to see if there's explicit JSON-P support. (There is in some other libraries.)


text:
Q: Make custom list item read only based on field value I would like to make a custom list item read-only based on a field value, i.e. FieldName=Billed FieldType Y/N if Y then the iten is read only and can't be changed but if it is N then the item can be changed and resaved.
Is this possible?

A: You could use a workflow that is triggered on ItemChange , checks the value, and changes the permissions accordingly. SP 2010 workflows have a Workflow Action called "Replace List Item Permissions" that can change permissions. This action is only available in an impersonation step. See:  http://spcycle.blogspot.hk/2012/01/how-to-create-workflow-to-change-item.html


text:
Q: How to reduce Buffer time on streaming app? I'm Building an android app that is supposed to stream an online radio station from a URL.
I am currently working on a demo and I have gotten a lot of help from online tutorials but I have a problem.
When I click on the NEXT button it's supposed to get it's audio from another URL, which gives it the effect of changing the station, but it takes too much time and most times it doesn't seem to work.
Is there any way I could reduce the time by 95% cause I want it to start almost immediately you click on the next button
CODE FOR THE NEXT BUTTON
b_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               mediaPlayer.stop();
                mediaPlayer.reset();
                try {
                    mediaPlayer.setDataSource("http://stream.radioreklama.bg/veronika.opus");
                    mediaPlayer.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                mediaPlayer.start();
            }
        });

A: The problem may not be buffering- there might be some slow startup time on the server side for example.
Either way, if you want to monitor the buffering there is a call back provided with MediaPlayer which will do this - 'OnBufferingUpdateListener.onBufferingUpdate()'.
From the MediaPlayer documentation (https://developer.android.com/reference/android/media/MediaPlayer.html#setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)):

While in the Started state, the internal player engine calls a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback method if a OnBufferingUpdateListener has been registered beforehand via setOnBufferingUpdateListener(OnBufferingUpdateListener). This callback allows applications to keep track of the buffering status while streaming audio/video.

One common technique to speed up switching between streams, across platforms, is to have the next stream prepared in advance.
For your case you would need a second media player which you would initialise and move to the prepared state, and possibly even seek to a point, and then play it as soon as you stop the other one.
For live streams this will be a little more difficult as you can't see to a point in the same way. You could experiment with having the second player playing but with the volume turned down, although this is obviously not very efficient, unless you have some reliable way to predict when the user is about to switch.


text:
Q: e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp in Android Studio This is the error that I'm getting everytime I press the upload button after selecting an image from the device

I/System.out:e:java.lang.ClassNotFoundException:com.mediatek.cta.CtaHttp
    W/System: ClassLoader referenced unknown path:system/framework/mediatek-cta.jar

While trying to upload an image with a text parameter from the app to SQL database.
MainAtivity.java
package com.example.veekalp.imageupload;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;

import java.io.IOException;
import java.util.UUID;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //Declaring views
    private Button buttonChoose;
    private Button buttonUpload;
    private ImageView imageView;
    private EditText editText;

    //Image request code
    private int PICK_IMAGE_REQUEST = 1;

    //storage permission code
    private static final int STORAGE_PERMISSION_CODE = 123;

    //Bitmap to get image from gallery
    private Bitmap bitmap;

    //Uri to store the image uri
    private Uri filePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Requesting storage permission
        requestStoragePermission();

        //Initializing views
        buttonChoose = (Button) findViewById(R.id.buttonChoose);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);
        imageView = (ImageView) findViewById(R.id.imageView);
        editText = (EditText) findViewById(R.id.editTextName);

        //Setting clicklistener
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    /*
    * This is the method responsible for image upload
    * We need the full image path and the name for the image in this method
    * */
    public void uploadMultipart() {
        //getting name for the image
        String name = editText.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name", name) //Adding text parameter to the request
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //method to show file chooser
    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    //handling the image chooser activity result
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //method to get the file path from uri
    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }

    //Requesting permission
    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            return;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
        }
        //And finally ask for the permission
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
    }

    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //Checking the request code of our request
        if (requestCode == STORAGE_PERMISSION_CODE) {

            //If permission is granted
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Displaying a toast
                Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
            } else {
                //Displaying another toast if permission is not granted
                Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == buttonChoose) {
            showFileChooser();
        }
        if (v == buttonUpload) {
            uploadMultipart();
        }
    }
}


text:
Q: Run os.system as if python was not executed with sudo When I run the following command, everyhting works as expected. No error and I get a system notification saying "Hello":
$ python3
>>> import os
>>> os.system("notify-send Hello")
0

However, when I do this:
$ sudo python3
>>> import os
>>> os.system("notify-send Hello")

The script gets stuck and nothing happens.
I then tried to do this:
$ sudo python3
>>> import os
>>> os.seteuid(1000)
>>> os.system("notify-send Hello")

(1000 being my normal non-root user account)
But still, the script gets stuck and nothing happens.
I also tried this:
$ sudo python3
>>> import os
>>> os.system("su my-user-name -c 'notify-send Hello'")

and this:
$ sudo python3
>>> import os
>>> os.seteuid(1000)
>>> os.system("su my-user-name -c 'notify-send Hello'")

They all have the same issue...
I'm not looking for an alternative way of creating notifications. I'm not interested in subprocess or things like notify2 which cause a whole new category of problems on my system. Oh and please don't tell me not to use sudo. I have my reasons.

A: The implementation detail I've discovered through trial-and-error is notify-send requires the XDG_RUNTIME_DIR environment variable to function -- at least with these versions:
$ dpkg -l | grep libnotify
ii  libnotify-bin                              0.7.7-3                                      amd64        sends desktop notifications to a notification daemon (Utilities)
ii  libnotify4:amd64                           0.7.7-3                                      amd64        sends desktop notifications to a notification daemon

I first determined it needed some sort of environment variable by using env -i notify-send hello, which produced no notification.
I then bisected the environment with a modified version of this script
How you get that environment variable is up to you, but you need to be running notify-send as the proper user and with that variable set.
Here's a sample python script, I refuse to use os.system due to its security issues:
import os
import pwd
import subprocess
import sys

def main():
    if len(sys.argv) != 2:
        raise SystemExit(f'usage `{sys.argv[0]} USER`')
    if os.getuid() != 0:
        raise SystemExit('expected to run as root')

    # find the `gnome-session` executable, we'll use that to grab
    # XDG_RUNTIME_DIR
    cmd = ('pgrep', '-u', sys.argv[1], 'gnome-session')
    pid = int(subprocess.check_output(cmd))

    # read that process's environment
    with open(f'/proc/{pid}/environ') as f:
        for line in f.read().split('\0'):
            if line.startswith('XDG_RUNTIME_DIR='):
                _, _, xdg_runtime_dir = line.partition('=')
                break
        else:
            raise SystemExit('Could not find XDG_RUNTIME_DIR')

    # run the notify send as the right user
    uid = pwd.getpwnam(sys.argv[1]).pw_uid
    os.seteuid(uid)
    os.environ['XDG_RUNTIME_DIR'] = xdg_runtime_dir
    os.execvp('notify-send', ('notify-send', 'ohai'))

if __name__ == '__main__':
    exit(main())

DISCLAIMER: this script is doing some very hacky things that I wouldn't necessarily suggest in production code.  Notably:

*

*shelling out to pgrep to find a process

*reading another process's environment variables

*sudo
Sample usage:
$ python3 t.py
usage `t.py USER`
$ python3 t.py asottile
expected to run as root
$ sudo python3 t.py asottile
# (I get a notification for `ohai`)


text:
Q: Is a LINQ statement faster than a 'foreach' loop? I am writing a Mesh Rendering manager and thought it would be a good idea to group all of the meshes which use the same shader and then render these while I'm in that shader pass.
I am currently using a foreach loop, but wondered if utilising LINQ might give me a performance increase?

A: I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.
It looks like LINQ might be faster than for each loop. Here are the results I got:
Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well.
Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.
public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }

    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}

A: LINQ-to-Objects generally is going to add some marginal overheads (multiple iterators, etc). It still has to do the loops, and has delegate invokes, and will generally have to do some extra dereferencing to get at captured variables etc. In most code this will be virtually undetectable, and more than afforded by the simpler to understand code.
With other LINQ providers like LINQ-to-SQL, then since the query can filter at the server it should be much better than a flat foreach, but most likely you wouldn't have done a blanket "select * from foo" anyway, so that isn't necessarily a fair comparison.
Re PLINQ; parallelism may reduce the elapsed time, but the total CPU time will usually increase a little due to the overheads of thread management etc.

A: This is actually quite a complex question. Linq makes certain things very easy to do, that if you implement them yourself, you might stumble over (e.g. linq .Except()). This particularly applies to PLinq, and especially to parallel aggregation as implemented by PLinq.
In general, for identical code, linq will be slower, because of the overhead of delegate invocation.
If, however, you are processing a large array of data, and applying relatively simple calculations to the elements, you will get a huge performance increase if:

*

*You use an array to store the data.

*You use a for loop to access each element (as opposed to foreach or linq).

*

*Note: When benchmarking, please everyone remember - if you use the same array/list for two consecutive tests, the CPU cache will make the second one faster. *

A: Why should LINQ be faster? It also uses loops internally.
Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code.

A: LINQ is slower now, but it might get faster at some point. The good thing about LINQ is that you don't have to care about how it works. If a new method is thought up that's incredibly fast, the people at Microsoft can implement it without even telling you and your code would be a lot faster.
More importantly though, LINQ is just much easier to read. That should be enough reason.

A: It should probably be noted that the for loop is faster than the foreach. So for the original post, if you are worried about performance on a critical component like a renderer, use a for loop.
Reference:
In .NET, which loop runs faster, 'for' or 'foreach'?

A: You might get a performance boost if you use parallel LINQ for multi cores. See Parallel LINQ (PLINQ) (MSDN).

A: Coming in .NET core 7 are some significant updates to LINQ performance of .Min .Max, .Average and .Sum
Reference: https://devblogs.microsoft.com/dotnet/performance_improvements_in_net_7/#linq
Here is a benchmark from the post.

If you compare to a ForEach loop, than it becomes apparent that in .NET 6 the ForEach loop was faster and in .NET 7 the LINQ methods:

this was the code of the benchmark using BenchmarkDotNet
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;

public class Program
{
    public static void Main()
    {
        BenchmarkRunner.Run<ForEachVsLinq>();
    }
}

[SimpleJob(RuntimeMoniker.Net60)]
[SimpleJob(RuntimeMoniker.Net70)]
[MemoryDiagnoser(false)]
public class ForEachVsLinq
{
    private int[] _intArray;

    [GlobalSetup]
    public void Setup()
    {
        var random = new Random();
        var randomItems = Enumerable.Range(0, 500).Select(_ => random.Next(999));
        this._intArray = randomItems.ToArray();
    }

    [Benchmark]
    public void ForEachMin()
    {
        var min = int.MaxValue;
        foreach (var i in this._intArray)
        {
            if ( i < min)
                min = i;
        }
        Console.WriteLine(min);
    }

    [Benchmark]
    public void Min()
    {
        var min = this._intArray.Min();
        Console.WriteLine(min);
    }

    [Benchmark]
    public void ForEachMax()
    {
        var max = 0;
        foreach (var i in this._intArray)
        {
            if (i > max)
                max = i;
        }
        Console.WriteLine(max);
    }

    [Benchmark]
    public void Max()
    {
        var max = this._intArray.Max();
        Console.WriteLine(max);
    }

    [Benchmark]
    public void ForEachSum()
    {
        var sum = 0;
        foreach (var i in this._intArray)
        {
            sum += i;
        }
        Console.WriteLine(sum);
    }

    [Benchmark]
    public void Sum()
    {
        var sum = this._intArray.Sum();
        Console.WriteLine(sum);
    }
}

In .NET Core 6 and earlier versions the mentioned methods are slower than doing your own foreach loop and finding the min, max value, average or summarizing the objects in the array.
But in .NET Core 7, the performance increase makes these buildin LINQ methods actually a lot faster.
Nick Chapsas shows this in a benchmark video on YouTupe
So if you want to calculate the sum, min, max or average value, you should use the LINQ methods instead of a foreach loop from .NET Core 7 onwards (at least, from a performance point of view)


text:
Q: Reversed regex pattern much slower than original I have a rather complex regex search in place, and I recently had to extend it to a "reversed" pattern. This was easy to implement, but performance dropped roughly by a factor of 10.
I would appreciate any tips on how to improve this problem, but I'm not particular about how. It's ok, for example, to use two or more steps if this is faster than a single, very involved one.
Original pattern
import regex

expression = regex.compile(
    fr"""
(?:{CUE})  # cue before targets. non capture (?:)
(?:{PADDING})  # text before the match.
(?:
(?:{ITEM_SEPARATION})?  # none or once
(?P<targets>{targets_as_regex})
)+
""",
    regex.VERBOSE,
)

Need to know: CUE is a rather short list of options, something like:
CUE = r"""word
|two\swords
|simple\soptions?
"""

This is about 5-15 options, quite simple (a bit simpler for the reversed scenario).
PADDING is literally anything, but no longer than 150. (PADDING = r".{0,150}?"). In the reversed scenario it's a bit more restrictive, only [,A-Za-z\d\s]
ITEM_SEPARATION is simple: optional spaces followed by either comma, bounded " y " and more optional spaces:
ITEM_SEPARATION = r"""
\s*          # optional spaces
(?:,|\by\b)  # non-capture, either comma, or 'y' (with bounds)
\s*          # optional spaces
"""

Finally, the problem is likely in targets_as_regex, which is a big list of bounded names. This can easily be hundreds or thousands of options, although each call will pass a unique list of targets.
The idea is to match something like:

This is a text, with a cue, then a bit more text and a match, other match y final match. And after the "." we stop matching.

And it performs sufficiently well. But then we have the reversed situation:
Reversed pattern
The idea is to match this:

This not a match, because of the stop. This is a match, another match y final match, because now we find a cue. Etc.

I naturally recycled my pattern:
expression = regex.compile(
    fr"""
(
(?P<targets>{targets_as_regex})
(?:{ITEM_SEPARATION})?
)+
(?:{SIMPLE_PADDING})  # text before the match
(?:{CUE_AFTER})  # cue after targets
""",
    regex.VERBOSE,
)

It works as expected, but performance is very poor when targets (that are many) come before cues (which are few).
What I tried
I added a basic check where we omit the whole thing if the cue is not in the text at all, but it did not help very much. Another idea that I have tested is to search all matches for the targets (regardless of cues and all that) and then pass a shortened list (targets_as_regex) with only these matches to the slow pattern. This actually helps, but not by much (still close to that x10 drop in performance).
Any other ideas that could help?

A: The ((?P<targets>{targets_as_regex})(?:{ITEM_SEPARATION})?)+ is a well-known catastrophic backtracking prone pattern (analogous to (a+b?)+ which is reduced to (a+)+), and the more to the left of the pattern, the more dangerous.
You need to "unroll" patterns like (a+b?)+ into a+(?:ba+)* making the subsequent subpatterns match only at different positions inside the string.
The pattern you need is
fr"""(?:{targets_as_regex})(?:{ITEM_SEPARATION}(?:{targets_as_regex}))*(?:{SIMPLE_PADDING})(?:{CUE_AFTER})"""

To speed it up, you need a regex trie built from the targets_as_regex, see Speed up millions of regex replacements in Python 3.