text:
Q: jquery mobile url parameter not updating in browser, but getting correct one with "data-url" I created the following example to show what I am experiencing.
If I navigate from page1 to page 2 with the button Page 2a, the URL will be ...#page2?id=a as expected.
When I click the button to go back to Page 1, then navigate to Page 2b, the URL will still show "#page2?id=a", but the  tag is clearly has an href of "#page2?id=b" along with the $(e.target).attr("data-url") being "#page2?id=b" when I get to #page2.
Any ideas what is going on here?  Thanks in advance for any help.

      <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />

Page 1

            Page 2a
            Page 2b

            Page1

Code sample is here on jsfiddle too.

A: I was able to resolve this issue by using the jqm.page.params plugin  with help from this question on stackoverflow.  Here is my code for using this plugin:

      <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />

      //Added the jqm.page.params plugin

Page 1

            Page 2a
            Page 2b

            Page1

A: The problem is with appended url variables with ajax navigation. JQM uses the appended variables with its own navigation. According to the docs, either lose the ajax navigation, or lose the variables. Breaking it up into several pages with rel="external" would also fix the problem if a web site (not app).


text:
Q: Replacing "infinite" with "finite" of a statement
Statement: The intersection of a finite collection of open subsets of $R^n$ is open in $R^n$.

Proof of the statement:
Suppose that $\mathcal{O}=\bigcap_{i=1}^{k}\mathcal{O}_i$ for some $k$, where $\mathcal{O}_i$ is open in $R^n$. Let ${\bf u}$ be a member of $\mathcal{O}$. If $1\leq i\leq k$, ${\bf u}$ belongs to $\mathcal{O}_i$ and $\mathcal{O}_i$ is open in $R^n$, so there is a positive number $r_i$ such that $\mathcal{B}_{r_i}({\bf u})\subseteq\mathcal{O}_i$. Define $r=\min\{r_1,\cdots,r_k\}$. Then $r$ is positive, and the open ball about the point $u$, $\mathcal{B}_r({\bf u})$, is contained in each $\mathcal{O}_i$ and therefore is contained in the intersection $\bigcap_{i=1}^{k}\mathcal{O}_i=\mathcal{O}$. Thus ${\bf u}$ is an interior point of $\mathcal{O}$. Therefore, every point in $\mathcal{O}$ is an interior point of $\mathcal{O}$, so $\mathcal{O}$ is open in $R^n$.

Now, if I replace "finite" with "infinite", the sentence "Then $r$ is positive, and the open ball about the point $u$, $\mathcal{B}_r({\bf u})$, is contained in each $\mathcal{O}_i$.........."  will be wrong. Because there are infinite many balls and we choose $r$ be the minimum radius, there must exists a ball that contain an element that lies on the boundary, so the intersection of a finite collection of open subsets of $R^n$ is closed in $R^n$.

Can someone check my logic? If not right, please point me out where I do wrong. Thanks

A: There is not necessarily a minimum to an infinite set of numbers. What if the set of balls is $\{A_n\}$ where $A_n=B_{1+1/n}(u)$? The radii of the balls are $\{2,3/2,4/3,5/4,...\}$. There is no minimum.
Also be careful with open and closed sets. If a set in $\mathbb R^n$ contains an element of its boundary, it is not open. But that does not mean that it is closed. A set is closed if its complement is open.
The phrase

there must exists a ball that contain an element that lies on the boundary

doesn't make much sense. You should make this statement precise. In doing so, you may find that what you mean to say is not actually true.
Finally, note that an infinite intersection of open sets could be open, it just doesn't have to be.

A: The first proof is correct, the second one not. Consider $A_n=\left(0,1+\frac{1}{n}\right)$, than $\bigcap_{n\in\mathbb N} A_n=(0,1]$ is neither open nor closed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Computer hangs on bulk insert of a 500mb file with c# I have text file of 550mb.When I run this code computer hangs after 10 mins and data insertion fails but this works fine for file of 100mb
 public static void BulkUpdate(string col, System.IO.StreamReader sr, string tableName)
    {
        ConnStr = ConfigurationSettings.AppSettings["ConnStrAffiliate"].Trim();
        SqlConnection myConn = DAO.fetchConnection();
 string[] value = col.Split(new char[] { '\t' },StringSplitOptions.RemoveEmptyEntries);
        DataTable dt = new DataTable();
        DataRow row;
        foreach (string dc in value)
            {
             dt.Columns.Add(new DataColumn(dc, typeof(string)));
}

        while (!sr.EndOfStream)
        {
            value = sr.ReadLine().Split(new char[] { '\t' });
            List<string> valueList = value.ToList();
            valueList.RemoveAt(valueList.Count - 1);
            value = valueList.ToArray();
            if (value.Length == dt.Columns.Count)
            {
                row = dt.NewRow();
                row.ItemArray = value;
                dt.Rows.Add(row);
            }
        }
        SqlBulkCopy bc = new SqlBulkCopy(ConnStr, SqlBulkCopyOptions.TableLock);
        bc.DestinationTableName = tableName;
        bc.BatchSize = dt.Rows.Count;
        bc.WriteToServer(dt);
        bc.Close();
    }

A: I suggest installing Glimpse (http://getglimpse.com/) and then see what the webserver is doing. My first hunch is that you are hitting a timeout value somewhere. You may also want to check the event logs to see if IIS logged an exception.

A: How much memory do you have available?  You could break the file up into smaller parts first and load it into a staging table.

A: I dont know what the problem was but i have tried Sql Server Integration services for reading and uploading the file into database.It was a success and takes much less time


text:
Q: How to create unit test for angulajs filter with dependency? How ot create unit tests for me Angularjs filter called ?  Current code gives me error:

Error: [$injector:unpr]
  http://errors.angularjs.org/1.6.0/$injector/unpr?p0=DateForFrontEndFilterFilterProvider%20%3C-%20DateForFrontEndFilterFilter
              at public/scripts/angular/angular.min.js:6:425
              at public/scripts/angular/angular.min.js:44:395

My code is following:
Filter code:
app.filter('DateForFrontEndFilter', ['$filter', 'ngOtherSettings', function($filter, ngOtherSettings) {
    return function(date) {
        var format = ngOtherSettings.FrontEndDateFormat;
        var result = $filter('date')(date, format, null);

Test code:
describe('DateForFrontEndFilter tests', function() {
    beforeEach(function() {

        module.apply('myApp');

        inject(function($injector) {
            filter = $injector.get('$filter')('DateForFrontEndFilter');
        });

        var testDate = "10/12/2017 10:32:12";
    });

    it('check date from DateForFrontEndFilter for date with format long', function() {

        var ngOtherSettings = { FrontEndDateFormat: 'dd/MM/yyyy HH:mm:ss' };
        var result = filter(ngOtherSettings, testDate);
        expect(result).toBe(testDate + "sda");
    });
            return result;
        };
    }]);
...


text:
Q: Swift, iOS 9.3.2 xCode 7.3: How to debug application not seeing GPX file airdropped in CS193 Trax application I am trying to duplicate CS193 Trax Swift application where GPX file is airdropped to IOS device and Trax application sees it.
Problem is that Trax application does not see file and I think I have set everything up properly.
I updated info.plist to permit GPX file with:
<array>
    <dict>
        <key>CFBundleTypeIconFiles</key>
        <array/>
        <key>CFBundleTypeName</key>
        <string>GPX File</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>edu.stanford.cs193p.gpx</string>
        </array>
    </dict>
</array>
<array>
    <dict>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.xml</string>
        </array>
        <key>UTTypeDescription</key>
        <string>GPX file</string>
        <key>UTTypeIdentifier</key>
        <string>edu.stanford.cs193p.gpx</string>
        <key>UTTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key>
            <array>
                <string>gpx</string>
            </array>
        </dict>
    </dict>
</array>

I also added (because I have had problems with this before):
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

I have verified in the apps info view that Document types is displaying GPX and imported UTIs is GPX.
Application is a copy of Pauls Trax demo app which only contains an application delegate call to:
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool
{
    print ("url = \(url)")
    return true
}

Airdropping vacation.gpx which Mac sees as a GPX file displays message on iPhone:
AirDrop
..mac.. would like to share a file that requires an app from the App store.  It shows GPX icon below.
e.g.  it is trying to transfer the file as a GPX file but it doesn't know that my app can process it.
How do I debug?
I set a breakpoint in the only function I have in my app and it is never called.
DOn't know what else to look at.


text:
Q: listView.SortKey = ColumnHeader.Index - 1 I am converting VB to VB.NET and I found two error which i have no idea to solve it
listView.SortKey = ColumnHeader.Index - 1

listView.Sorted = False

I know that SortKey is getting the column index for sorting and  listView.Sorted  is setting turn off or on sorting.
but how is the code in vb.net?

A: You can use ListView1.Sorting = SortOrder.None to turn off the sort.
To sort on a particular column, you can use the ListViewItemSorter
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.listviewitemsorter.aspx
However, when you have assigned a custom sorting class to the .ListViewItemSorter, you cannot disable the sort. You have to assign a new ListView1.ListViewItemSorter = Nothing AND set SortOrder.None.


text:
Q: How to escape special characters in a variable to provide commandline arguments in bash I very often use find to search for files and symbols in a huge source tree. If I don't limit the directories and file types, it takes several minutes to search for a symbol in a file. (I already mounted the source tree on an SSD and that halved the search time.)
I have a few aliases to limit the directories that I want to search, e.g.:
alias findhg='find . -name .hg -prune -o'
alias findhgbld='find . \( -name .hg -o -name bld \) -prune -o'
alias findhgbldins='find . \( -name .hg -o -name bld -o -name install \) -prune -o'

I then also limit the file types as well, e.g.:
findhgbldins \( -name '*.cmake' -o -name '*.txt' -o -name '*.[hc]' -o -name '*.py' -o -name '*.cpp' \)

But sometimes I only want to check for symbols in cmake files:
findhgbldins \( -name '*.cmake' -o -name '*.txt' \) -exec egrep -H 'pattern' \;

I could make a whole bunch of aliases for all possible combinations, but it would be a lot easier if I could use variables to select the file types, e.g:
export SEARCHALL="\( -name '*.cmake' -o -name '*.txt' -o -name '*.[hc]' -o -name '*.py' -o -name '*.cpp' \)"
export SEARCHSRC="\( -name '*.[hc]' -o -name '*.cpp' \)"

and then call:
findhgbldins $SEARCHALL -exec egrep -H 'pattern' \;

I tried several variants of escaping \, (, * and ), but there was no combination that did work.
The only way I could make it to work, was to turn off globbing in Bash, i.e. set -f, before calling my 'find'-contraption and then turn globbing on again.
One alternative I came up with is to define a set of functions (with the same names as my aliases findhg, findhgbldins, and findhgbldins), which take a simple parameter that is used in a case structure that selects the different file types I am looking for, something like:
findhg {
    case $1 in
        '1' )
            find <many file arguments> ;;
        '2' )
            find <other file arguments> ;;
        ...
    esac
}

findhgbld {
    case $1 in
        '1' )
            find <many file arguments> ;;
        '2' )
            find <other file arguments> ;;
        ...
    esac
}

etcetera

My question is: Is it at all possible to pass these types of arguments to a command as a variable ?
Or is there maybe a different way to achieve the same i.e. having a combination of a command (findhg, findhgbld,findhgbldins) and a single  argument to create a large number of combinations for searching ?

A: It's not really possible to do what you want without unpleasantness. The basic problem is that when you expand a variable without double-quotes around it (e.g. findhgbldins $SEARCHALL), it does word splitting and glob expansion on the variable's value, but does not interpret quotes or escapes, so there's no way to embed something in the variable's value to suppress glob expansion (well, unless you use invalid glob patterns, but that'd keep find from matching them properly too). Putting double-quotes around it (findhgbldins "$SEARCHALL") suppresses glob expansion, but it also suppresses word splitting, which you need to let find interpret the expression properly. You can turn off glob expansion entirely (set -f, as you mentioned), but that turns it off for everything, not just this variable.
One thing that would work (but would be annoying to use) would be to put the search options in arrays rather than plain variables, e.g.:
SEARCHALL=( \( -name '*.cmake' -o -name '*.txt' -o -name '*.[hc]' -o -name '*.py' -o -name '*.cpp' \) )
findhgbldins "${SEARCHALL[@]}" -exec egrep -H 'pattern' \;

but that's a lot of typing to use it (and you do need every quote, bracket, brace, etc to get the array to expand right). Not very helpful.
My preferred option would be to build a function that interprets its first argument as a list of file types to match (e.g. findhgbldins mct -exec egrep -H 'pattern' \; might find make/cmake, c/h, and text files). Something like this:
findhgbldins() {
filetypes=()
if [[ $# -ge 1 && "$1" != "-"* ]]; then # if we were passed a type list (not just a find primitive starting with "-")
    typestr="$1"
    while [[ "${#typestr}" -gt 0 ]]; do
        case "${typestr:0:1}" in # this looks at the first char of typestr
            c) filetypes+=(-o -name '*.[ch]');;
            C) filetypes+=(-o -name '*.cpp');;
            m) filetypes+=(-o -name '*.make' -o '*.cmake');;
            p) filetypes+=(-o -name '*.py');;
            t) filetypes+=(-o -name '*.txt');;
            ?) echo "Usage: $0 [cCmpt] [find options]" >2
               exit ;;
        esac
        typestr="${typestr:1}" # remove first character, so we can process the remainder
    done
    # Note: at this point filetypes will be something like '-o' -name '*.txt' -o -name '*.[ch]'
    # To use it with find, we need to remove the first element (`-o`), and add parens
    filetypes=( \( "${filetypes[@]:1}" \) )
    shift # and get rid of $1, so it doesn't get passed to `find` later!
fi

# Run `find`
find . \( -name .hg -o -name bld -o -name install \) -prune -o "${filetypes[@]}" "$@"
}

...you could also use a similar approach to building a list of directories to prune, if you wanted to.
As I said, that'd be my preferred option. But there is a trick (and I do mean trick), if you really want to use the variable approach. It's called a magic alias, and it takes advantage of the fact that aliases are expanded before wildcards, but functions are processed afterward, and does something completely unnatural with the combination. Something like this:
alias findhgbldins='shopts="$SHELLOPTS"; set -f; noglob_helper find . \( -name .hg -o -name bld -o -name install \) -prune -o'
noglob_helper() {
    "$@"
    case "$shopts" in
        *noglob*) ;;
        *) set +f ;;
    esac
    unset shopts
}
export SEARCHALL="( -name *.cmake -o -name *.txt -o -name *.[hc] -o -name *.py -o -name *.cpp )"

Then if you run findhgbldins $SEARCHALL -exec egrep -H 'pattern' \;, it expands the alias, records the current shell options, turns off globbing, and passes the find command (including $SEARCHALL, word-split but not glob-expanded) to noglob_helper, which runs the find command with all options, then turns glob expansion back on (if it wasn't disabled in the saved shell options) so it doesn't mess you up later. It's a complete hack, but it should actually work.


text:
Q: How do I copy the list of files from a global search in Xcode to an editor? I would like the results from find navigator in an external list so I can freely organize/mark them. Is there a way to do this?
I have tried copying them but there is no 'paste' option for programs useful for dealing with lists, such as Excel.


text:
Q: How to export Outlook email body to a Unicode text file? My emails in Outlook 2010 have Unicode characters inside their body, so when I want to export them to a .txt file (Tab Separated In Windows) I got many question marks in output file!
How can I fix this problem? Is there any option in Outlook to change that file's format?

A: In Outlook when you save as text it will, by default, use the default system codepage. It's a bit unclear but you can change this behavior.
After you click on Save As and choose a filename you get this warning:

You have to click on No to get an option to change the format. When you do you get this dialog:

Select the Other encoding: radio button and select Unicode in the list. This will give you a text file encoded as Unicode without the question marks or boxes.


text:
Q: ¿porque gulp-imagemin no me funcina?

const {series,src,dest,watch} = require("gulp");
const sass = require('gulp-sass')(require('sass'));
const imagemin = require("gulp-imagemin");

// Funcion que compila sass

function css() {
  return src("src/scss/app.scss").pipe(sass({
    outputStyle:"expanded"
  }))
  .pipe(dest("./build/css"));
}

function minificarcss() {
  return src("src/scss/app.scss").pipe(sass({
    outputStyle:"compressed"
  })).pipe(dest("./build/css"));

}

function imagenes() {
  return src("src/img/**/*")
  .pipe(imagemin())
  .pipe(dest("./build/img"));
}

function watchArchivo() {
  watch("src/scss/**/*.scss",css);// * = la carpeta actual - ** = Todos los archivos con esa extensionCsss
}

exports.css = css;
exports.minificarcss = minificarcss;
exports.imagenes = imagenes;
exports.watchArchivo = watchArchivo;

este es mi gulpfile de mi proyecto ,pero cuando quiero ejecutar gulp imagenes
me sale este error:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\Toshiba\Desktop\musicaRock\node_modules\gulp-imagemin\index.js
require() of ES modules is not supported.
require() of C:\Users\Toshiba\Desktop\musicaRock\node_modules\gulp-imagemin\index.js from C:\Users\Toshiba\Desktop\musicaRock\gulpfile.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\Toshiba\Desktop\musicaRock\node_modules\gulp-imagemin\package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (C:\Users\Toshiba\Desktop\musicaRock\gulpfile.js:3:18)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12) {

code: 'ERR_REQUIRE_ESM'
}
he buscado por todas partes la solucion pero no me aprece nada y intentado con muchas formas para solucinar el problema pero no he tenido exito,me gustaria un poco ayuda para resolver este problema gracias

A: bro, acabo de resolver el mismo problema (tambien estoy haciendo el curso xd),
yo borre del package.json el 'gulp-imagemin' y volvi a instalar esto: npm i -D gulp-imagemin@7.0.0  es una version mas vieja, esto lo saque de las respuestas del curso, me acaba de funcionar, me paso algo parecido con la version de sass, tuve que emparchar, espero te sirva

A: siguiendo la respuesta de hernan

*

*borre la carpeta gulp-imegemin dentro de la carpeta node_modules

*ejecute la instalacion, pero con la diferencia que la ejecute como
dependencia de desarrollo
npm install --save-dev gulp-imagemin@7.0.0

*volvi a ejecutar gulp imagenes y funciono....

A: Ya que la versión de imagemin 8 ahora es ESM puro, (Nota del autor al respecto) si deseas usarlo en el sistema de módulos de commonjs, deberás cargarlo de la siguiente manera:

const imageminJpegtran = require('imagemin-jpegtran');

async function main() {
  const imagemin = (await import('imagemin')).default;
  const files = await imagemin(['images/*.{jpg,png}'], {
    destination: 'build/images',
    plugins: [imageminJpegtran()]
  });
}

main();

Recomiendo no usar las versiones antiguas de estos plugins, ya que la mayoría tienen dependencias con vulnerabilidades criticas de seguridad.


text:
Q: Continue query exception when fill(null) used This continue query:
select mean(elapsed) as average, percentile(elapsed,95) as percentile_95, max(elapsed) as maximum from /^Jmeter./ group by time(1s) fill(null) into 1sec.timing.:series_name backfill(false)*
cause to error:
[2015/07/01 08:05:38 IDT] EROR Couldn't write data for continuous query: %!(EXTRA *errors.errorStr
ing=proto: Marshal called with nil)
and doesnt works.
Without fill(null) the CQ works fine, but i need to fill the intervals in series.
Is some workaround exists?

A: In InfluxDB (v0.8), a continuous query inserts the results of each run of the query into a series. If a run of the CQ produces no results, nothing is written to the series.
By definition, a FILL(null) returns no result so nothing is written to the series for that run of the CQ.
To accomplish what I think you're trying to do, query the series created by the CQ with a FILL(null) and a GROUP BY time(1s). For example,
SELECT average, percentile_95, maximum FROM 1sec.timing.:series_name GROUP BY time(1s) FILL(null)


text:
Q: coinbase api call resulted in a `403 Forbidden` response I'm trying to integrate Coinbase Wallet PHP Library.
here is my code to get current BTC buy price
<?php

require_once 'vendor/autoload.php';

use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Resource\Address;
use Coinbase\Wallet\Resource\Account;

$apiKey = '**********';
$apiSecret = '*************';
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);

try {
    $buyPrice = $client->getBuyPrice('BTC-USD');
} catch (Exception $exc) {
    echo '
';
    echo $exc->getTraceAsString();
    echo '
';
    echo $exc->getMessage();
    echo '
';

}
?>

above code work perfectly, but some time it throw following error
#0 C:\xampp\htdocs\coinbase\vendor\coinbase\coinbase\src\HttpClient.php(137): Coinbase\Wallet\Exception\HttpException::wrap(Object(GuzzleHttp\Exception\ClientException))
#1 C:\xampp\htdocs\coinbase\vendor\coinbase\coinbase\src\HttpClient.php(121): Coinbase\Wallet\HttpClient->send(Object(GuzzleHttp\Psr7\Request), Array)
#2 C:\xampp\htdocs\coinbase\vendor\coinbase\coinbase\src\HttpClient.php(74): Coinbase\Wallet\HttpClient->request('GET', '/v2/prices/BTC-...', Array)
#3 C:\xampp\htdocs\coinbase\vendor\coinbase\coinbase\src\Client.php(820): Coinbase\Wallet\HttpClient->get('/v2/prices/BTC-...', Array)
#4 C:\xampp\htdocs\coinbase\vendor\coinbase\coinbase\src\Client.php(118): Coinbase\Wallet\Client->getAndMapMoney('/v2/prices/BTC-...', Array)
#5 C:\xampp\htdocs\coinbase\index.php(16): Coinbase\Wallet\Client->getBuyPrice('BTC-USD')
#6 {main}
Client error: `GET https://api.coinbase.com/v2/prices/BTC-USD/buy` resulted in a `403 Forbidden` response:

Please suggest.
Thanks

A: I had a similiar issue connecting this API, but not using the libary.
I think it is some kind of protection from Cloudflare. I managed to circumvent it adding some additional headers to fake a "real" browser, especially the "User-Agent":
        $url = 'https://api.coinbase.com/v2/prices/BTC-EUR/spot';
        $response = wp_remote_get($url, array(
                'timeout' => 120,
                'headers' => array(
                    'CB-VERSION' => '2017-05-19',
                    'Accept' => '*/*',
                    'Accept-Language' => 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
                    'Cache-Control' => 'no-cache',
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 OPR/45.0.2552.882'
                )
            )
        );

(wp_remote_get is from WordPress)


text:
Q: How can I make real-time list using Node.js and Firebase I'm using Using Firebase and Node.js I'm trying to make a real-time list, see code below:
router.get('/', (req, res) => {
    db.ref('contacts').on('value', (snapshot) => {
        const data = snapshot.val();
        console.log(data);
        res.render('index', { contacts: data });
    });
});

but is giving me this error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

A: Your code is trying to send multiple responses from an Express route.  The error message is telling you that's not possible.  Once you call res.render(), you are declaring the full response to be sent to the client, and that's all you can send.  The client will have to make another request to get an update.
If you want to keep a socket open to the client to send updates over time, you're going to need a websocket or some other way to keep the connection open.  express-ws is one thing to try on the backend.  Note that this will not work with Cloud Functions and probably other serverless providers.


text:
Q: Passportjs: Cannot read property 'connection' of undefined at Strategy._verify Using passportjs for authentication in my node.js application but getting the error above. This is my code below
app.js
passport.use(new LocalStrategy({usernameField: 'email'},function(email, password, res, done) {
    res.locals.connection.query('SELECT id, password FROM users WHERE email = ?', [email], function(err, user) {
        console.log(user);

        if (err) {return done(err)};

        if (user.length === 0) {
            done(null, false);
        };

        const hash = user[0].password.toString();
        console.log(hash);

        bcrypt.compare(password, hash, function(err, res) {
            if (res === true) {
                return done(null, {user_id: user[0].id});
            } else {
                return done(null, false);
            }
        });
    });
}
));

index.js
router.post('/', passport.authenticate('local', {
    successRedirect: 'home',
    failureRedirect: '/'
}));

What could be wrong with my code?


text:
Q: How to find items not in a table My database has,
mysql> select * from peeps;
+-------+
| name  |
+-------+
| tom   |
| dick  |
| harry |
+-------+

I want to write a sql statement to return a result set of users not in that table.
sql ????  where name in ( 'dave', 'tom')

I want a result set which returns 'dave'.  The answer can't return 'harry'.  I'm not keen on creating a new temporary table, can this be dont in a single statement.
Thanks!

A: Would something like this work for you? It returns dave as requested.
SELECT a.name
FROM
    (SELECT 'dave' AS name
    UNION ALL
    SELECT 'tom' AS name) a
LEFT JOIN peeps b ON b.name = a.name
WHERE b.name IS NULL

Result
| NAME |
--------
| dave |
SQL Fiddle


text:
Q: How can I add checkbox values to setState array in reactJS I know this question has been asked before but I have an array I'm looping over the array getting data from that array and displaying that data in a list and in that list I have checkbox I want to get some data when the checkbox is ticked and store in a state array
this is my code so far, the issue that I am having now is that the first click on the first checkbox registers as an empty array and the consecutive clicks after store the values in the array I think that us due to the fact that useState is set to empty how can I change the code so that I store the values of the checkbox in an array to be used later

    const [checkList, setCheckList] = useState([]);

    const handleChange = e => {
        setCheckList([...checkList, e]);
        setChecked(prev => !prev);
        console.log(checkList);
      };

    <List>
          {someList.map(w => (
            <ListItem key={w.id}>
              <ListItemIcon>
                <ReactSVG
                  style={{ height: '35px', width: '35px' }}
                  src={w.logo}
                />
              </ListItemIcon>
              <ListItemText primary={w.name} />
              <ListItemSecondaryAction>
                <Checkbox
                  edge="end"
                  onChange={e => handleChange(e.target.value)}
                  value={w.id}
                  // checked={checked}
                />
              </ListItemSecondaryAction>
            </ListItem>
          ))}
        </List>

A: Checked should be determined based on checkList items. and handleChange should update the state depending on the checked value of the checkbox. Check my solution.
export default function App() {
  const [checkList, setCheckList] = useState([]);

  const workspaces = [
    {
      id: 1,
      name: "hello"
    },
    {
      id: 2,
      name: "hello2"
    }
  ];
  const handleChange = e => {

    if (e.target.checked === true) {
      setCheckList([...checkList, Number(e.target.value)]);
    } else {
      const selectedAcc = checkList.filter(a => {
        if (a === Number(e.target.value)) return false;
        return true;
      });
      setCheckList([...selectedAcc]);
    }
  };

  return (
    <div className="App">
      <List>
        {workspaces.map(w => (
          <ListItem key={w.id}>
            <ListItemText primary={w.id} />
            <ListItemSecondaryAction>
              <Checkbox
                edge="end"
                onChange={e => handleChange(e)}
                value={w.id}
                checked={
                  checkList.lastIndexOf(Number(w.id)) >= 0 ? true : false
                }
              />
            </ListItemSecondaryAction>
          </ListItem>
        ))}
      </List>
    </div>
  );
}


text:
Q: I am finding it difficult to create an .exe from python script using pyinstaller. My script executes perfectly but when i run the .exe i get traceback My Python script executes perfectly in a virtual environment which has python 3.9.2 but when i create an exe using pyinstaller the exe doesn.t work, i get tracebacks of certain modules missing but when i add the missing modules with the help of spec files it then gives a traceback of some other modules missing on and on.
File "modin\config\pubsub.py", line 118, in get
File "modin\config\envvars.py", line 32, in _get_raw_from_config
File "os.py", line 669, in getitem
KeyError: 'MODIN_ENGINE'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "file.py", line 1
118, in
File "file.py", line 8
38, in commonsteps
File "swifter\swifter.py", line 358, in apply
File "swifter\swifter.py", line 259, in _modin_apply
File "", line 961, in _find_and_load
File "", line 950, in find_and_load_unlocked
File "", line 655, in load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
File "modin\pandas_init.py", line 180, in
File "modin\config\pubsub.py", line 107, in subscribe
File "modin\pandas_init.py", line 109, in _update_engine
File "modin\config\pubsub.py", line 120, in get
File "modin\config\envvars.py", line 75, in _get_default
File "", line 961, in _find_and_load
File "", line 950, in _find_and_load_unlocked
File "", line 655, in load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
File "distributed_init.py", line 1, in
File "", line 961, in _find_and_load
File "", line 950, in _find_and_load_unlocked
File "", line 655, in _load_unlocked
File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
File "distributed\config.py", line 17, in
FileNotFoundError: [Errno 2] No such file or directory: 'D:\01_xew\02_ret

after getting this traceback i tried to specify the modin engine in the script but then got this traceback
Traceback (most recent call last):
  File "swifter\swifter.py", line 340, in apply
  File "DTC_dask.py", line 840, in compare
  File "pandas\core\ops\common.py", line 65, in new_method
  File "pandas\core\ops\__init__.py", line 365, in wrapper
ValueError: Can only compare identically-labeled Series objects

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "DTC_dask.py", line 1127, in <module>
  File "DTC_dask.py", line 847, in commonsteps
  File "swifter\swifter.py", line 358, in apply
  File "swifter\swifter.py", line 259, in _modin_apply
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
  File "modin\pandas\__init__.py", line 180, in <module>
  File "modin\config\pubsub.py", line 107, in subscribe
  File "modin\pandas\__init__.py", line 122, in _update_engine
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
  File "distributed\__init__.py", line 1, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller\loader\pyimod03_importers.py", line 476, in exec_module
  File "distributed\config.py", line 17, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\TTC01017\\Documents\\My Received Files\\exe_392_dask\\distributed\\distributed.yaml'
[16400] Failed to execute script 'DTC_dask' due to unhandled exception!

After this when i try to add the missing directory to the exe using spec file it further then gives a traceback of some other module missing
I guess the main issue here is pyinstaller not properly coping the dependent libraries to the exe.... can anyone help with this issue and how to create the pyinstaller with spec file which takes care of all the dependent libraries.

A: In both cases a FileNotFoundError is thrown, double check that the file path is correct and if that is the case try using / instead of \\
'C:/Users/TTC01017/Documents/My Received Files/exe_392_dask/distributed/distributed.yaml'


text:
Q: jQuery Quadratic equations Whats wrong in my code for solving jQuery Quadratic equations ?
a = parseFloat($('#a').val());
b = parseFloat($('#b').val());
c = parseFloat($('#c').val());
root = Math.sqrt(Math.pow(b, 2) - (4 * a * c));
x1 = (-b + root) / 2 * a;
x2 = (-b - root) / 2 * a;

function validateForm(){
            $('#result1').fadeIn('slow');
            $('#result2').fadeIn('slow');
            $('#result1').html('First ans equal' + x1);
            $('#result2').html('Second ans equal' + x2);
}

Maybe its the root, or the POW ? Help me to figure this out please

A: its simple maths. jQuery/Javascript has very little to contribute in this.
for the jquery/Javascript part:
make sure #a, #b,#c have values when you run your code. i.e.
 $('#a').val() = some valid Float text

one thing you can do in this regard is to wrap your variables a,b,c inside a function.
and call the function on some button click or only after you're sure that #a,#b,#c have value.
see below illustration:
var x1,x2;
function calculate(){

     a = parseFloat($('#a').val());
     b = parseFloat($('#b').val());
     c = parseFloat($('#c').val());

     root = Math.sqrt(Math.pow(b, 2) - (4 * a * c));

     x1 = (-b + root) / 2 * a;
     x2 = (-b - root) / 2 * a;
}

$('#validate').on("click",function(){
     calculate();
    $('.result').html('').append('first answer'+x1).append('second answer'+x2);
});

Maths Part.
It will work fine as long as your quadratic equation has rational roots. i.e. if you give your
coefficients(a,b,c) a value, that your quadratic equation has no rational roots, in that case you will get NaN in your x1 and x2, because the result that you get are not Real Numbers but a Complex Number.
so everytime Math.pow(b, 2) - (4 * a * c) < 0, you are not going to get any real roots i.e. you will get NaN inside x1 and x2
see this fiddle


text:
Q: which techniques are used for these kinds of animations? Here there are really, really great and helpful animations, which I'd love to learn. Which iOS-techniques are used to achieve those? UI Dynamics? A simple [UIView animateWithDuration], Cocos2D or what?

A: Yes you can achieve such animations by playing and experimenting with UI Dynamics and with Simple [UIView animateWithDuration].
Here are some useful links regarding UIView and UI Dynamic animations.
1) View Programming Guide for iOS
2) Introduction to UIKit Dynamics.
3) Animation in iOS.
4) Custom Navigation Transitions & More
Hope this will helps you.


text:
Q: Sending Slack message via windows Curl I'm try to send Slack messages with Slack API and curl command on C++ Console Application but I can't solve this error due to String type:
Curl command (this command successfully send a message)
curl -X POST -H "Content-type:application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.slack.com/services/{API_KEY}

C++ code:
#include <iostream>
#include <string>
int main()
{
    std::string command = "curl -X POST -H \"Content - type:application / json\" --data \"{\"text\":\"A New Program Has Just Been Posted!!!\"}\" https://hooks.slack.com/services/{API_KEY}";
    system(command.c_str());
    return 0;
}

As you can see on this picture I can't send message (I need to see OK):

A: You need more escaping. You've escaped the shell "s, but not the JSON "s.
#include <iostream>
#include <string>

int main()
{
    std::string command = "curl -X POST -H \"Content-Type: application/json\" --data \"{\\\"text\\\":\\\"A New Program Has Just Been Posted!!!\\\"}\" https://hooks.slack.com/services/{API_KEY}";
    system(command.c_str());
}

Just like \" is an escaped quote, \\ is an escaped backslash. So a "double-escape" looks like \\\". Yuck!
Since C++11 this may (or may not) be clearer using raw string literals, like this:
#include <iostream>
#include <string>

int main()
{
    std::string command = R"(curl -X POST -H "Content-Type: application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.slack.com/services/{API_KEY})";
    system(command.c_str());
}

(I have also corrected your Content-Type header.)
In any case, I suggest you use libcurl rather than executing shell commands.


text:
Q: Tracker computation not working in production I have a Tracker.autorun function:
Tracker.autorun(function(){
    console.log('tst1');
    if(Meteor.user()) {
        Router.go('MyRouteName');
    }
    else {
        Router.go('Route2');
    }

});

When I run my meteor app with production, this function doesn't work. Error printed on console is:

Exception from Tracker afterFlush function:  'e5f8fe47959145548e982acc170a59633baa3fe3.js?meteor_js_resource=true'.

How to proceed?

A: Solved the problem. Apparently firefox debugger (firebug) is better than chrome debugger. I was using a var which was undefined in the onCreated function. Hence the code never reached the autorun part.


text:
Q: Toggle silent mode with automation in iOS? Is it possible to enable/disable Silent mode using Automation in Shortcuts on iPhone?
If not, is it possible to detect the position of the silent rocker switch?
I am not interested in toggling DND for this scenario.

A: As far as I can tell, this isn't possible without jailbreaking. Could I know your use case and see if a clever implementation of DND could work?

A: It is now possible to detect the volume of the device using Automation:

*

*Add action

*Select 'If'

*Select 'Device Details'

*Click 'Device Details'

*Select 'Volume'

*Select 'Greater than or equal to'

*Type a number in the range of 0.00-1.00, for example 0.07 is the first notch on the volume bar

However it seems like it is still not possible to check whether the silent rocker switch is on.


text:
Q: Trying to insert user defined objects into a vector while i read values from a directory of files I am trying to open a directory and read the 4 text files with different number of iterative and selection statements.
having trouble with the while and for loop something going wrong but i can't figure it out. pretty new to c++
#include <iostream>
#include <dirent.h>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <fstream>

using namespace std;

typedef struct { // typedef for all the counters
string fName; // to store the file name
int countFor = 0;
int countIf = 0;
int countWhile = 0;
int countSwitch = 0;
int countElse = 0;
int total = 0;
} counters;

string filepath;

static const int S = 4;

vector<counters> files(S);
DIR *dp = NULL; //typedef in dirent.h
struct dirent *d;

void print();

int main()
{

cout << "************************Welcome!*****************************" << endl;
cout << "This program is designed to check plagiarism using simple" << endl;
cout << "measures between the files within the directory entered by user " << endl;
cout << "*************************************************************" << endl;

string directory;
cout << "Please enter a directory: \n";  // enter test for testing
getline(cin, directory);

dp = opendir(directory.c_str());
if (dp == NULL)
{
    cout << "Error! opening the directory: " << directory << endl;
    system("pause");
    exit(0);
}
while ((d = readdir(dp)) != NULL)
{
    filepath = directory + "/" + d->d_name;

    if (!strcmp(d->d_name, "..") || (!strcmp(d->d_name, ".")))
    {
        continue;
    }
    ifstream myFile(filepath.c_str());

    for (int i = 0; i < 4; i++)
    {
        myFile.open(filepath.c_str());

        string read;

        files[i].fName = d->d_name;

        while (myFile >> read)
        {
            if ("for" == read)
            {
                files[i].countFor++;
                files[i].total++;
            }
            else if ("while" == read)
            {
                files[i].countWhile++;
                files[i].total++;
            }
            else if ("if" == read)
            {
                files[i].countIf++;
                files[i].total++;
            }
            else if ("switch" == read)
            {
                files[i].countSwitch++;
                files[i].total++;
            }
            else if ("else" == read) {
                files[i].countElse++;
                files[i].total++;
            }

        }

        myFile.close();

    }
}
print();
system("pause");
return 0;
}

void print() {
ofstream testFile;
testFile.open("Results.txt");

testFile << setw(20) << "Document Name"
    << setw(20) << "If Statements"
    << setw(20) << "Switch Statements"
    << setw(20) << "For Loops"
    << setw(20) << "Else Statements"
    << setw(20) << "While Loops"
    << setw(20) << "similarity \n";
for (int i = 0; i < 4; i++)
{
    testFile << setw(20) << endl
        << setw(20) << files[i].fName
        << setw(20) << files[i].countIf
        << setw(20) << files[i].countSwitch
        << setw(20) << files[i].countFor
        << setw(20) << files[i].countElse
        << setw(20) << files[i].countWhile
        << setw(20) << files[i].total << "\n";
}
testFile.close();
}

here is the out put
       Document Name       If Statements   Switch Statements           For Loops     Else Statements         While Loops        similarity
       read4.txt                   0                   0                   0                   0                   0                   0

       read4.txt                  10                   4                  11                  15                   1                  41

       read4.txt                  10                   4                  11                  15                   1                  41

       read4.txt                  10                   4                  11                  15                   1                  41

A: Read this part:
while ((d = readdir(dp)) != NULL)
{
    filepath = directory + "/" + d->d_name;

    if (!strcmp(d->d_name, "..") || (!strcmp(d->d_name, ".")))
    {
        continue;
    }
    ifstream myFile(filepath.c_str());

    for (int i = 0; i < 4; i++)
    {
        myFile.open(filepath.c_str());
        string read;

        files[i].fName = d->d_name;

You're reading (and storing the results for) each file four times, and you're only keeping the (four) results for the last file in the directory.
The reason that you got all zeros for the first iteration is that the file was already open when you tried to open it - the constructor took care of that - and this put the stream into its "failure state", so the subsequent reads all failed.
Your explicit closing of the stream in the loop lets later iterations succeed.
Don't hardcode the number of files, use push_back to add to the vector.
Something like this:
while ((d = readdir(dp)) != NULL)
{
    if (!strcmp(d->d_name, "..") || (!strcmp(d->d_name, ".")))
    {
        continue;
    }

    std::string filepath = directory + "/" + d->d_name;
    std::ifstream myFile(filepath);
    counters c;
    c.fName = d->d_name;

    string read;
    while (myFile >> read)
    {
        if ("for" == read)
        {
            c.countFor++;
            c.total++;
        }
        else if ("while" == read)
        // ... and so on - your code with 'c' instead of 'files[i]'
    }
    files.push_back(c);
}


text:
Q: Como puedo saber si existe un archivo txt desde PLSQL tengo en siguiente problema, estoy creando un Trigger en Oracle para que escriba información en un archivo txt, hasta aquí todo bien, puedo escribir sin dramas, el problema es cuando necesito añadir información al archivo, a parte de la que ya tiene. Entiendo que debo leer el archivo, extraer lo que contiene y juntarlo con el nuevo texto, el gran problema se presenta cuando intento abrir el archivo pero no existe. Como puedo agregar esta validación?(si no existe, que lo cree)
Este es el Trigger:
CREATE OR REPLACE TRIGGER BAJOSTOCK
AFTER
UPDATE
ON PRODUCTO
FOR EACH ROW

DECLARE
V_ARCHIVO UTL_FILE.FILE_TYPE;
V_LINEA VARCHAR2(1024);
BEGIN
IF :NEW.CANTIDAD <= :OLD.STOCK_CRITICO THEN

 --Aqui me da el errror, cuando no existe

    --Abro el archivo
    V_ARCHIVO := UTL_FILE.FOPEN ('DIR_TMP', 'stock.txt', 'r');

  --Leo lo que contiene
  LOOP
    UTL_FILE.GET_LINE (V_ARCHIVO, V_LINEA);
  END LOOP;
    UTL_FILE.FCLOSE(V_ARCHIVO);--Lo cierro

  --Vuelvo a abrirlo y escribo
    V_ARCHIVO := UTL_FILE.FOPEN ('DIR_TMP', 'stock.txt', 'w');
  --Escribo lo que tenía y el nuevo contenido
    UTL_FILE.PUT_LINE(V_ARCHIVO,V_LINEA);
    UTL_FILE.PUT_LINE (V_ARCHIVO, 'El producto '|| :OLD.DESCRIPCION ||' se encuentra en stock crítico, por favor revíselo');
    UTL_FILE.FCLOSE(V_ARCHIVO); --Cierro el archivo
END IF;

--Cierro el archivo si hay errores
EXCEPTION
WHEN NO_DATA_FOUND THEN
 UTL_FILE.FCLOSE(V_ARCHIVO);
END;
/

Agradezco su ayuda....

A: No necesariamente hay que leerlo todo para agregar información.
Pero vamos por partes:
Considerando que en mi ambiente el query:
select  * from ALL_DIRECTORIES

Devuelve
OWNER   DIRECTORY_NAME  DIRECTORY_PATH
SYS     XMLDIR          /u01/app/oracle/product/11.2.0/xe/rdbms/xml
SYS     DATA_PUMP_DIR   /u01/app/oracle/admin/XE/dpdump/

Por otra parte en mi directorio /u01/app/oracle/admin/XE/dpdump/ tengo el archivo: dp.log
Luego entonces para revisar si el archivo existe se puede usar la funcion FGETATTR. Según mi ambiente puedo poner:
DECLARE
  nombreDirectorio CONSTANT VARCHAR2(100):= 'DATA_PUMP_DIR';
  nombreArchivo    CONSTANT VARCHAR2(100) := 'dp.log';
  existeElArchivo  BOOLEAN;
  longitudEnBytes  NUMBER;
  numeroDeBloques  NUMBER;

BEGIN

    UTL_FILE.FGETATTR( nombreDirectorio, nombreArchivo
                     , existeElArchivo, longitudEnBytes, numeroDeBloques);

     IF existeElArchivo THEN
        DBMS_OUTPUT.PUT_LINE( 'El archivo '|| nombreArchivo  ||' existe ' );
     ELSE
        DBMS_OUTPUT.PUT_LINE( 'El archivo '|| nombreArchivo  ||' NO existe ' );
     END IF;

END;
/

Lo cual me arroja como salida que el archivo existe.

*Para agregar al archivo no hace falta leerlo todo. Puedes abrirlo en modo de agregado.

En lugar de indicar que es para escritura (por el parámetro final w):
V_ARCHIVO := UTL_FILE.FOPEN ('DIR_TMP', 'stock.txt', 'w');

Puedes usar el parametro 'a':
V_ARCHIVO := UTL_FILE.FOPEN ('DIR_TMP', 'stock.txt', 'a');

Es importante comentar que si abres el archivo en modo 'a', si no existe el archivo Oracle lo creará en ese momento y lo abrirá en modo 'w'


text:
Q: how to run linux commands on real server using php I have created a script in php in which i have created a function
which executes a command using exec(). The function is as follows
public function tellWhoAmI()
{
return exec('whoami');
}

On localhost it is working as it should but when i upload it to the server the exec() does not seem to be working.
Question:-
Do i need to do something else to run this on real server?


text:
Q: Multiplot indexing when plotting piecewise regression model not working I've used the piecewise regression package to create 16 outputs, code e.g.:
x_ave = SalVGape['Sal'][SalVGape['Mussel ID'] == 'Average'].tolist()
y_ave = SalVGape['Gape'][SalVGape['Mussel ID'] == 'Average'].tolist()

pw_fit_ave = piecewise_regression.Fit(x_ave,
                                      y_ave,
                                      n_breakpoints = 1,
                                      #start_values=[23]
                                     )

These all plot very easily individually using:
plt.rcParams["figure.figsize"] = (20,15)
# Plot the data, fit, breakpoints and confidence intervals
pw_fit_ave.plot_data(color="grey", s=20)
# Pass in standard matplotlib keywords to control any of the plots
pw_fit_ave.plot_fit(color="red", linewidth=4)
pw_fit_ave.plot_breakpoints()
pw_fit_ave.plot_breakpoint_confidence_intervals()
plt.ylim([0,1])

However, I would like to combine the graphical outputs into a single 4x4 multiplot, I have set this up with:
#Setup Environment and Titles
fig, axs = plt.subplots(4,4,
                        sharex = True,
                        sharey = True,
                        #squeeze = False,
                        figsize = (20,20)
                       )
plt.setp(axs, xlim = (0,36), ylim = (0,1))

But when I try and plot the outputs on this multiplot they appear to ignore the indexing, and all plot in the final windoe (e.g. [3,3])
The plotting code I currently have is:
axs[0, 0].set_title('Average')
axs[0, 0].set_xlabel("Salinity")
axs[0, 0].set_ylabel("Gape")
axs[0, 0] = pw_fit_ave.plot_fit(color="red", linewidth=4)
axs[0, 0] = pw_fit_ave.plot_breakpoints()
axs[0, 0] = pw_fit_ave.plot_breakpoint_confidence_intervals()

axs[0, 1].set_title('M1')
axs[0, 1].set_xlabel("Salinity")
axs[0, 1].set_ylabel("Gape")
axs[0, 1] = pw_fit_M1.plot_data(color="grey", s=20)
axs[0, 1] = pw_fit_M1.plot_fit(color="red", linewidth=4)
axs[0, 1] = pw_fit_M1.plot_breakpoints()
axs[0, 1] = pw_fit_M1.plot_breakpoint_confidence_intervals()

This results in this plot.
Is there a way to force the indexing here?


text:
Q: Android Google Checkout Alternative I have to create an application where a user makes a deal and then gives me (the owner of the application) a certain amount of money for the deel to be made available to the rest of the world. I was thinking of achieving this through Google Checkout, but I stumbled upon Android in app billing sdk. My question is, is it possible to use in app billing in my scenario?

A: The google in app billing works only officially with receivables (AFAIK) i.e. The most effective way i could see you doing this is to make the deal, then charge for an item called for example ("Transaction fee" / "Deal fee") and then the app runs as normal.
It's not reccomended that you start using your own payment system, purely if not anything else, support could drop at any minute and your app starts breaking the ToS

A: I got the answer :) We can use in app billing with Unmanaged products :)


text:
Q: All WordPress AJAX calls always return 0 After page migration I have a problem with all AJAX calls. They always returning 0. I probably done everything and can't figure out what is wrong? Could you help me please?
Ajax call as shorten form:
$.ajax({
    url : '/wp-admin/admin-ajax.php',
    type : 'post',
    dataType: 'JSON',
    data : {
        action : 'ajax_newsletter',
        email : 'aaa@aaa.aaa'
    },
    success : function( response ) {
        console.log(response);
    },
    error: function(err){
        console.log(err);
    }
});

Functions.php function as shorten form:
function ajax_newsletter() {
    $response = [];
    $resposne['succcess'] = true;
    wp_send_json($response);
    wp_die();
}
add_action('wp_ajax_ajax_newsletter', 'ajax_newsletter');
add_action('wp_ajax_nopriv_ajax_newsletter', 'ajax_newsletter');


text:
Q: Filter gremlin path by label and property I want to find all transitive relations (regardless of direction) by numbers of hops (2) with this traversal:
g.V(1).repeat(both()).times(2).path()

The result will look something like this:
==>[v[1], v[2], v[3]]

If I use by(label()) at the end of path():
==>[A, B, C]

If I use by('name'):
==>[R2, R1, R3]

But I cannot figure out how to mix the label and name together in the path result like this:
==>[A.R2, B.R1, C.R3]

I can already achieve the desired result with Java, but it costs a lot of iterations, converts and the performance is not great. Therefore I want to know if there is a native gremlin way to do this.

A: There's no support for String concatenation in TinkerPop, but you could do something like this:
g.V(1).
  repeat(both()).
    times(2).
  path().
    by(union(label(), values("name")).fold())


text:
Q: Error al agregar elemento a la pila Tengo una estructura Pila que guarda estructuras de tipo CD, pero a la hora de agregar un CD a la Pila se crashea el programa.
Por lo que veo es en el momento de agregar un CD a la pila, no sé si esta bien mi código. Uso punteros. La función recibe un puntero que apunta a una Pila, y otro que apunta a un CD.
He modificado varias cosas pero no resuelven mi problema.
CÓDIGO:
typedef struct{
    char titulo[50];
    char autor[50];
    float duracion;
    int numeroCan;
}CD;

typedef struct{
    int top;
    CD cds[tamanio];
}Pila;

//Funcion para agregar un CD a la pila
void Push(Pila *ptrPila, CD *ptrCD){
    if(Full(ptrPila)){ //Verifica si la pila está llena

        printf("Pila desbordada");

    }
    else{//Agrega el CD a la pila
              ptrPila->cds[++(ptrPila->top)]=*ptrCD;
        printf("CD Agregado!!");

        printf("\nNombre del CD: %s",ptrCD->titulo);

    }
}

A: Todo apunta a que en ningún momento has inicializado los valores de la estructura Pila pasada a la función, en particular el valor de top.
Por ese motivo top puede tener un número aleatorio (posiblemente negativo, para que la llamada a Full te falle) que te esté forzando a escribir en una zona de memoria fuera del ámbito de tu programa.
Podrías inicializar el valor de dos maneras diferentes:
/* Definimos una pila con el valor "top" a cero */
Pila pila = { 0 };
/* También podríamos haberlo hecho así tras definirlo: */
pila.top = 0;

Ésta sería una prueba de concepto con el problema solucionado:
#include<stdio.h>

#define tamanio 10

typedef struct{
    char titulo[50];
    char autor[50];
    float duracion;
    int numeroCan;
}CD;

typedef struct{
    int top;
    CD cds[tamanio];
}Pila;

/* Funcion para agregar un CD a la pila */
void Push(Pila *ptrPila, CD *ptrCD){
    if(ptrPila->top > tamanio){
        printf("Pila desbordada");
    } else { /* Agrega el CD a la pila */
        ptrPila->cds[++(ptrPila->top)]=*ptrCD;
        printf("CD Agregado!!");
        printf("\nNombre del CD: %s\n",ptrCD->titulo);
    }
}

int main() {
    /* Definimos el contenido de un CD */
    CD cd = { "Título", "Autor", 10.0, 5 };
    /* Definimos una pila con el valor "top" a cero */
    Pila pila = { 0 };
    /* También podríamos haberlo hecho así tras definirlo: */
    pila.top = 0;
    Push(&pila, &cd);
    return 0;
}

Su salida de valgrind:
$ valgrind ./pr
==15904== Memcheck, a memory error detector
==15904== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==15904== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==15904== Command: ./pr
==15904==
CD Agregado!!
Nombre del CD: Título
==15904==
==15904== HEAP SUMMARY:
==15904==     in use at exit: 0 bytes in 0 blocks
==15904==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==15904==
==15904== All heap blocks were freed -- no leaks are possible
==15904==
==15904== For counts of detected and suppressed errors, rerun with: -v
==15904== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Antes de solucionar el problema ésta era la salida de valgrind:
$ valgrind ./pr
==15688== Memcheck, a memory error detector
==15688== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==15688== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==15688== Command: ./pr
==15688==
==15688== Use of uninitialised value of size 8
==15688==    at 0x4005EC: Push (in /tmp/pr)
==15688==    by 0x4006AC: main (in /tmp/pr)
==15688==
==15688== Invalid write of size 8
==15688==    at 0x4005EC: Push (in /tmp/pr)
==15688==    by 0x4006AC: main (in /tmp/pr)
==15688==  Address 0x120f648b60 is not stack'd, malloc'd or (recently) free'd
==15688==
==15688==
==15688== Process terminating with default action of signal 11 (SIGSEGV)
==15688==  Access not within mapped region at address 0x120F648B60
==15688==    at 0x4005EC: Push (in /tmp/pr)
==15688==    by 0x4006AC: main (in /tmp/pr)
==15688==  If you believe this happened as a result of a stack
==15688==  overflow in your program's main thread (unlikely but
==15688==  possible), you can try to increase the size of the
==15688==  main thread stack using the --main-stacksize= flag.
==15688==  The main thread stack size used in this run was 8388608.
==15688==
==15688== HEAP SUMMARY:
==15688==     in use at exit: 0 bytes in 0 blocks
==15688==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==15688==
==15688== All heap blocks were freed -- no leaks are possible
==15688==
==15688== For counts of detected and suppressed errors, rerun with: -v
==15688== Use --track-origins=yes to see where uninitialised values come from
==15688== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

En especial debes fijarte en los errores:

==15688== Use of uninitialised value of size 8
==15688==    at 0x4005EC: Push (in /tmp/pr)
==15688==    by 0x4006AC: main (in /tmp/pr)
==15688==
==15688== Invalid write of size 8
==15688==    at 0x4005EC: Push (in /tmp/pr)
==15688==    by 0x4006AC: main (in /tmp/pr)
==15688==  Address 0x120f648b60 is not stack'd, malloc'd or (recently) free'd

Que te dicen que has hecho uso de un valor sin inicializar y que has escrito en una zona de memoria que no está en la pila, ni alojada ni liberada recientemente.


text:
Q: How can I increase volume mediaplayer sound in kotlin compose? I've been doing for a while dictionary app and I want the word to be heard aloud, so I made the word listen button. It's working properly but for some reason it sounds a bit low when I'm listening so I want to turn the volume up a bit how can I do that? I am sharing my codes below
I am making the dictionary application in kotlin and using compose.
phoneticSound function
fun phoneticSound(_audioUrl:String){

    val mediaPlayer = MediaPlayer()
    var audioUrl = _audioUrl

    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)

    try {
        mediaPlayer.setDataSource(audioUrl)
        mediaPlayer.prepare()
        mediaPlayer.start()

    } catch (e: Exception) {

        e.printStackTrace()
    }

}

This function receives a string. This string is the url of the audio source. I am playing the audio with mediaPlayer using this url.
How can I adjust the sound by adding an add-on to the codes I've made?

A: MediaPlayer has the 'setVolume()' function, which you can use to set the volume. You can set values from 0.0 - 1.0 (0-100%).
source: https://developer.android.com/reference/android/media/MediaPlayer#setVolume(float,%20float)


text:
Q: Array filtering with multiple(or not) items I'm trying to filter a array, passing throught the filter another array.
filterArray = [{BEERSERV-01,BEERSERV-02,BEERSERV-03}]

itemArray = [{
product1:{
equipamento: "BEERSERV-01"
id_pdv: "18225301000189"
item_venda: "OATMEAL STOUT - Mark The Shadow"
},
product2:{
equipamento: "BEERSERV-02"
id_pdv: "18225301000189"
item_venda: "IPA - Hector 5 Rounds"
},
product3:{
equipamento: "BEERSERV-03"
id_pdv: "20138940000159"
item_venda: "IPA - Hector 5 Rounds"
}

}

Those values will be selected in the SELECT of the printscreen below, each place had one of the values above, and at each select, i push thens to the filterArray.
For each select i do, a need a return of a new list with the selected value, but when the filterArray got more than 1 value, never return a value.
 public async gerarListaPDV(){
    let filtered = []
    this.filterarr = []
    console.log(this.filterarr.length)
    for(var x in this.pdvs_selecionados){
      for(var y in this.pdvs_selecionados[x].equipamentos){
        this.filterarr.push(this.pdvs_selecionados[x].equipamentos[y].nome_equipamento)
      }
    }

    this.lista_vendas_filtrada.filter((obj)=>{
           if(this.filterarr.includes(obj.equipamento)){
             console.log(this.filterarr)
             filtered.push(obj)
           }
    })
    this.exibir_por_pdv = filtered

    console.log(this.filterarr)
    if(this.filterarr.length >= 1){
      this.lista_vendas_filtrada = this.exibir_por_pdv
    }
    else{
      this.lista_vendas_filtrada = this.lista_vendas_constante
    }
    this.carregarRelatorioTotal(true)

  }

Filtering example

A: your problem statement is hard to understand. I don't know what your issue is, but based on your code, there's an issue:
you're calling filter on this.lista_vendas_filtrada, but you're not returning anything in the callback.
Please take a look at what filter method does - link
filter callback should return trueif you want to keep the value in the new array that it returns, or false if you want to remove it from the new array it returns. filter does not modify the array it's called on.
Hope this helps. If you need more concrete answer, please edit your question to be minimal reproduceable example, write code in English, and format your question so it's not all in one unformatted paragraph.


text:
Q: In RxJS, Why Check rxSubscriberSymbol in toSubscriber? I have read through parts of the ReactiveX codebase several times, and still cannot wrap my head around exactly what is going on here, in toSubscribe.ts:
if (nextOrObserver) {
  if (nextOrObserver instanceof Subscriber) {
    return (<Subscriber<T>> nextOrObserver);
  }

  if (nextOrObserver[rxSubscriberSymbol]) {
    return nextOrObserver[rxSubscriberSymbol]();
  }
}

What I Know
I know Observable.subscribe takes a passed in observer (which can be in different forms) and, via toSubscribe.ts, converts the observer to a Subscriber object. The new Subscriber object will have a SafeSubscriber instance in the Subscriber.destination property.
This segment from Subscriber.ts class is also relevant to the below question:
[rxSubscriberSymbol]() { return this; }

In the above code, the rxSubscriberSymbol Symbol property returns the class instance itself.
My Question
I get that toSubscriber must check if the observer is already a Subscriber. Well, I am not entirely sure when toSubscribe would be called with an observer that is already a Subscriber, but I guess there are times when that happens.
Why is it necessary to check both whether the observer is an instance of Subscriber and whether the rxSubscriberSymbol Symbol property exist? As far as I can tell, if an instance is an instance of Subscriber it always has the rxSubscriberSymbol Symbol property, and vice versa.

A: When you compose an observable by piping operators, like this:
const source = of(42);
const composed = source.pipe(
    map(value => (6 * 9) - value)
);
composed.subscribe(value => console.log(value));

there will an observable introduced for each operator.
Here, the caller is subscribing to the mapped observable and that mapped observable subscribes to the source.
When the caller subscribes, only the next handler is passed. That is, the caller doesn't pass a Subscriber instance - so toSubscriber is needed to create one. However, when the mapped observable subscribes to the source, it does so by passing the map operator's MapSubscriber. You can see the call to subscribe made here.
MapSubscriber extends Subscriber, so there is no need for toSubscriber to create another; it can just return the MapSubscriber that it received.
The rxSubscriberSymbol is a Symbol that's used to identify Subscriber and Subject instances.
In version 5 of RxJS, this symbol was declared using Symbol.for - see here - which meant that the same symbol would have been shared between different copies or versions of RxJS. And the symbol enabled interop between copies or versions - Subscribers from one copy wouldn't need to be wrapped by another.
In version 6, however, the symbol is declared using Symbol - see here. Which means that it is essentially private, as each copy or version of RxJS will receive a unique symbol and it cannot perform an interop role.
rxSubscriberSymbol is used in Subscriber and in Subject, but now that it is a private symbol, it no longer serves a purpose and it seems, to me, to be unnecessary:

*

*Its use in Subscriber is not necessary, as the instanceof Subscriber check will identify Subscriber instances.

*And its use in Subject is unnecessary, as the rxSubscriberSymbol property in Subject - see here - does nothing other than wrap the Subject in a Subscriber - which is what would happen in toSubscriber without the check.


text:
Q: Resize jHtml text area I would like to resize jHtml TextArea just like normal text area , so is there any way for resizing.
Following is the code for creating jHtml Textarea.
Here is the HTML code:

        <%=Html.LabelFor(m => m.Description)%>

        <%=Html.TextAreaFor(m => m.Description, new { @class="form-control",style="width: 610px; height: 150px" })%>

and below is the javascript code :

A: you can achieve the behaviour by adding the "resizable" attribute of jHtmlarea. May it help you out.

A: My guess is that you can easily achieve desired behaviour by using css rules as in code snippet below:

#Comments {
    position:absolute;
    width:60%;
    height:200px;
}
<textarea id="Comments">My text.</textarea>


text:
Q: mod_rewrite missing trailing affects link system I am trying to make my site multilingual by implementing language codes (en/es) into the URL. So far it has worked well, all the links automatically switch to the language you select. Except for the home page.
A link saying mydomain.com/en/staff.php will be in the right language, and all the links will automatically work (en/home.php, for example).
The one that doesn't do that is the home, if I forget the trailing slash.  mydomain.com/en/ works perfectly fine while mydomain.com/en (no slash) doesn't update the links properly.
Is there a way around this using mod_rewrite? Or will I have to write out the links manually in the HTML?
Options -MultiViews
RewriteEngine on
RewriteBase /

RewriteRule ^([a-zA-Z]{2})/?$  index.php?lang=$1 [QSA,L]
RewriteRule ^([a-zA-Z]{2})/(\w+)\.php  $2.php?lang=$1 [QSA,L]

A: You can use a rule to enforce trailing slash Place this rule in your root .htaccess:
DirectorySlash On
Options -MultiViews
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]

RewriteRule ^([a-zA-Z]{2})/$  index.php?lang=$1 [QSA,L]
RewriteRule ^([a-zA-Z]{2})/(\w+)\.php$ $2.php?lang=$1 [QSA,L]


text:
Q: Can we query and update structure at different levels with lens? I often use lens when dealing with nested structures (JSON from various APIs), and I'm worried that nontrivial data manipulations with lens are somewhat complicated.
By nontrivial I mean performing update on different node than the node I query for.
For example, I would:

*

*Drill down to obtain a foldable list of interesting values (like price)

*Apply a criteria on that list (like max) to identify the "owning" entity of the result (like order)

*Drill down again for some interesting value (say, vip flag of a customer)

*Finally, update yet another value in that structure (say add a new item free of charge to latest order)

A somewhat reliable strategy is to use "stages" where simple lens are used to extract interim results and apply new lens to narrow down further or update the result. But this is somewhat against the spirit of lens, where I should be able to update the whole structure.
Other times I'm lucky to find combinators like maximumByOf, aside but I feel that I lack vocabulary and understanding of the problem - what kind of combinators are sufficient for this kind of tasks?
Is there idiomatic way to to this with lens?


text:
Q: Jquery/JS not loading text file I am writing a word/name generator. On my local computer the script works fine but when uploaded, the jQuery is not able to load the text file and I get a 404 not found error. The text file is there, I have checked a number of times. Here is the simplified code: http://namepicker.site11.com/test.html
Thank you for any advise,
Todd
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>JQuery-Load Text File</title>
        <script type="text/javascript" src="./js/jquery-1.4.3.min.js"></script>
            <script type="text/javascript">
            function loadXML()
            {
                var file= './names/names.txt';
                $.get(file, function(data) {
                    alert(data);
                });
            }
            </script>
    </head>

    <body onload="loadXML();">
    </body>
</html>

A: Well a simple look at Chrome's Developer Tools reveals this error:
GET http://namepicker.site11.com/names/names.txt 404 (Not Found)

Obviously, you'd need to actually upload the names.txt file into the names directory.
Edit: I see that other files redirect to your hosting 404 page while names/names.txt does not, so perhaps it exists but does it somehow still send a 404 code. Is it a real text file or an underlying PHP file?

A: http://namepicker.site11.com/names/names.txt
The file does not exist, It needs to be there to be loaded. Try creating it and see if your having the same issues.
EDIT:
http://namepicker.site11.com/names/
File does seem to exist, perhaps check the CHMOD settings on the files.

A: jQuery is not ready yet. You need to wrap jQuery functions.
For example:
$(function() {
    $(window).load(function()
        var file= './names/names.txt';
        $.get(file, function(data) {
            alert(data);
        });
    });
});


text:
Q: Total and aggregate percentage in hive I have a table like
fruit   sold
----------------
apple   5
apple   10
apple   3
orange  2
orange  5

I wanna get the total and also aggregate percentage. So the output would be
fruit   sold
----------------
All     25
apple   52%
orange  48%

As of all sold apple is 13/25 and orange is 12/25.

A: I think that's union all between a query that generates the total sum, and another that computes the total per fruit:
select 'All' as fruit, sum(sold) sold from mytable
union all
select fruit, 100.0 * sum(sold) / sum(sum(sold)) over()
from mytable
group by fruit

One thing to be careful about is that the datatypes of the subqueries need to be aligned. This puts everything as numbers (both the total sales, and the percentages per fruit).


text:
Q: How to know subtract two arrays I have an array of string:
private static string[] dataNames = new string[] { "value1", "value2", ..... "value56" };

I have a table in my SQL database that contains a column which its type is VARCHAR
I want to know which values that exist in the array and doesn't exist in that column.
What I tried
var matchingRows = dt.AsEnumerable()
    Where(row => dataNames.Contains(row.Field<string>("ColumnName"), StringComparer.OrdinalIgnoreCase));

where dt is the dataTable the contains the results of this query:
SELECT * FROM table name

now I have the matchingValues in matchingRows variable and I can transfer it to array usingg ToArray()
Now I still need to know how to subtract the dataNames array from the matchingRows in order to know which values exist in the array and don't exit in the table column.
could you help me in that issue please

A: Use Enumerable.Except
var columnData = matchingRows.Select(row => row.Field<string>("ColumnName"));
var diff = dataNames.Except(columnData);

In order to perform a case insensitive comparison, you need to pass an instance of IEqualityComparer<string> to Except. Normally, you'd have to implement this interface yourself, but luckily, StringComparer provides a few out-of-the-box custom string comparers.
var diff = dataNames.Except(columnData, StringComparer.InvariantCultureIgnoreCase);

A: Select all values for this column from table and then use Except() method.
var matchingRows = dt.AsEnumerable()
    .Where(row => dataNames.Contains(row.Field<string>("ColumnName"), StringComparer.OrdinalIgnoreCase))
    .Select(row => row.Field<string>("ColumnName"));

var diff = dataNames.Except(matchingRows, StringComparer.OrdinalIgnoreCase);


text:
Q: Huffman algorithm for decompress an already compressed bytes I have a byte array in the database which has been compressed using the Huffman algorithm in Delphi. Now I need to decompress it in SSIS (SQL Server Integration Services).
I need some C#/.NET code, or a tool to decrypt the bytes into a file, based on the Huffman algorithm. There are a few tools in the market that unpack a compressed file, but I don't have the file with full header for LHA compression. I need a way to somehow  convert a series of bytes to a decompressed file, and then save it to a file.

A: With Huffman compression, each character in your input file will map to a sequence of bits. If you have access to the Delphi source code, you can try to figure out how the frequency and character mapping information was done. Is the mapping included in the compressed file? You will need that mapping in order to write the code to decompress the file.


text:
Q: Remove duplicates vector of strings, keep first instance. Can't use algorithm I have a vector of
strings.vector input;
bob
sam
bob
sammom
aardvark
money
aardvark
wanted

I need to remove the duplicates but each part of the vector corresponds to the next location. They are pairs.
ex. bob corresponds to the its definition, which is sam.
I need to keep the first instance, so keep bob and sam, but remove the second instance of bob, so remove bob and sammon. Only the first instance of the pair need to kept.
It doesn't matter if the sam and sammon don't match, all that matters is the first part of the pair.
The vector is already in alphabetical order. I can't use the algorithm library.

A: Something like this?
#include <iostream>

using namespace std;

int main()
{
    int stringSize=10, k=2, newlen=0;

    string v[] = {"bob","sam","bob","samelia","bob","sammom","aardvark","money","aardvark","wanted"};

    // erase duplicates
    for (int i=0; i<=stringSize-4; i+=2)
    if (v[i]==v[i+k])
    {
        while (v[i]==v[i+k])
        {
            v[i+k]="";
            v[i+k+1]="";

            k+=2;
        }
        i=k-2;
        k=2;
    }

    // remove blank components
    for (k=0; k<stringSize; k++)
    if (v[k]!="")
    {
        v[newlen]=v[k];
        newlen++;
    }
    stringSize=newlen;

    // show the cleaned vector
    for (int i=0; i<stringSize; i++)
    cout << v[i] << endl;

}

A: This will remove duplicates even if there is multiple in a row like this
Again note that this is for pairs
And only the first instance is kept.
Lets say vector input; has the following
bob
son
bob
son2
mark
wife1
mark
wife2
mark
wife3

Becomes
bob
son
mark
wife

This will remove duplicates up to 6 in a row, increase as needed.
I had to remove the blank spaces two times for some reason.
    //vector<string> input; is filled in alphabetical order with duplicates
    int size=input.size();

    //transfer to dynamically created array of strings
    string *strarray;
    strarray = new string[size];
    for(int i=0; i<size; i++){
       strarray[i] = input[i];//Copy the vector to the string
    }

    // erase duplicates
    for (int i=0; i<=size-(size/2); i+=2){
        if (strarray[i]==strarray[i+2])
        {
            strarray[i+2].erase(0,strarray[i+2].size());
            strarray[i+3].erase(0,strarray[i+3].size());
        }
        if (strarray[i]==strarray[i+4])
        {
            strarray[i+4].erase(0,strarray[i+4].size());
            strarray[i+5].erase(0,strarray[i+5].size());
        }
        if (strarray[i]==strarray[i+6])
        {
            strarray[i+6].erase(0,strarray[i+6].size());
            strarray[i+7].erase(0,strarray[i+7].size());
        }
        if (strarray[i]==strarray[i+8])
        {
            strarray[i+8].erase(0,strarray[i+8].size());
            strarray[i+9].erase(0,strarray[i+9].size());
        }
        if (strarray[i]==strarray[i+10])
        {
            strarray[i+10].erase(0,strarray[i+10].size());
            strarray[i+11].erase(0,strarray[i+11].size());
        }
    }

    // remove blank components
        for (int i=0; i<size; i++){
        if (strarray[i]=="")        {
            for (int j=i; j<size-1; j++)
                strarray[j]=strarray[j+1];

            size--;
            i--;
        }
        }


text:
Q: Can I use column names as data I have to check the data in each column in 7000 tables.
So I want to insert into Temp_Table has Columns ( Table_name, Column_name, Data)
eg.
SELECT * FROM TABLE_A;

COL_A
COL_B
COL_C

DATA_A1
DATA_B1
DATA_C1

DATA_A2
DATA_B2
DATA_C2

I want to insert into Temp_table
eg.

TABLE_NM
COL_NM
DATA

TABLE_A
COL_A
DATA_A1

TABLE_A
COL_A
DATA_A2

TABLE_A
COL_B
DATA_B1

TABLE_A
COL_B
DATA_B2

TABLE_A
COL_C
DATA_C1

TABLE_A
COL_C
DATA_C2

Is there any way?

A: you can do this using union all from metadata.
select 'TABLE_A' TABLE_NM, 'COL_A' COL_NM, COL_A DATA from table_a
union all
select 'TABLE_A' TABLE_NM, 'COL_B' COL_NM, COL_B DATA from table_a
union all
select 'TABLE_A' TABLE_NM, 'COL_C' COL_NM, COL_C DATA from table_a
...

Put the list of table and columns in XL and then create a formula to create the whole query. But list of tables and columns - you need to get from metadata.


text:
Q: Adding an array of values to an existing array I've got a foreach where I create an array out of id's, based on the submitted selected checkboxes from my form (which are `checkbox[$id]. So I end up with:

Where 1, 2 and 3 are the submitted id's from the form. So far so good.
Now I also have an input field amount[$id]in my form. When selecting a checkbox, I can enter an amount for that row and submit the results. I need to add the values of amount to my array if id's. My end result should look like this:
[1 => ['amount' => '10'], 2 => ['amount' => '12'], 3 => ['amount' => '5'] // And so on

I tried merging, and array_push, but I seem to be doing it wrong, since I cannot figure it out. Any pointers?

A: Something like this should work:
$result = [];
$ids = [1,2,3];   // I suppose it is `$_POST['ids']`
$amounts = [1 => 10, 2 => 11, 3 => 22];   // I suppose it is `$_POST['amount']`
foreach ($ids as $id) {
    if (!empty($amounts[$id])) {
        $result[$id] = ['amount' => $amounts[$id]];
    }
}

Using array_combine as advised in comments can be used only if sizes of arrays are equal. So if you have something like:
$ids = [1,2,4];
$amounts = [1 => 10, 2 => 11, 3 => 0, 4 => 22];
print_r(array_combine($ids, $amounts));   // PHP Warning

And second fact - array_combine won't create values as arrays. So
$ids = [1,2,3];
$amounts = [1 => 10, 2 => 11, 3 => 10];
print_r(array_combine($ids, $amounts));   // no subarrays here


text:
Q: SQL how group by fiscal quarter and year with a date field I am running SQL 2008, I have been tasked to create a report that groups 'vendor name' and certain information together, furthermore group it by fiscal year and their quarters.
It went well up the the grouping by year, except that our fiscal start isnt on January but instead November. I have a date field called 'Expected Arrival Date' that is formatted as 'yyyy-mm-dd hh:mm;ss.mmm' I am not sure how i can group it to associate:
A. the fiscal year starting with November year before to the rest of the fiscal year ending at October (example fiscal year 2012 = beginning November 2011 -  End October 2012
B. The fiscal quarter Nov1- Jan31 , Feb1 - Apr30, May1-July31, Aug1-Oct31
Here is the code I already have
SELECT
    YEAR([Expected Arrival Date])as 'Year',
    MONTH([Expected Arrival Date]) as 'Month',
    [Vendor Name],
    (SUM(CASE WHEN ([Days Past Due] = 0) THEN [Qty Received] ELSE 0 END) / SUM([Qty Received])) * 100  AS 'On-Time %',
    (SUM(CASE WHEN ([Days Past Due] < 0) THEN [Qty Received] ELSE 0 END) / SUM([Qty Received])) * 100  AS 'Early %',
    (SUM(CASE WHEN ([Days Past Due] > 0) THEN [Qty Received] ELSE 0 END) / SUM([Qty Received])) * 100  AS 'Late %',
    SUM([Qty Received]) aS 'TOTAL'

FROM data_view
GROUP BY YEAR([Expected Arrival Date]),MONTH([Expected Arrival Date]),[Vendor Name]
ORDER by YEAR([Expected Arrival Date]),MONTH([Expected Arrival Date])

If you have any helpful pointers to create a nice query it would also be appreciated.
Edit**
The structure of the data_view is as follows
    SELECT        [Receipt #], [Vendor Code], [Vendor Name], [PO Applied], [PO Line #], [Item Code], [Item Description], [Expected Arrival Date], [Receiving Date], [Receiving Date Filter],
                         [Qty Received], [Qty Ordered], [% Received], [PO Date], [Receipt User], DATEDIFF(dd, CAST(CAST([Expected Arrival Date] AS CHAR) AS DATETIME),
                         CAST(CAST([Receiving Date] AS CHAR) AS DATETIME)) AS [Days Past Due]
FROM            (SELECT        T1.RCPNUMBER AS [Receipt #], T1.VDCODE AS [Vendor Code], T1.VDNAME AS [Vendor Name], T4.PONUMBER AS [PO Applied],
                                                    T3.DETAILNUM AS [PO Line #], T2.ITEMNO AS [Item Code], T2.ITEMDESC AS [Item Description],
                                                    CASE WHEN T3.EXPARRIVAL = 0 THEN CASE WHEN T4.EXPARRIVAL = 0 THEN CAST(CAST(T4.DATE AS CHAR) AS DATETIME)
                                                    ELSE CAST(CAST(T4.EXPARRIVAL AS CHAR) AS DATETIME) END ELSE CAST(CAST(T3.EXPARRIVAL AS CHAR) AS DATETIME)
                                                    END AS [Expected Arrival Date], CAST(CAST(T1.DATE AS CHAR) AS DATETIME) AS [Receiving Date], CAST(CAST(T1.DATE AS CHAR) AS DATETIME)
                                                    AS [Receiving Date Filter], T2.RQRECEIVED AS [Qty Received], T3.OQORDERED AS [Qty Ordered],
                                                    ROUND(CASE WHEN T2.OQORDERED <> 0 THEN (T2.RQRECEIVED / T2.OQORDERED) * 100 ELSE 100 END, 2) AS [% Received],
                                                    CAST(CAST(T4.DATE AS CHAR) AS DATETIME) AS [PO Date], T5.ENTEREDBY AS [Receipt User]
                          FROM            canada.dbo.PORCPH1 AS T1 INNER JOIN
                                                    canada.dbo.PORCPH2 AS T5 ON T1.RCPHSEQ = T5.RCPHSEQ INNER JOIN
                                                    canada.dbo.PORCPL AS T2 ON T2.RCPHSEQ = T1.RCPHSEQ INNER JOIN
                                                    canada.dbo.POPORL AS T3 ON T3.PORHSEQ = T2.PORHSEQ AND T3.PORLSEQ = T2.PORLSEQ INNER JOIN
                                                    canada.dbo.POPORH1 AS T4 ON T4.PORHSEQ = T3.PORHSEQ) AS tblReceips

A: Something like this should work:
SELECT
    YEAR([Expected Arrival Date]) + CASE
        WHEN MONTH([Expected Arrival Date]) IN (11, 12) THEN 1
        ELSE 0
    END As FiscalYear,
    CASE
        WHEN MONTH([Expected Arrival Date]) IN (11, 12, 1) THEN 1
        WHEN MONTH([Expected Arrival Date]) IN (2, 3, 4) THEN 2
        WHEN MONTH([Expected Arrival Date]) IN (5, 6, 7) THEN 3
        ELSE 4
    END As FiscalQuarter,
    ...
GROUP BY
    YEAR([Expected Arrival Date]) + CASE
        WHEN MONTH([Expected Arrival Date]) IN (11, 12) THEN 1
        ELSE 0
    END,
    CASE
        WHEN MONTH([Expected Arrival Date]) IN (11, 12, 1) THEN 1
        WHEN MONTH([Expected Arrival Date]) IN (2, 3, 4) THEN 2
        WHEN MONTH([Expected Arrival Date]) IN (5, 6, 7) THEN 3
        ELSE 4
    END,
    [Vendor Name]
ORDER BY
    FiscalYear,
    FiscalQuarter
;

A: Richard Deeming's SQL works perfectly in MySQL, but I wasn't happy with the size of the query, so I used the basic concept to create a much smaller query using the built-in MySQL IF() function:
SELECT
    YEAR(date),
    MONTH(date),
    YEAR(date) + IF(MONTH(date)>10, 1, 0) as 'FiscalYear',
    IF(MONTH(date)>10, 1, CEIL((MONTH(date)+2)/3)) as 'FiscalQuarter'
FROM dates

See SqlFiddle

A: For those who interested in query for FY start from Jul
SELECT
    YEAR(date),
    MONTH(date),
    YEAR(date) + IF(MONTH(date)>6, 1, 0) as FiscalYear,
    IF(MONTH(date)>6, FLOOR((MONTH(date)-4)/3), CEIL((MONTH(date)+6)/3)) as FiscalQuarter
FROM dates


text:
Q: How to connect to user's stream in TokBox I'm making a 1 on 1 video call app using TokBox.
I'm opening a session using this code:
[_session connectWithApiKey:kApiKey token:kToken];
after getting the didConnect message i'm publishing a stream on one user device using this code:
    _publisher = [[OTPublisher alloc] initWithDelegate:self];
    [_publisher setName:@"PublishName"];
    [_session publish:_publisher];
    [self.view addSubview:_publisher.view];
    [_publisher.view setFrame:CGRectMake(0, 0, widgetWidth, widgetHeight)];

What do I need to transfer to the other user in order for him to see what the first user publishes? I tried going through the docs but It's really unclear to me.
Do I need a session ID? Publish ID?
Thanks.

A: Think of sessions as rooms. People connected to the same session will be in the same room so they are able to see each other. Lets say you have 2 iPhones, A and B. After iPhone A calls [_session publish...], iPhone B will get a stream created event with A's video stream. Simply subscribe to that stream and B should be able to see As video.
You probably want to have a streamCreated delegate. In your streamCreated delegate, simply call [session subscribe...] to subscribe to the publishing stream.
For an example, check out the OpenTok HelloWorld Tutorial. Its a simple group video chat where everybody is publishing and subscribing to each other.


text:
Q: How to concatenate and Alter/Update table
Possible Duplicate:
How to insert the next highest number into the database

I am using MYSQL
I have a column known as TeacherId which is auto incremented and goes like this:
TeacherId

1
2
3
4

What I want to do is add the letter 'T' in front of the numbers so it becomes:
TeacherId

T1
T2
T3
T4

How can I update or alter table to do this?
Below is my attempt but it did not work:
UPDATE Teacher SET TeacherId = CONCAT('T',TeacherId)

A: I highly recommend you consider appending the T to the display at query time instead of trying to store a T on every single row. I don't understand the purpose of storing the data this way, particularly if you have other tables that use the TeacherId value in its native form.
If you need to distinguish teachers from admins, then two thoughts:

*

*The table should be called Personnel, not Teachers.

*This can still be stored as a separate column e.g. PersonnelType.

I know you might have been told that it should show as T3 etc., but surely they did not tell you explicitly "we want you to store the T and 3 together in the same column, or else." You can show them T3 without shoehorning them together in a terrible and unusable design.

A: To select the data and automatically add the letter T in front of TeacherId:
SELECT *, CONCAT('T', TeacherId) AS TeacherId2 FROM Teacher

A: If you must have it in your table, create a second column in your table, so your create would look like:
CREATE TABLE  `teacher` (

`teacherId` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`t` CHAR( 10 ) NOT NULL DEFAULT ''
)

Then create a trigger to set your second column to 'T' concatenated with your id.
delimiter |

CREATE TRIGGER teacherInsert after INSERT ON teacher
  FOR EACH ROW BEGIN
    UPDATE teacher SET `t` = concat('T', teacherId);
  END;
|

delimiter ;

Alternatively, you can also do what Aaron suggests, and just get it at query time:
select teacherId, concat('T', teacherId) from teacher


text:
Q: Estimating value of $h$ needed to cap the approximation error of $\ln{(1+h)}$ We know that
$$\ln{(1+h)} = h - \frac{h^2}{2} +...$$
What is the method for finding how much we should cap $h$ at, to cap the approximation error of $\ln{(1+h)}=h$ at a certain value, like $10^{-3}$ or something like this? I want to solve this using Taylor remainder theorem.

A: If you approximate $\ln(1+h)$ to $h$, then Taylor's remainder theorem yields that there exists $t\in(0,h)$ such that $\ln(1+h)=h-\dfrac{1}{(1+t)^2}\dfrac{h^2}{2}$. Then the error $\left\lvert\ln(1+h)-h\right\rvert\le\dfrac{h^2}{2}$, since $\dfrac{1}{(1+t)^2}$ is decreasing. If you want to cap the approximation error at $10^{-3}$, then $\dfrac{h^2}{2}\le 10^{-3}$, and you can do the rest of the calculation.

A: Alternatives to Taylor's Remainder Theorem
We can use
$$
\frac{h}{1+h}\le\overbrace{\int_0^h\frac{\mathrm{d}x}{1+x}}^{\log(1+h)}\le h
$$
we get the maximum error is
$$
\left|\,\log(1+h)-h\,\right|\le\frac{h^2}{1+h}
$$

However, if $h\ge0$, we can use Jensen's inequality and the convex function $\frac1{1+x}$ to get
$$
\frac1h\int_0^h\frac{\mathrm{d}x}{1+x}\ge\frac1{1+\frac1h\int_0^hx\,\mathrm{d}x}=\frac1{1+\frac12h}
$$
which gives a better bound of
$$
\left|\,\log(1+h)-h\,\right|\le\frac{h^2}{2+h}
$$


text:
Q: Multiple Asserts in a Unit Test I've just finished reading Roy Osherove's "The Art of Unit Testing" and I am trying to adhere to the best practices he lays out in the book. One of those best practices is to not use multiple asserts in a test method. The reason for this rule is fairly clear to me, but it makes me wonder...
If I have a method like:
public Foo MakeFoo(int x, int y, int z)
{
     Foo f = new Foo();
     f.X = x;
     f.Y = y;
     f.Z = z;

     return f;
}

Must I really write individual unit tests to assert each separate property of Foo is initialized with the supplied value? Is it really all that uncommon to use multiple asserts in a test method?
FYI: I am using MSTest.
EDIT: Thanks for all the responses. I think I'll wind up going with the multiple asserts. In my situation the behavior being tested is that MakeFoo makes a proper Foo. So asserting that each property is getting the expected value should suffice. However, if there was a condition around setting one of the properties then I'd test each of the individual outcomes separately.
I still don't like it though.... The reason I like the idea of having one assert per test is that you know the exact reason a test failed. If you fix the problem then the test will pass. With multiple asserts you don't have the same guarantee. If you fix the problem alluded to by the failing assertion, there is nothing to stop another assertion later on in the test from failing next. If the asserts were split up, then you'd have known about both failures from the start.
And finally, the reason I'm not just using .Equals() is because in my situation Foo is a LINQ-To-SQL entity which introduces some complications that aren't worth getting into here.
Thank again.

A: In situations like this, if I'm trying to be strict about one assert per test, I'll assert equality on the Foo, rather than its components.  That drives me to write Foo.equals(), and that's usually a good thing in and of itself.  But I'm not always strict about one assert per test.  See what feels good to you.

A: AFAI see, the principle behind the practice was

*

*to test one cohesive/logical thing per test ; leading to concise and easy to read tests.

*to have better test isolation. One test should not fail for 1 of n reasons. If it does, then it is not immediately apparent as to how to fix it ; without first investigating which reason caused it to fail. A single change should not fail a truckload of seemingly unrelated tests.

*a starter-rule from the rulebook for TDD beginners ; so that they can internalize the process.

the point is not that you need one 'NUNit'/'xUnit' assert per test ; rather you have one logical assert per test.
[Test]
public void MakeFoo_SeedsInstanceWithSpecifiedAttributes()
{
  Assert.AreEqual( new Foo(1,2,3), Foo.MakeFoo(1,2,3), "Objects should have been equal );
}

Here I have one NUnit assert (keeping the assert police happy) : However it is testing three things behind the scenes (in Foo.Equals I'd be checking if all the variables are equal.)
The guideline is to prevent tests like (i.e. an integration test masquerading as a unit test)
[Test]
public void ITestEverything()
{
  // humongous setup - 15 lines
  payroll.ReleaseSalaries();
  // assert that the finance department has received a notification
  // assert employee received an email
  // assert ledgers have been updated
  // statements have been queued to the printqueue
  // etc.. etc..
}

Moral of the story: It is a nice target to aim for. Try and compose all the things you want to test into one logical/cohesive Assert with a good name. e.g. Assert.True(AreFooObjectsEqual(f1,f2). If you find that you're having a tough time naming the cohesive verification/assert - maybe you need to review your test and see if you need to split it.

A: I've actually written an NUnit addin to help with this. Try it out at http://www.rauchy.net/oapt

A: It is far more important to test just one concept per unit test.
It may take more than one assertion to test a concept, so don't worry overly about the number of assertions. Of course if you end up with a large number of assertions, you may want to take a step back and think about what you are really testing.

A: It's common to use multiple asserts in a test, but I don't feel that it's a "best practice."
I would say that yes, you do want to use multiple tests for the above function, exactly so you can see where the problem is.  I've recently been working with a fairly large test suite that has some weird failures in it that I have yet to track down, and the problem I'm experiencing is that the test cases each do too much.  I've split them up, and now I can disable the specific ones that are failing so that I can get back to them when I have the opportunity.
However, you can still use a fixture to factor out the commonality of your setup and teardown.  I can't speak to MSTest, but in UnitTest++ you'd do something like:
class FooFixture
{
public:
   FooFixture() : f(MakeFoo(kX, kY, kZ)) { }

   static const int kX = 1;
   static const int kY = 2;
   static const int kZ = 3;

   Foo f;
};

TEST_FIXTURE(FooFixture, IsXInitializedCorrectly)
{
   CHECK_EQUAL(kX, f.X);
}

// repeat for Y and Z

It's not a ton more typing, especially given cut&paste.  Heck, in vim it's just esc y ctrl-{ pp and then minor edits.  With this setup, though, you can see if it's just one field failing and then dig in to see why.

A: I typically find myself having multiple asserts in a method, but they're usually all related to the test at hand. I sometimes chuck in an assert to verify a precondition that I know will break the test because I don't want the test to succeed by accident.
[Test] // NUnit style test.
public void SearchTypeAndInventory()
{
    var specification = new WidgetSearchSpecification
                    {
                        WidgetType = Widget.Screw,
                        MinimumInventory = 10
                    };
var widgets = WidgetRepository.GetWidgets(specification);
if( !widgets.Any() )
    Assert.Inconclusive("No widgets were returned.");
Assert.IsTrue(
    widgets.All( o => o.WidgetType == Widget.Screw),
    "Not all returned widgets had correct type");
Assert.IsTrue(
    widgets.All( o => o.InventoryCount >= 10),
    "Not all returned widgets had correct inventory count.");

* While I could have combined the Asserts, I find it's more useful to separate what went wrong.

I don't think sticking to a hard rule of 1-assert-per-test is very useful. What's more important is that a test is only testing 1 thing. I've seen many uber-tests that are one enormous method that tests everything about a class. These uber-tests are fragile and hard to maintain.
You should think of your tests as being as important and well-written as the code they are testing. E.g. apply the same refactoring techniques to ensure that a test does one thing and does it well, and isn't a stovepipe that tests everything in sight.

A: The way I read the books, you're supposed to do "Red, Green, Refactor". In the "Refactor" part, you're supposed to refactor both the code under test and the unit tests.
I see nothing wrong with the following refactoring:
Original
[TestMethod]
public void TestOne()
{
    LetsDoSomeSetup();
    AssertSomething();
}

[TestMethod]
public void TestTwo()
{
    LetsDoSomeSetup(); // Same setup
    AssertSomethingElse();
}

Refactored
[TestMethod]
public void TestOneTwo()
{
    LetsDoSomeSetup();
    AssertSomething();
    AssertSomethingElse();
}

Of course, that assumes that the two asserts are related, and of course relies on the same scenario.