text:
Q: php - Comparing associative and numeric array using array_diff Array1 is an associative array containing multiple lists fetched from MySQL, and Array2 is a numerical array, i.e a simple array. Array2 has list_ids, which are to be used to filter the Array1.
Sample of Array1:
Array (
    [0] => Array (
        [id] => 1
        [list_id] => 68
        [list_value] => List-68
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
    [1] => Array (
        [id] => 2
        [list_id] => 69
        [list_value] => List-69
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
    [2] => Array (
        [id] => 3
        [list_id] => 80
        [list_value] => List-80
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
    [3] => Array (
        [id] => 4
        [list_id] => 81
        [list_value] => List-81
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
)

Array2:
[68, 81]
My output should be:
Array (
    [0] => Array (
        [id] => 2
        [list_id] => 69
        [list_value] => List-69
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
    [1] => Array (
        [id] => 3
        [list_id] => 80
        [list_value] => List-80
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
)

So, under normal circumstances array_diff() would do it, but here it won't work. I tried converting the numerical Array2 into an associative and used array_diff_assoc() function, but still didn't work.
I also tried iterating through my numerical array and check each element in the associative Array1 (i.e each fetched row from MySQL) for each number in the numerical array.
foreach ($list as $val) {
    while ( $r = mysqli_fetch_assoc($result)) {
        echo $val."<br/>";
        if($r['list_id'] != $val ) {
                $new[] = $r;
        }
    }
}
print_r($new);

But the output echoes only the first number of numerical Array1 4 times (the length of Array1) and hence only one list_id is removed out of the associative Array2 instead of 2:
68
68
68
68
Array (
    [0] => Array (
        [id] => 2
        [list_id] => 69
        [list_value] => List-69
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
    [1] => Array (
        [id] => 3
        [list_id] => 80
        [list_value] => List-80
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )
    [2] => Array (
        [id] => 4
        [list_id] => 81
        [list_value] => List-81
        [subject] => "abc"
        [message] => "abc"
        [obj_var] => "abc"
        [url_link] => "abc"
        [list_time] => 2014-05-13 22:04:04
    )

)

So, how can I make it work? What would be the optimum algorithm?

A: You can use foreach loop with in_array check to unset unwanted elements :
foreach ($Array1 as $key => $value)
    if(in_array($valeu['list_id'], $Array2)) unset($list[$key]);

A: I've simplified your code to the following.
$arr1 = array();
while ( $r = mysqli_fetch_assoc($result)) { $arr1[] = $r; }
$arr2 = array(68,81);

// the magic happends here. It will return an array with only the elements that matches the id of those values in $arr2
$filtered = array_filter($arr1, function ($val) use ($arr2) { return !in_array($val['id'], $arr2); });


text:
Q: Load .csv files from folder I have a folder with .csv files, total size 6 GB.
I want to insert all my data from this folder in Stata, automatically.
Searching the net, I have found some solutions, like:
cd "E:\myfolder"

. insheet using "file1.csv"

. save "a", replace

. local satafiles: dir . files "*.csv"

. foreach file of local satafiles {
  2. append using "a"
  3. save "myfile.dta", replace
  4. }

But if I explore the imported data, I have the same date value in all entries.
Does anyone have experience in Stata import of data?

A: It's repeating because you are just appending "a", i.e. your first dataset, multiple times. Try this:
cd "E:\myfolder"

clear
local satafiles: dir . files "*.csv"

foreach file of local satafiles {
    preserve
    insheet using `file',clear
    save temp,replace
    restore
    append using temp
}
*remove the temporary .dta file
rm temp

save alldata, replace

Note that if the files are becoming too large you can do some space-saving formatting after the insheet command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Updating Existing Android App on Play Store Gives Error When I update the App with the new apk. it gives the error as attached image.
says
Upload Failed, We could not save your changes, please try again
my package name is the same, same key store is used...
What will be the reasons ? Thanks

A: It is a known problem with Google Play today.


text:
Q: Invalid SQL syntax. Trying to run php to mysql I'm receiving the following error message when I try to run php:

Invalid query: You have an error in your SQL syntax; check the manual
  that corresponds to your MySQL server version for the right syntax to
  use near 'query' at line 1

Here's my code. I've looked at similar issues and nothing seems to be working.
<?php

    require("phpsqlajax_dbinfo.php");

    // Start XML file, create parent node

    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);

    // Opens a connection to a MySQL server

    $connection=mysqli_connect ('127.0.0.1', 'chris', 'banks');
    if (!$connection) {  die('Not connected : ' . mysql_error());}

    // Set the active MySQL database

    $db_selected = mysqli_select_db($connection, 'business');
    if (!$db_selected) {
      die ('Can\'t use db : ' . mysql_error());
    }

    // Select all the rows in the markers table

    $query = "SELECT * FROM markers WHERE 1";
    $result = mysqli_query($connection, 'query');
    if (!$result) {
      die('Invalid query: ' . mysqli_error($connection));
    }

    header("Content-type: text/xml");

    // Iterate through the rows, adding XML nodes for each

    while ($row = @mysql_fetch_assoc($result)){
      // Add to XML document node
      $node = $dom->createElement("marker");
      $newnode = $parnode->appendChild($node);
      $newnode->setAttribute("id",$row['id']);
      $newnode->setAttribute("name",$row['name']);
      $newnode->setAttribute("address", $row['address']);
      $newnode->setAttribute("lat", $row['lat']);
      $newnode->setAttribute("lng", $row['lng']);
      $newnode->setAttribute("type", $row['type']);
    }

    echo $dom->saveXML();

?>

A: Change
$result = mysqli_query($connection, 'query');

To
$result = mysqli_query($connection, $query);

Also WHERE 1 doesn't make much sense.

A: 1.First of all,don't mix drivers as you are using mysqli and mysql at the same place. Prefer mysqli as mysql has deprecated.

*Change your code from

$result = mysqli_query($connection, 'query');

To

$result = mysqli_query($connection, $query);

because you have stored your sql query in $query variable.
3.avoid "where 1" --simply use SELECT * FROM markers
although it seems to work in phpmyadmin but avoid it using in php code.
Hope it works..!!!


text:
Q: Override Theme CSS with CSS from a plugin I have seen multiple questions regarding overriding a plugin's CSS with a theme(Example 1, Example 2, etc), but I am looking for the opposite.
I have installed a job board plugin that comes with some custom CSS, however my theme is overriding that plugin's CSS.  It's not a deal breaker, but I don't like what my theme is doing with the CSS.  I could of course grab the CSS that I want and put it into my child theme's stylesheet, but I imagine there is a more elegant and simple solution.
I'm using the plugin WP Job Manager with the theme Divi from Elegant Themes.  The plugin works fine overall without issue, but I prefer the look of the form fields when it is used in a default theme (i.e. Twenty-Twelve).
Any advice is welcome.

A: You can try to dequeue the plugin stylesheet, then re-enqueue the stylesheet with your theme stylesheet added as a dependency which will ensure that the plugin stylesheet is loaded after your theme stylesheet.
function custom_style_order() {

    if ( defined('JOB_MANAGER_PLUGIN_URL') ) {

        //dequeue the original plugin stylesheet by its handle
        wp_dequeue_style( 'wp-job-manager-frontend' );

        //re-enqueue the stylesheet but with an added dependency (your theme stylesheet)
        wp_enqueue_style(
            'wp-job-manager-frontend',
            JOB_MANAGER_PLUGIN_URL . '/assets/css/frontend.css',
            array('your-theme-stylesheet-handle')
        );

    }

}

add_action('wp_enqueue_scripts', 'custom_style_order', 100);

Note: you will need to find the "handle" of your theme stylesheet, as an example if we are dealing with a default theme like Twenty Twelve, then the handle for that themes main stylesheet is twentytwelve-style found in its functions.php file on line 150.


text:
Q: Convert Single to Boolean (Kotlin) I have a mutable live data which I use to adjust visibility(with binding adapter) in my layout. I use the boolean value of live data to achieve this with the code below.
@BindingAdapter("viewVisibility")
fun setVisibility(view: View, visible: Boolean) {
    view.visibility = if (visible) View.VISIBLE else View.GONE
}

To get this data I use the following method
   Flowable.just(
Sdk().searchContact(CHATBOT_NAME)).map {!(it.isEmpty()) }

it.isEmpty() gives me a Flowable < Single< Boolean>> instead of Flowable and I want to convert this Single to a boolean(to give it as a parameter to my binding adapter) but I could not find a way to convert it. My temporary (probably bad) solution is below.
  it.blockingLast().isEmpty() // Blocking last gives me a list so I can get non-single boolean with isEmpty. Since I need one element from search contact method blocking last or first works same in this case.

Is this an acceptable solution? How can I convert Single to normal Boolean?

A: it's me again,try following code:
fun doesExist(): Flowable<Boolean> {
   return Flowable.just(Single.just(Sdk().searchContact(CHATBOT_NAME)).map{ it.isEmpty()}).map {it.blockingGet() }
}


text:
Q: WP_Query Not Working with Variable If I use this code(code not complete, this is the problem section), the posts appear properly. NOTE the "new WP_Query('cat=2,3,5,6,7,8,9');":
$catslugs = array('academic',/*'adventure',*/ 'arts', 'religious', 'special-interest', 'special-needs', 'sports','teen');//Must upate as new Main categories are added
    $out = array();
    foreach($catslugs as $slug) {
        array_push($out, get_category_by_slug($slug)->term_id);
        $CatIDs= implode(',', $out);
        }
    //featured category ID = 153
    //academic category ID = 2
    //adventure category ID = 4
    //arts category ID = 3
    //religious category ID = 5
    //special-interest category ID = 6
    //special-needs category ID = 7
    //sports category ID = 8
    //teen category ID = 9
    $CatIDsCode="'cat=".$CatIDs."'";
    $camp_posts_bynumber = new WP_Query('cat=2,3,5,6,7,8,9');

    if( $camp_posts_bynumber->have_posts() ):

If I change it to this it doesn't. Instead it shows ALL categories including "Uncategorized". What am I doing wrong? Is it something with "have_posts()"
$catslugs = array('academic',/*'adventure',*/ 'arts', 'religious', 'special-interest', 'special-needs', 'sports','teen');//Must upate as new Main categories are added
$out = array();
foreach($catslugs as $slug) {
    array_push($out, get_category_by_slug($slug)->term_id);
    $CatIDs= implode(',', $out);
    }
//featured category ID = 153
//academic category ID = 2
//adventure category ID = 4
//arts category ID = 3
//religious category ID = 5
//special-interest category ID = 6
//special-needs category ID = 7
//sports category ID = 8
//teen category ID = 9
$CatIDsCode="'cat=".$CatIDs."'";
$camp_posts_bynumber = new WP_Query($CatIDsCode);

if( $camp_posts_bynumber->have_posts() ):

OR
$catslugs = array('academic',/*'adventure',*/ 'arts', 'religious', 'special-interest', 'special-needs', 'sports','teen');//Must upate as new Main categories are added
$out = array();
foreach($catslugs as $slug) {
    array_push($out, get_category_by_slug($slug)->term_id);
    $CatIDs= implode(',', $out);
    }
//featured category ID = 153
//academic category ID = 2
//adventure category ID = 4
//arts category ID = 3
//religious category ID = 5
//special-interest category ID = 6
//special-needs category ID = 7
//sports category ID = 8
//teen category ID = 9
$CatIDsCode="'cat=".$CatIDs."'";
$camp_posts_bynumber = new WP_Query($CatIDs);

if( $camp_posts_bynumber->have_posts() ):

A: I'm pretty sure it's because you've got mixed nested quotes when you're setting $CatIDsCode.
So this should fix it:
$camp_posts_bynumber = new WP_Query (array ('cat' => $CatIDs));

P.S. Move $CatIDs= implode(',', $out); outside of the foreach loop. :)


text:
Q: Steps to Debug Dependancy In Webapp Eclipse/Tomcat I have the Maven Web App, where I have to many dependencies. I am trying to create the Remote Debug configuration in eclipse to debug jars when my home page open. As I am aware to to the debugging on java code, how can i do the same with maven dependencies.
Thanks,

A: You can debug libraries from maven the same way you debug your code. Nothing special need to be configured in debugger.
You just need to make sure for the libraries you're going to debug, sources are available in eclipse.
You can either download and specify them manually, or let maven download sources automatically for you.


text:
Q: Vue: moving from slots to v-slot for Vue 3 I am currently using a simple implementation of slots in Vue 2.  I have my parent component using MyComponent and slotting in OtherComponent.  My MyComponent code
uses <slot></slot> for the content.  How would I make changes to the slots to adapt for Vue 3's v-slot since slot is deprecated?
Parent.vue
<MyComponent>
    <template v-slot="slotProps">
       <OtherComponent
          :data="slotProps.data"
       >
       </OtherComponent>
   </template>
</MyComponent>

MyComponent.vue
<template>
    <div class="container">
       <template v-for="(item, index) in data">
            <slot :item="item"></slot>
       </template>
    </div>
</template>


text:
Q: Discretizing over the area of an ellipse given bounds The problem is I have a center (x,y) and some standard deviations sigma_{x1} and sigma_{x2}, together I can use these to plot a Gaussian 3-sigma confidence interval of the center (x,y)
I need to discretize over this ellipsoid such that I can evaluate the expected value of a function as f(x,y)*p(x,y) but I am not sure how to generate the x and y "mesh". I'm not sure if mesh is the correct terminology here.
If this were a square instead the answer would be applying np.linspace(start=min, stop=max) for some arbitrary min/max value for x and y. I am not entirely sure how to proceed for non-rectangular shapes?  My thought process at first was to generate a rectangular region around and then select points for which solving the ellipse equation returns something <=1 but I figure this is not the most efficient way to implement this.
Note: Currently using python 3.6.9 and numpy 1.19.4

A: I don't think you can do it much more efficiently than with the approach you already proposed. To make a grid you can use
x, y = np.mgrid[minx:maxx:step*1j, miny:maxy:step*1j]

Here mgrid is basically a multidimensional version of np.linspace.
Then you just need to discard values outside of your ellipse and retain the ones inside. This is easiest by "masking" using logical indexing:
mask = x**2 + y**2 < 1  # replace unit circle equation with ellipse equation
x, y = x[mask], y[mask]

Then you can evaluate your expected value using
ev = (f(x,y) * p(x, y)).sum()

(assuming both f and p can deal with vectors as inputs).


text:
Q: MbUnit cannot recognize test assemblies compiled with MSBuild on Windows Server 2003 I've recently installed MbUnit version 2.4.2.355 on our build server which runs via Cruise Control.NET and NAnt, on a Windows Server 2003 machine with .NET Framework 3.5 SP1 installed.
I've checked every nook and cranny of the build scripts, and the NAnt output report on CC.NET tells me that the test project builds fine.
This is the NAnt script:
<target name="compiletests" description="Compiles unit tests separately">
    <exec program="${netframework.dir}\msbuild.exe">
        <arg line="C:\dev\PROJ3.1\trunk\src\PROJ\Customer\CustomerUnitTests\Company.CustomerUnitTests.csproj  /t:Rebuild /p:Configuration=Debug"></arg>
    </exec>
</target>

And the output is the ff:

[exec] Company.CustomerUnitTests ->
  C:\dev\PROJ.1\trunk\src\PROJ\Customer\CustomerUnitTests\bin\Debug\Company.CustomerUnitTests.dll
  [exec] Done Building Project
  "C:\dev\PROJ.1\trunk\src\PROJ\Customer\CustomerUnitTests\Company.CustomerUnitTests.csproj"
  (Rebuild target(s)). [exec] Build
  succeeded. [exec]
  "C:\dev\PROJ3.1\trunk\src\PROJ\Customer\CustomerUnitTests\Company.CustomerUnitTests.csproj"
  (Rebuild target) (1) ->

What this means is that the build of the unit test assembly succeeded.
Thing is, at the end of the NAnt outputs is this:

mbunit-tests: [mbunit] MbUnit
  2.4.2.355 test runner [mbunit] No test assemblies found in test

I've gone console and tried using MbUnit.Cons.Exe to manually test the compiled assemblies. The results went like this:

*

*Test assemblies built using my Windows XP SP3 machine were properly recognized and the tests were being run properly on my machine, and on any other dev machine for that matter.

*Test assemblies built in the build server running Windows Server 2003 weren't being recognized as test assemblies; I tried copying those files into my XP machine and they weren't recognized either.

I'm now wondering: what is the difference between a test assembly and a non-test assembly? I'm sure it has something to do with the Test and TestFixture attributes, but in my case, why are the assemblies compiled in WinXP machines compiled as tests, and those compiled the Win2K3 machine not recognized?
Hope someone has a clue on this.

A: First of all check this issue.
If this not help, you need to check target platform (project properties, build) to be "Any CPU". After this try to open assembly which is generated on your build machine using Reflector. May be generated files are corrupted. And also could you please try to build the project manually using VS and load generated tests in MbUnit.

A: There is no fundamental difference as to whether any particular assembly is considered a test assembly.
My guess is that your dev machine is running a slightly different build of MbUnit than your build server.  MbUnit v2 has cross-version compatibility issues that can cause it not to recognize tests properly (because it attempts to load a different version of the framework assembly than is installed).
Incidentally, these issues have largely been resolved in MbUnit v3.
If you haven't done so already, you may find it helpful to install a copy of MbUnit in your source tree.  That will ensure that a consistent version is always used everywhere.


text:
Q: why has firebug greyed-out my area element <map name="theMap">
  <area alt="Find out more" style="cursor:pointer;" coords="0,0,10,10" shape="rect" href="#">
</map>

in firebug the area element is greyed out. There are no CSS styles affecting it. The map element shows clearly.

A: It was because I hadnt put a hash in the usemap attribute of my image.
usemap="theMap" should have been usemap="#theMap"


text:
Q: Matplotlib log log plot not displaying all major and minor ticks when using loglocator and different x and y limits I am making a log log plot and using matplotlib. I am using loglocator to make sure the relevant major and minor ticks are displayed. However, I noticed that when the x and y limits are different, some ticks and tick labels and missing:

Below there is a simple example that produces this undesired behaviour. Any help would be greatly appreciated.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib

Npoints=100
xs=np.logspace(-8,0, 100)
ys=xs

fig=plt.figure(figsize=(4,3))
ax=fig.add_subplot(111)
ax.plot(xs, ys)
ax.set_xscale('log')
ax.set_yscale('log')

locmaj = matplotlib.ticker.LogLocator(base=10,numticks=100)
locmin = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) # subs=(0.2,0.4,0.6,0.8)

ax.yaxis.set_major_locator(locmaj)
ax.yaxis.set_minor_locator(locmin)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.xaxis.set_major_locator(locmaj)
ax.xaxis.set_minor_locator(locmin)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.set_xlim(1.0e-3, 1.0)
ax.set_ylim(1.0e-8, 1.0)

plt.show()

A: In general, Locator instances should not be reused on different axes. From the Locator docs:

Note that the same locator should not be used across multiple Axis because the locator stores references to the Axis data and view limits.

So, for your plot, when you reuse the locators on the x-axis, they modify the ticks on the y-axis in an undesirable way. To fix this. you should make a separate instance of each LogLocator for use on each axis.  For example:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib

Npoints=100
xs=np.logspace(-8,0, 100)
ys=xs

fig=plt.figure(figsize=(4,3))
ax=fig.add_subplot(111)
ax.plot(xs, ys)
ax.set_xscale('log')
ax.set_yscale('log')

locmajx = matplotlib.ticker.LogLocator(base=10,numticks=100)
locminx = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) # subs=(0.2,0.4,0.6,0.8)
locmajy = matplotlib.ticker.LogLocator(base=10,numticks=100)
locminy = matplotlib.ticker.LogLocator(base=10,subs=np.arange(2, 10) * .1,numticks=100) # subs=(0.2,0.4,0.6,0.8)

ax.yaxis.set_major_locator(locmajy)
ax.yaxis.set_minor_locator(locminy)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.xaxis.set_major_locator(locmajx)
ax.xaxis.set_minor_locator(locminx)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())

ax.set_xlim(1.0e-3, 1.0)
ax.set_ylim(1.0e-8, 1.0)

plt.show()


text:
Q: Has vs have in action/singular noun Let's say I'm playing COC(clash of clans), and a clan member donated me troops.
Do I say:

A clan member already has donated me troops.

Or

A clan member already have donated me troops.

P.s: I'm confused now which one is correct, I think 'has' is more correct than 'have' but it doesn't sound right to my ear. Pls. Help.

A: The root of your sentence is

A clan member has...

The subject is singular, so, your sentence would be

A clan member has donated troops to me.

If you insist on using have, you might say

Troops have been donated to me by a clan member.


text:
Q: mysql order by two fields I could solve this on php side, but I would like to use only one query:
I have this rows that represents categories and there list order and subcategory pathway:

 id   order pathway
  1     7     1
  2     5     2
  3     9     2/3
  4     0     4
  5     3     2/3/5

From that data I need to sort them primary by order number and then pathway to list subcategories inside there catetegory:

 id   order pathway
  4     0     4
  2     5     2
  3     9     2/3
  5     3     2/3/5
  1     7     1

UPDATE:
simple sort by order, pathway doesn't work in this case.
First row that need to be outputed is ID:4 because it has the lowest order number
Then ID:2 because it has second lowest order number if we exclude ID:5 because it's inside categories 3 that is inside cat 2.
I also have column that represent category level (is it a main category or category inside some category and have deep) and column for category parent_id

A: SELECT * FROM yourtable ORDER BY order, pathway


text:
Q: MySQL service hung in "Starting" mode I am trying to install multiple instances of MySQL on a Windows Server 2003 using this link.
First instance which is on port 6699 get configured and working successfully. But when I try to install another instance on default port (3306) MySQL service gets hung on "Starting" status. This is the log
140210 17:13:20 [Note] Plugin 'FEDERATED' is disabled.
140210 17:13:20 InnoDB: The InnoDB memory heap is disabled
140210 17:13:20 InnoDB: Mutexes and rw_locks use Windows interlocked functions
140210 17:13:20 InnoDB: Compressed tables use zlib 1.2.3
140210 17:13:20 InnoDB: Initializing buffer pool, size = 128.0M
140210 17:13:20 InnoDB: Completed initialization of buffer pool
InnoDB: The first specified data file .\ibdata1 did not exist:
InnoDB: a new database to be created!
140210 17:13:21  InnoDB: Setting file .\ibdata1 size to 10 MB
InnoDB: Database physically writes the file full: wait...
140210 17:13:21  InnoDB: Log file .\ib_logfile0 did not exist: new to be created
InnoDB: Setting log file .\ib_logfile0 size to 5 MB
InnoDB: Database physically writes the file full: wait...
140210 17:13:23  InnoDB: Log file .\ib_logfile1 did not exist: new to be created
InnoDB: Setting log file .\ib_logfile1 size to 5 MB
InnoDB: Database physically writes the file full: wait...
InnoDB: Doublewrite buffer not found: creating new
InnoDB: Doublewrite buffer created
InnoDB: 127 rollback segment(s) active.
InnoDB: Creating foreign key constraint system tables
InnoDB: Foreign key constraint system tables created
140210 17:13:26  InnoDB: Waiting for the background threads to start
140210 17:13:27 InnoDB: 1.1.8 started; log sequence number 0
140210 17:13:27 [Note] Server hostname (bind-address): '0.0.0.0'; port: 6699
140210 17:13:27 [Note]   - '0.0.0.0' resolves to '0.0.0.0';
140210 17:13:27 [Note] Server socket created on IP: '0.0.0.0'.
140210 17:13:27 [Note] Event Scheduler: Loaded 0 events
140210 17:13:27 [Note] C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe: ready for connections.
Version: '5.5.25'  socket: ''  port: 6699  MySQL Community Server (GPL)
140210 17:42:18 [Note] Plugin 'FEDERATED' is disabled.
140210 17:42:18 InnoDB: The InnoDB memory heap is disabled
140210 17:42:18 InnoDB: Mutexes and rw_locks use Windows interlocked functions
140210 17:42:18 InnoDB: Compressed tables use zlib 1.2.3
140210 17:42:19 InnoDB: Initializing buffer pool, size = 128.0M
140210 17:42:19 InnoDB: Completed initialization of buffer pool
140210 17:42:19 InnoDB: highest supported file format is Barracuda.
InnoDB: The log sequence number in ibdata files does not match
InnoDB: the log sequence number in the ib_logfiles!

Observe line 140210 17:42:19  InnoDB: Database was not shut down normally!

A:
InnoDB: The log sequence number in ibdata files does not match

Double check your configuration!
Make a binay backup or entire /var/lib/mysql.
If you don't need most recent data, delete the log files and try to start.
If you need your data, try the followling:
Try innodb_force_recovery = 1 to 6 all six options in an increasing order.
Assume the worst -- innodb disk image corrupted.
If you are lucky you can salvage most of your data, perhaps mysql starts in one of recovery modes, run checksum on each table, see what tables are still ok.
If mysql refuses to start up to certain recovery mode N and crashes on startup with recovery mode N, then go looking for those daily/weekly backups I hope you system was configured to take.


text:
Q: If $(x+1)^2-2x>2(x+1)+2,$ then $x$ cannot equal which one of the following? I am preparing to GRE Quant and I ran into one problem which seems to me bit false.
If $(x+1)^2-2x>2(x+1)+2,$ then $x$ cannot equal which one of the following?
(A) -5
(B) -3
(C) 0
(D) 3
(E) 5
The above inequality is equivalent to $x^2-2x-3>0$ and the set of solutions is $(-\infty,-1)\cup(3,+\infty)$.
Immediately we get that $x$ cannot equal $0$ and $3$.
So the answers are (C) and (D).
However in official GRE Guide the answer is (C). Am I false? I rechecked every step in my solution and did not find any mistakes.
Please help

A: HINT: one can write your inequality in the form $$(x+1)^2-2(x+1)>2(x+1)$$ can you finish?
this is equivalent to $$(x+1)^2-4(x+1)>0$$ and this $$(x+1)(x-3)>0$$ and your term $$x^2-2x-3=(x+1)(x-3)>0$$ your solution is right.


text:
Q: Graphics card drivers - dual-link DVI? Running default install of Ubuntu 10.04 on PC with Geforce 9500GT graphics card - would there be any problems running a monitor that needs dual-link DVI cables?

A: There should not be any problems, as long as you have the driver correctly installed by Jockey (Additional Drivers).


text:
Q: pyspark - weighted moving average through uneven period lengths I am trying calculate a weighted (based on duration) moving average of a dataframe with uneven timestamp records.
Below is an example df.
+-----+-------------------+
|value|               date|
+-----+-------------------+
|  9.0|2017-03-15 11:42:00|
|  7.0|2017-03-16 13:02:00|
|  7.0|2017-03-16 19:02:00|
|  7.0|2017-03-16 21:38:00|
|  7.0|2017-03-16 21:58:00|
|  6.0|2017-03-18 10:07:00|
| 22.0|2017-03-18 12:21:00|
| 21.0|2017-03-20 23:21:00|
| 19.0|2017-03-21 10:21:00|
| 17.0|2017-03-04 11:01:00|
| 16.0|2017-03-09 18:41:00|
+-----+-------------------+

I have tried to use rangeBetween but I think it only takes simple average
Then tried to use pyspark.sql.functions.window method with w = window('date','7 days','5 minutes'), and calculate weighted average with a udf, but I haven't been able to even calculate a simple average because it took forever to calculate it.
w = window('date','7 days','5 minutes')
win = Window.partitionBy(w).orderBy(df['date'].asc())
new_df = df.withColumn('average',avg('value').over(win))

I was also advised to transform the table to an evenly distributed time period.
Which one do you advise & why, and how to approach window sliding and filling?
I am a newbie in pyspark
Thanks


text:
Q: Crear SELECT dinámico con javascript con array asociativo en vez de normal SIN eval() ¡Hola!
Quisiera hacer una serie de SELECT dinánicos, cuyo contenido cuyo contenido depende de los SELECT anteriores. La única forma que he encontrado usa la función eval() pero por lo visto no es una buena opción usar esa función.
Además, yo quisiera hacerlo con un array asociativo en vez de un array normal, porque así, al crearlo, al valor del option le añadiría la clave y como texto del option le pondría el valor de dicha clave. Eemplo:
<select name="ComunidadAutonomaEnvio" id="ComunidadAutonomaEnvio">
    <option value="Selecciona">- Selecciona -</option>
    <option value="Andalucia">Andalucía</option>
    <option value="LaRioja">La Rioja</option>
</select>

Con un array asociativo, como por  ejemplo:
var comunidadesAutonomas = {
    "Andalucia" : "Andalucía",
    "LaRioja" : "La Rioja"
};

También me gustaría seleccionar la opción concreta guardada previamente en la base de datos  mysql(en  concreto, por si influye, mariadb). Si bien en el formulario normal la  primera opción estará seleccionada por defecto, quisiera saber cómo decidir dinámicamente (según el dato obtenido con PHP desde MYSQL mediante un objeto como $direccion->getComunidadAutonoma() ) un index concreto buscándolo por el texto del option(el valor en el array) o por el valor del option(la clave del array).
¡Gracias!


text:
Q: Is there a term for an anniversary that falls on the same day of the week as its original date? An anniversary refers to the yearly recurrence of a date of an event. However, being an incredibly sentimental person who also takes notice of all sorts of minor details, I find myself placing significance in anniversaries that happen on the same day of the week.
For example, if an event occurred on Tuesday, June 10, 2008, today will be the sixth anniversary of said event. However, today also happens to be the first anniversary that falls on the same day of the week, i.e., Tuesday, June 10, 2014.
Is there a term that I can use for this, similar to the word "anniversary", or will I have to describe its significance?1

1 I'll probably have to either way, if the term turns out to be a really obscure one.

A: If we follow the etymological path of anniversary:

from annus (genitive anni) "year" (see annual (adj.)) + versus, past participle of vertere "to turn" (see versus).

we can come up with dieiversary as a neologism. (or it can be simplified as diversary or dieversary). Though diversary can be confused as a form of diverse. (or a second anniversary?). I can see that some people already thought about this when you do a search.
In Latin, diēs is day and the genitive form is diēī.
Note: There is also a neologism diaversary which is used for the diabetes diagnosis anniversary.

On the other hand, we would call it a curious coincidence in a normal day. What a coincidence that Merriam-Webster has this example usage:

By a curious coincidence, they bought a house the same day their old one burned down.

Though there is a mathematical and astronomical explanation for the reason that an anniversary can fall on the same day of the week. Usually the first anniversary wouldn't fall on the same day of the event, unless a leap year day occurs on the first year of the event. Because 365 has a remainder 1 when divided by 7 and adding one day gives you the next day of the original event day.

You might say coinciding anniversaries also but it is usually used when the anniversaries of two different events coincide. Though it can be applied to the coinciding anniversaries of the same event.


text:
Q: Renewing Certbot Let's Encrypt WILDCARD Certificates in Cron I've been searching for a good solution to renew WILDCARD certificates from Let's Encrypt.
It's easy to set up a wildcard certificate:
Apache Debian 9 Stretch:
sudo apt-get install certbot python-certbot-apache -t stretch-backports

sudo certbot certonly --cert-name CERTNAME --server https://acme-v02.api.letsencrypt.org/directory --manual --preferred-challenges dns -d 'DOMAIN.co,*.DOMAIN.co'

After the DNS setup, it created the certificate. But now I don't want to deal with it every 90 days for renewal. I've been looking for a good solution for a Cron Job. The problem with most Cron Job solutions is that they are for non-wildcard domains.
I like this solution which checks every day if the certificate can be renewed and renews it if it allows itself to:
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot renew

The problem with wildcard certificates is that it has a DNS setup component and certbot renew doesn't work with manual certbot setup.
I am looking for a Cron Job that is like this:
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' && certbot certonly --cert-name CERTNAME --server https://acme-v02.api.letsencrypt.org/directory --manual --preferred-challenges dns -d 'DOMAIN.co,*.DOMAIN.co'

But I don't think this will work with the DNS setup.
How can I create a Cron Job to renew wildcard certificates property and efficiently?

A: I solved this problem by switching to acme.sh instead of certbot.
Documentation on current versions of certbot (1.30-5) say it can do automated wildcard renewals (DNS-01), but Debian buster stable doesn't yet include a version that does (0.31.0-5). I couldn't get past the limitation.
I found acme.sh as easy to implement and more easy to understand that certbot. My DNS provider is Cloudflare. The support across both solutions is good.


text:
Q: Initializing a SessionManager in Alamofire 4.0 Just upgraded to Alamofire 4.0. Having issues with the session manager. Firstly actually initialising it:
Previously:
let alamoManager = Alamofire.SessionManager(configuration: configuration)

Now:
let alamoManager = Alamofire.SessionManager(configuration: configuration, delegate: SessionDelegate, serverTrustPolicyManager: ServerTrustPolicyManager?)

What is the session delegate object for and why does it have to be included now? What is the trust policy?

A: let configuration = URLSessionConfiguration.default
var alamofireManager = Alamofire.SessionManager(configuration: configuration)


text:
Q: Google App Engine - Connect to remote datastore locally using Objectify I have a google app engine app using the cloud datastore written in Java.  I have an entity class as follows:
@Entity
public class Student {

    @Id private Long studentId;
    @Index private League league;
    @Index private String year;
    private String firstName;
    private String lastName;
    ...
}

I have a csv file of 1K students.  I need to upload this info into the cloud datastore.  I also generally want to interact locally with my remote datastore for testing etc.  I want to be able to do the following (row is a row of the csv file, i'll handle that).
for ( Row row : Iterator<Row> ){
   Student student = new Student(row);
   ofy().save().entity(student).now();
}

This code should run on my local machine and save entities to the cloud datastore.
I can connect to the datastore using the GCD JSON following the methodology at
https://github.com/JavaMonday/gcd-json-java
However, this doesn't allow for the use of objectify.  My app relies on objectify and need to populate in that manner.  Does anyone have a clue how to generically connect and populate the datastore that allows objectify/Java?

A: If you need to connect to remote datastore from local machine, I think you need to use the Remote API: https://cloud.google.com/appengine/docs/java/tools/remoteapi

The Java SDK includes a library called Remote API that lets you
  transparently access App Engine services from any Java application.
  For example, you can use Remote API to access a production datastore
  from an app running on your local machine.

This works for Datastore API, which are used by Objectify. So you're good to go.


text:
Q: EntityFramework/LINQ: filter a hierarchical list I need to filter a hierarchical list like:

*

*Folder 1

*Folder 2

*

*Document 1

*Document 2

*Folder 4

*

*Document 3

*Document 4

*Folder 3

*

*Document

Each folder has folders and/or documents. Each document has a Status enum.
How can i get all empty Folders or with documents where the status from the document is on "Deleted"?
var folders = from f in context.Folders
              // where f.Documents.All( d => d.Status == DocumentStatus.Deleted )
              select f;

Lazy loading is enabled.

A: How about this:
Folders.Where(folder => folder.Documents.Any(document => document.Status == DocumentStatus.Deleted));

Unfortunately you have a more complex structure, the above linq statement will work only of folders have documents and not other folders.
To do what you want to do you will have to define a Predicate manually and filter with that, because in the case that a folder has children which are folders themselves, you have to recursively call the filter method to see if the condition is true.


text:
Q: Store passwords in Ruby script I wrote a helper script in Ruby to handle my file synchronization through some servers. It was used only in my intranet and authentication was made by SSH keys. But now I want to use it where I can't use SSH keys and I want to store the passwords in a config file.
I know, there are some encryption libraries like bcrypt or OpenSSL, but I have a problem with that:

*

*I start my script and enter my passphrase and it is stored in a variable to decrypt my passwords.

*My code is open source.

So everybody, who has access with my user to my computer (which would be the first barrier, which I'd like to extend) and looks into the memory (where my passphrase is stored) can decrypt my password file. How is that handled in applications which are relevant to security?
Edith says as a reply to DevDude (but here, because I want to keep my specifications in my question):
But then this configuration file would be plain text and not encrypted. And when I encrypt this file there are two more issues in my opinion:

*

*The super_secret_pwd would be stored in a variable, so when I would search in the memory of the computer, I would find it, wouldnt I?

*The master password for encryption would be in the memory as plain text, too.

So the big question is: Is it possible to read plain text variables from the memory? As I know it is possible in C and a big security issue.

A: What you are looking for is to use a YAML file with the password/API keys. and never check this file into your repo.
Then you can reference this file on your initializers, and maybe make the password a global variable or x, use configatron, etc.
This is basically how production applications work, they read their important settings from a YAML file stored on the server itself.
This is what I use:
@c = configatron

# Per environment settings
app_settings = YAML.load_file('config/secret_stuff.yml')

@c.password = app_settings['super_secret_pwd']

Do not use ENVIRONMENT variables because they have all sort of security issues. They are an antipattern.


text:
Q: преобразование и отображение char в с++ есть проблема, ввожу русские буквы, например "у", по идее оно должно отображать в формате char "у" , а в формате int номер по таблице ASCII "227", но оно отображает "г" и "-29", хотя с латиницей и знаками препинания работает корректно. Почему так, и что с эти делать?
#include <iostream>;
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
char x;
int y;
cout << "Введите символ _";
cin >> x;
y = x;
cout << x << "   ";
cout << y << endl;
system("pause");
return 0;
}


text:
Q: What does 'relative' mean? Can I talk about my mother if somebody requests me to describe a relative who I am like? I wonder if a relative refers to my aunt, uncle or cousin, or it's just a member in my family such as my mom, dad, etc.
I've looked this word in Cambridge Dictionary and it says

a member of your family

A: Mostly we don't call mom, dad, wife, husband and siblings as relatives, they are called as family members. Aunt, Uncle, Cousin, Nephew, etc are called as relatives. And if someone asks you that which relative do you like the most then don't tell about your family members.
Relatives are those person who are related to you by one of your family member.

A: There are some circumstances in which you might interpet the word "relatives" to exclude your parents and siblings.  For example, if you normally live with your parents, and someone says to you, "Are you staying with relatives this weekend?", you might assume that they mean relatives other than the ones normally live with.
However, generally speaking, "relatives" includes your immediate family as well as more distant relatives.  In fact, the person asking which relaive you resemble is more likely to have close relatives in mind than distant ones, if only because you're less likely to know whether you resemble a distant relative.
So, it's entirely legitimate to answer the question by saying you're like your mother or father.  It's also entirely legitimate to answer it by saying you're like your aunt, uncle, grandfather, grandmother, cousin, or another relative of whom you have sufficient knowledge to answer the question.


text:
Q: Fail to run npm install on local angular project Every time I run npm install on my local angular project I get the following errors:
C:\Projects\Angular>npm install
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://git@github.com/pemrouz/buble.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\elbal\AppData\Roaming\npm-cache\_logs\2019-12-07T09_45_08_860Z-debug.log

I run a Windows 10 Home 64bit OS with the following:
C:\Windows\system32>node -v
v12.13.1

C:\Windows\system32>npm -v
6.13.2

Angular CLI: 8.3.2
Node: 12.13.1
OS: win32 x64
Angular: 8.2.4

I followed the solutions in various posts like:
npm local install fails on first try
npm ERR! Windows_NT 6.1.7601: ENOENT: no such file or directory
Error: npm install -g angular-cli | npm ERR! Windows_NT 10.0.10586
but none of them solved my problem. Can anybody help?

A: try this:
cd C:\Projects\Angular
git clone https://github.com/pemrouz/buble.git
cd buble
npm install

A: try removing package-lock.json and then run npm install again.


text:
Q: Is there a faster way than this to extract data from XML nodes in T-SQL? I am currently trying to create a stored procedure in T-SQL which takes an XML table as its input, and then inserts the data in it into a temporary table.
The XML that I am using has the following format:
<Table>
    <row MyFirstColumn="foo" MySecondColumn="bar" ... />
</Table>

The SQL that I am using to insert this XML data into a temporary table is of the following format:
INSERT INTO
    #TempTable
SELECT
    T.c.value('@MyFirstColumn', 'varchar(50)')
   ,T.c.value('@MySecondColumn', 'varchar(50)')
   ,...
FROM
    @x.nodes('//Table/row') T(c)

However, I am doing this with XML tables containing 150 columns and upwards of  200,000 rows. At present, executing this SQL on 10,000 rows takes ~142 seconds, so this is completely inappropriate for dealing with XML tables containing large numbers of rows.
Can anyone suggest a way to speed up this process?

A: Shredding XML with nodes()/value() in SQL Server has performance issues when you query a lot of columns. There is one nested loop join with a call to a xml function for each column.
Query plan with 3 columns:

Query plan with 5 columns:

Just imagine what it would look like with more than 150 columns.
Another option for you is to use OPENXML. It does not have the same problems with many columns.
Your query would look something like this:
declare @H int;
declare @X xml;

exec sys.sp_xml_preparedocument @H output,
                                @X;

select C1,
       C2,
       C3
from
       openxml(@H, 'Table/row', 0)
       with (
              C1 int,
              C2 int,
              C3 int
            );

exec sys.sp_xml_removedocument @H;

For me, using 150 columns and 1000 rows took about 14 seconds with nodes()/value() and 3 seconds with OPENXML.
Vote for a change.
Code used for testing;
drop table T;

go

declare @C int = 150;
declare @S nvarchar(max);
declare @X xml;
declare @N int = 1000;
declare @D datetime;

set @S = 'create table T('+
stuff((
      select top(@C) ', '+N'C'+cast(row_number() over(order by 1/0) as nvarchar(3)) + N' int'
      from sys.columns
      for xml path('')
      ), 1, 2, '') + ')'

exec sp_executesql @S;

set @S = 'insert into T select top(@N) '+
stuff((
      select top(@C) ',1'
      from sys.columns as c1
      for xml path('')
      ), 1, 1, '') + ' from sys.columns as c1, sys.columns as c2';

exec sp_executesql @S, N'@N int', @N;

set @X = (
         select *
         from dbo.T
         for xml raw, root('Table')
         );

set @S = 'select '+
stuff((
      select top(@C) ', '+N'T.X.value(''@C'+cast(row_number() over(order by 1/0) as nvarchar(3)) + N''', ''int'')'
      from sys.columns
      for xml path('')
      ), 1, 2, '') + ' from @X.nodes(''Table/row'') as T(X)'

set @D = getdate();
exec sp_executesql @S, N'@X xml', @X;
select datediff(second, @D, getdate());

set @S = 'declare @H int;
exec sp_xml_preparedocument @H output, @X;

select *
from openxml(@H, ''Table/row'', 0)
  with (' +
stuff((
      select top(@C) ', C'+cast(row_number() over(order by 1/0) as nvarchar(3))+ ' int'
      from sys.columns
      for xml path('')
      ), 1, 2, '') + ');
exec sys.sp_xml_removedocument @H';

set @D = getdate();
exec sp_executesql @S, N'@X xml', @X
select datediff(second, @D, getdate());

A: I really liked and voted for Mikael Eriksson answer, but there's one aspect about it:
His test generates 909 KB XML document with 1000 rows, 150 columns.
And sp_xml_preparedocument takes only 226 milliseconds in his case (which is really fast), but...
I tried applying it to my XML document which is 521 MB.
It contains 2045156 rows with 11 different columns, all are read as nvarchar(255)
When I selected all 11 columns via *:

*

*select * via .value() took 297 sec

*select * via openxml took 231 sec in total:
(sp_xml_preparedocument took 107 sec, select * from openxml took 123 sec)

openxml works better in this case!
When I selected only 2 columns:

*

*select 2 columns via .value() took 57 sec

*select 2 columns via openxml took 189 sec in total:
(sp_xml_preparedocument - 86 sec, select * from openxml - 103 sec)

.value() works better in this case!
So it looks like which method is faster actually depends on xml size, number of rows and number of columns that you query from xml!

A: SQL-Server is pretty fast in dealing with XML, but you did not tell us the most important thing: Where is @x coming from?
Within SQL-Server the XML is not stored as as string you see, but as a hierarchically organised tree in physical tables. If you get this XML on string base and assign it to a variable of type XML, the engine will have to parse the whole lot and transfer all its content into the internal structures. The rest should be rather fast.
On the first sight there are two places to tune it a bit:

*

*FROM @x.nodes('//Table/row') T(c)
The // will use a deep search, the engine will look into each <row> if there might be another <Table> nested below. Rather use FROM @x.nodes('/Table/row') T(c).

*And use 'nvarchar(50)' instead of 'varchar(50)'. Internally XML stores its strings as NVARCHAR. You can avoid all these casts...
If you have SQL-Server 2016+ and you have control over the sender, you might give JSON a try. This is better in one-time-actions because it will not transfer your data in internal structures before it can work with it.

A: Your options depend on how much control you have over the server and what preparation you're willing and able to do.
If you have the ability to clean your data before calling the procedure (running an executable, for example)...
You could deserialize your data into an entity and use your ORM tool of choice (nHibernate, EntityFramework, etc.) to store the entity.
You could parse the XML into an object that a bulk importer could handle, store it to a file, and make use of sql's bulk import functionality. https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017
If you are able to make use of custom functionality on the server, you can use CLR user-defined functions to do this work instead of running it in a separate executable. https://learn.microsoft.com/en-us/sql/relational-databases/clr-integration-database-objects-user-defined-functions/clr-user-defined-functions?view=sql-server-2017
If I think of anything else I'll edit this post.


text:
Q: Controller is accepting null as request body on one environment but refuses on another I have encountered a puzzling behavior between production and development environments.
My Spring controller is as follows (the same between the two environments)
    @RequestMapping(value = "/find")
    @ResponseBody
    public List<D> find(@RequestBody P params) throws Exception {
        // omitted
    }

When a request is done by Chrome on production environment, the browser receives correct response:

However, when the request is done by Chrome on development environment, Spring prints a warning (warning points to missing request body)
WARN [qtp543254421-52] AbstractHandlerExceptionResolver.java:197 -
Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
Required request body is missing: public java.util.List<D>
pl.kg.ut.postgres.controller.ReadPostgresController.find(P) throws java.lang.Exception]

Here's a screenshot of that request from Chrome.

When we compare the two request (from dev and prod) there are some similarities and differences. Request URL, Request Method, and Request Payload are the same. (What is striking is that Request Payload is null  but the controller needs a payload.) What is different is request headers: there are more of them when request is made from production.

A: You definitely shouldn't GET HTTP method request with body for parsing.
Data enclosure is done with HTTP POST for stored request' body.
Please, try to defined code below for posting valid payload.
@RequestMapping(value = "/find", method=RequestMethod.POST)
@ResponseBody
public List<D> find(@RequestBody P params) throws Exception {
    // omitted
}


text:
Q: Storing JSP Tags in a Database I have a requirement to store jsp content in a oracle database. I retrieve it from the database and store it in a string and output it by setting escapeXML to false which renders the html.
<c:out value="${myProfileForm.skinElement.footerContent}" escapeXml="false"/>

This works fine except for tags which end up resolving as html and not tags for example:
        <c:choose>
        <c:when test="${displayLinks=='true'}">
            <jsp:include page="header-myprofile.jsp" />
        </c:when>
        <c:when test="${displayLinks=='false'}">
            <jsp:include page="header-no-menu.jsp" />
        </c:when>
        <c:otherwise>
            <jsp:include page="header-myprofile.jsp" />
        </c:otherwise>
    </c:choose>

Is there a way to store jsp tags in a database?

A: Instead of storing JSP in database you can achieve the same thing by using a Templating Engine like Velocity or FreeMarker.


text:
Q: How to prove $A \succeq B \Leftrightarrow AB=B$ for orthogonal projectors $A, B$? For orthogonal projection matrices $A, B \in \mathbb R^{n\times n}$, we have that

*

*$A^\top = A$ and $A^2 = A$

*$B^\top = B$ and $B^2 = B$
where $A^\top$ is the transpose of $A$, and $A \succeq B $ says that $A-B$ is a positive semidefinite matrix.
I would like to prove the following proposition
$$A \succeq B \Leftrightarrow AB = B$$
For showing $A \succeq B \Rightarrow AB = B$, we have that
$$
\begin{aligned}
A-B \succeq 0 &\Rightarrow x^\top (A-B)x \ge 0 \; \forall x \\
&\Rightarrow y^\top(I-A)^\top(A-B)(I-A)y \ge 0 \; \text{for } x = (I-A)y \; \forall y\\
&\Rightarrow y^\top(I-A)^\top B(I-A)y \le 0 \; \forall y \; \text{ as } A(I-A)=0 \\
&\Rightarrow y^\top(I-A)^\top B(I-A)y = 0 \; \forall y \; \text{ as } B \succeq 0\\
&\Rightarrow y^\top(I-A)^\top B^\top B(I-A)y = 0 \; \forall y \; \text{ as } B=B^2=B^\top B \\
&\Rightarrow B(I-A) = 0 \\
&\Rightarrow A^\top B^\top = B^\top \\
&\Rightarrow AB = B
\end{aligned}
$$
Not sure how to show $A-B\succeq 0 \Leftarrow AB = B$.

A: For the $\Leftarrow$ direction: Suppose that $AB=B$. Observe that $BA=B^{T}A^{T}=(AB)^{T}=B^{T}=B=AB$.
That is, $A$ and B commutes. Also, $(I-B)^{2}=I-B$. Let $x$ be
an arbitrary vector. Consider
\begin{eqnarray*}
 &  & \langle(A-B)x,x\rangle\\
 & = & \langle A(I-B)x,x\rangle\\
 & = & \langle A(I-B)^{2}x,x\rangle\\
 & = & \langle(I-B)A(I-B)x,x\rangle\\
 & = & \langle A(I-B)x,(I-B)^{T}x\rangle\\
 & = & \langle A(I-B)x,(I-B)x\rangle\\
 & \geq & 0.
\end{eqnarray*}
(In the above, $\langle\cdot,\cdot\rangle$ denotes the usual inner
product.) Obviously $A-B$ is symmetric. Hence, $A-B$ is positive semi-definite.


text:
Q: LINQ: Comparing specific values in two datatables I have two datatables.
datatable 1 has data with columns FirstName, LastName, DOB, Gender
datatable 2 has data with columns CustomerID, FirstName, LastName, DOB, Gender
I want to compare the firstName, LastName, DOB and gender in datatable 1 and 2, and if there is a match, load that row in datatable 2 into a new datatable.
Below is what I am using, I can compare with Firstname, but I want to add the lastname, DOB and gender. Please can you show me how I can do that?
I want to do it such that if firstname, lastname, dob and gender match then return that matching row in datatable 2. The column length between the tables are different.
DataTable dtMerged = (from a in dataTable.AsEnumerable()
                                  join b in dt.AsEnumerable()
                                  on a["Forename"].ToString() equals b["FirstName"].ToString()
                                  into g
                                  where g.Count() > 0
                                  select a).CopyToDataTable();

            dtMerged.AsDataView();

A: Try this
DataTable dtMerged = dataTable.AsEnumerable()
    .Where(ra => dt.AsEnumerable()
    .Any(rb => rb.Field<string>("firstname") == ra.Field<string>("firstname")
      && rb.Field<string>("lastname") == ra.Field<string>("lastname")
      && rb.Field<DateTime>("dob") == ra.Field<DateTime>("dob")
      && rb.Field<string>("gender") == ra.Field<string>("gender")))
              .CopyToDataTable();


text:
Q: Firebase Realtime Database Get Value and Increment I have firebase realtime database. I have tags and users. When someone clicked the button i want to get like value from tag, increase it and update new value. But i have observer and i cant get updated value with this code:
DataService.dataService.TAG_REF.observe(.value, with: { (snapshot) in
    self.tags = []

    if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
        for snap in snapshots {
            if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
                let key = snap.key
                let tag = Tag(key: key, dictionary: postDictionary)
                self.tags.insert(tag, at: 0)
            }
        }
    }
    self.dashCollectionView.reloadData()
    }) { (error) in
        print(error.localizedDescription)
}

And when i clicked button:
if sender.image(for: .normal) == UIImage(named: "like") {
    DataService.dataService.TAG_REF.child(selectedTag.tagKey).observeSingleEvent(of: .value, with: { snapshot in
        let totalLikeSnap = snapshot.value as! Dictionary<String, AnyObject>
        var totalLike = totalLikeSnap["like"] as! Int
        totalLike = totalLike + 1
        DataService.dataService.TAG_REF.child(selectedTag.tagKey).child("like").setValue(totalLike)
    })

    let likedTags = DataService.dataService.CURRENT_USER_REF.child("likedTags").child(selectedTag.tagKey)
    likedTags.setValue(["time": "getcurrenttimelater"])

    sender.setImage(UIImage(named: "liked"), for: .normal)
    sender.setTitle(String(selectedTag.tagLikes), for: .normal)

    self.dashCollectionView.reloadData()
} else {
    print("already liked")
}

But it is not increasing like. I will be happy if anyone help me to update data.
tags {
    -bB1231e23a24 {
       comment: 0
       image: "1"
       like: 1
    }
}

A: First of all change the way you increment your like's in your Database.
func updateTotalNoOfPost(completionBlock : (() -> Void)){

 let prntRef = FIRDatabase.database().reference().child("tags/\(selectedTag.tagKey)")

 prntRef.child("like").runTransactionBlock({ (noOfLikes) -> FIRTransactionResult in
    if let totalLikes = noOfLikes.value as? Int{

        noOfLikes.value = totalLikes + 1
        return FIRTransactionResult.successWithValue(noOfLikes)
    }else{

        return FIRTransactionResult.successWithValue(noOfLikes)

        }
      }, andCompletionBlock: {(error,completion,snap) in

            print(error?.localizedDescription)
            print(completion)
            print(snap)
        if !completion {

            print("The value wasn't able to Update")
            }else{

            completionBlock()
        }
   })
}

There must be an array in which you must be saving your noOfLike's for your collectionView Datasource. When you update your Database, also update your collectionView Datasource.
When your user clicks the button, in your button Function :-
updateTotalNoOfLikes{
   print("Value incremented!")

   // Here add the value to your collectionView datasource
    //And then call collectionView.reloadData()
    }


text:
Q: SSH keys fail for one user I just set up a new Debian server. I disabled root SSH and password auth, so you've gotta use a key file.
For my primary user, everything works exactly as expected. I used ssh-keygen -t dsa and got myself a public and private key. Put one in authorized keys, put the other in a pem file locally.
I wanted to create a user that I can deploy things with, so I did basically the same process. I addusered it, made a .ssh folder, ran ssh-keygen -t dsa (I also tried RSA), put the keys in their appropriate locations.
No luck. I'm getting a Permission denied (publickey) error. When I use the exact same keys as the account that works, same error. When I enable password authentication, I can log in via SSH with the password.
How do I debug this?
EDIT
Verbose ssh output (deployer.pem is proper key):

debug2: key: /Users/eli/.ec2/deployer.pem (0x100126830)
debug2: key: /Users/eli/.ec2/deployer.pem (0x100126b30)
debug2: key: /Users/eli/.ec2/deployer.pem (0x0)
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering public key: /Users/eli/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Offering public key: eli.pem
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Offering public key: /Users/eli/.ec2/deployer.pem
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Offering public key: /Users/eli/.ec2/deployer.pem
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Trying private key: /Users/eli/.ec2/deployer.pem
debug1: read PEM private key done: type DSA
debug3: sign_and_send_pubkey
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

A: Two parts: first, turn up debugging on your ssh sever.  Edit /etc/ssh/sshd_config and increase LogLevel to DEBUG.  Then force your ssh server to reload it's config with killall -HUP <sshd pid>.
That will cause the server to add much more details to your /var/log/secure and/or /var/log/auth logfiles.
Secondly (actually you cant try this first), increase the debug level on the client side.  ssh in to the box with

$ ssh -vvv hostname

and that will print out lots more info about where the process is failing.
If you do turn up the debug level on your ssh server, don't forget to turn it back down when you are finished.

A: Have you checked the permissions on the key files? The .ssh/id_dsa file should be 600 and owned by the user. Run ssh -v root@host to see if this is the problem.

A: If the user's home directory, the .ssh directory under the user's home directory, or the user's authorized_keys file are writable by anyone other than the user (either group or other), key authentication will outright fail because the .ssh/authorized_keys file can no longer be trusted (as another user could then replace or modify it and thus log in as that user).
Try:
chmod go-w ~USER ~USER/.ssh ~USER/.ssh/authorized_keys

and see if that clears up your problem.

A: chown -R username. /home/username/.ssh
chmod 700 /home/username/.ssh
chmod 400 /home/username/.ssh/id_dsa /home/username/.ssh/id_dsa.pub
chmod 600 /home/username/.ssh/authorized_keys

A: Here are a few tips based on the issues I ran into while trying to get ssh working via Pubkey Authentication ie ssh rsa:
in addition to the above tips (permissions, -vvv):
- on the destination server, check the account info via passwd -S username or passwd -s username.  The output will look like [username][stat][pwchg][min][max][warn].  if the [stat] column says LK, you need to unlock the account passwd -u username.  if the [pwchg] date is older than [max] days, you need to change the max days or change the password on username via passwd -x 999 or passwd username
example:
# uname -n
myserver

# pwd
/export/home/santac
# ls -l .ssh
-rw-------   1 santac   users        796 Jul  8 00:27 authorized_keys
# cat .ssh/authorized_keys
ssh-rsa AAABBBCCCboogaboogaAAABBBCCCidonthinkyougetthatthisisbogusbutwhattheheck== santac@otherserv
# date
Wed Jul  8 00:55:10 GMT 2015
# passwd -S santac
santac    LK    03/05/14     7   60     10
(note stat is LK or locked)
# passwd -u santac
# passwd -S santac
santac    PS    03/05/14     7   60     10
(note [pwchg] date is older than 60 days)
# passwd santac
Enter New Password:
Confirm New Password:
# passwd -S santac
santac    PS    07/08/15     7   60     10
(all good now)

FROM THE OTHER SERVER:
# uname -n
otherserv
# pwd
/export/home/santac
# ls -l .ssh
-rw-------   1 santa   users       1675 Jul  6 20:23 id_rsa
-rw-------   1 santa   users        394 Jul  6 20:23 id_rsa.pub
# cat .ssh/id_rsa.pub
ssh-rsa AAABBBCCCboogaboogaAAABBBCCCidonthinkyougetthatthisisbogusbutwhattheheck== santac@otherserv

LOOKS GOOD...


text:
Q: Expression for the connection between RNA strands I'm searching for proper expressions that mean connection of RNA strands.
Up to this time I came with strands connection, strands conjunction, and strands ligation.
Are my expressions proper, or do you know other expressions?

A: Almost certainly ligation is the preferred term here; note that the enzymes that actually connect the strands are termed ligases, which immediately suggests the preferred word for the action they perform.   I would strongly lean away from conjunction, which suggests to me  a word more suited to the particular orientation two strands of RNA might have towards each other, and certainly doesn't immediately suggest the physical connection I think you're implying in your question.  Connection also seems a weak word to use, because it does not convey the aforementioned physical joining together of the strands of RNA; if one used it, it might be ambiguous whether the strands are actually ligated to each other or simply associated together in solution, through weak ionic bonding or some such.
Finally, as a word of advice, you shouldn't really seek a reply to this sort of question at an English language site; technical terms often morph from their intended meaning when they are first coined, to a more precise and different meaning later on as the science advances, so that one might be mislead if one tries to divine the technical usage from the meaning in ordinary language  -- the stuff this StackExchange specializes in.  (In just one example, the TCS site recently hosted a question about what they would might rename the method dynamic programming if they had a choice in the matter; debates like this often occur quite often in the mathematical sciences, subjects in which this forum has no expertise.)

A: The term RNA recombination might be what you are referring to.


text:
Q: Basic TCP protocol questions -- What happens on send() and recv() I have some basic questions on TCP protocol
Situation: Machine_A calls send(sockfd) to send data to Machine_B. send() call succeeds.
Question: When the send() call returns, does it mean the data has already reached Machine_B? Or has it just been accepted by the operating system
Situation: Machine_A calls send(sockfd) to send data to Machine_B. But the application_B on Machine_B has not been reading from the socket fast enough. Application_A is writing 10MB/s but Application_B is just reading 1KB/sec.
Question:

*

*When does the send() call succeed on Machine_A in this case?

*Does it succeed the moment the data is submitted to OS_A on Machine_A or does it wait until there is an acknowledgement from OS_B?

*Does OS_B require Application_B to pull the packets before it is acknowledged to OS_A?

A: send only cares about putting data into the local socket buffer, i.e. it will not wait for an ACK from the recipients machine or even wait until the data are processed by the recipient application (which is even later). If you need this kind of information you would need to have some application-level acknowledgement. Moreover, while an ACK gets send by TCP it would not get send by other protocols like UDP anyway.
send will only fail if it cannot put data in the socket buffer, maybe because there is no socket buffer (socket closed) or because the socket buffer is already full but send called non-blocking. If the socket buffer is full and send is called blocking it will just block until there is again space in the socket buffer.


text:
Q: How to prevent setting the fontsize to tiny from reducing the size of the table caption when using longtable I have a very large table of results. It spans over two pages using the longtable package. To reduce the size of the table I have set the font size to \tiny. However, as a longtable doesn't exist within a float, it makes the table ID (eg "Table 1") before the table caption tiny also.
Below is a working example of my code:
\tiny
    \begin{longtable}{llllll}
    \caption{\normalsize{This is the caption.}}\\
\hline
column 1 & column 2 & column 3 & column 4 & column 5 \\ \hline
blah & blah & blah & blah & blah \\ \hline
\end{longtable}

How do I produce a longtable with tiny text in the cells but normal sizing for the table ID/number?

A: Typesetting of the \caption under longtable is defined within \LT@makecaption and doesn't follow the same protocols of the regular placement of \captions within floats, since a longtable doesn't float.
You can patch \LT@makecaption to use \normalsize for setting the caption (using etoolbox):

\documentclass{article}

\usepackage{longtable,etoolbox}

\makeatletter
\patchcmd{\LT@makecaption}% <cmd>
  {\sbox}% <search>
  {\normalsize\sbox}% <replace>
  {}{}% <success><failure>
\makeatother

\begin{document}

\tiny
\begin{longtable}{ *{6}{l} }
  \caption{This is the caption.} \\
  \hline
  column 1 & column 2 & column 3 & column 4 & column 5 \\
  \hline
  blah & blah & blah & blah & blah \\
  \hline
\end{longtable}

\end{document}

The other - more preferred - option is to use caption:
\usepackage{caption}
\captionsetup{font=normalsize}


text:
Q: Regex to remove all but the last occurrence of a single character Our sanitisation on a salary input replaces all characters other than numerics (0-9) and points (.) with a blank string.
[^0-9.]
Which results in a string like "£63,000.00" becoming "63000.00", which can easily be converted to a float. Now I want to sanitise the case where users have used a point as the thousand separator as well as the decimal separator (eg "63.000.00"). How would I write the regex to remove all but the LAST point character in a string?

A: You can use this rgex for replacement:
\.(?![^.]+$)|[^0-9.]

RegEx Demo
replace by empty string.


text:
Q: How can I use "getopts" without a parameter? (here for "-v") How can I use the getopts without a parameter?
while getopts ":a:f:l:r:h:v:" arg; do
   printf $arg
   case $arg in
     a)
        add_param=${OPTARG}
        ;;
     f)
        file_param=${OPTARG}
        ;;
     l)
        list_param=${OPTARG}
        ;;
     r)
       remove_param=${OPTARG}
       ;;
     v)
       version_param="version"
       printf "hello world"
       ;;
     h | *)
       print_usage
       exit_script
   esac
done

I never get in the case -v if I run my script like this sh script.sh -v because this implementation expects a parameter.
Can you help me to fix that?

A: From help getopts (in bash):

getopts: getopts optstring name [arg]
    Parse option arguments.

    Getopts is used by shell procedures to parse positional parameters
    as options.

    OPTSTRING contains the option letters to be recognized; if a letter
    is followed by a colon, the option is expected to have an argument,
    which should be separated from it by white space.

I think it's valid also for sh. You should try ":a:f:l:r:hv" instead of ":a:f:l:r:h:v:".


text:
Q: NetSuite Custom List/Record Field: Customer Address filtered to Current Record Addresses This relates to Custom Fields in NetSuite.
I have added a List/Record field to Customer records, with the list type "Addressbook".
If you edit this field on a Customer record, it will give you a list of ALL Addresses, not just the ones relating to that specific Customer.
I cannot find a way get the field filtering options to limit the list to the specific record I am editing.
NOTE: Changing the List/Record list type to "Address" will provide no values at all.
Thanks in advance for your help!


text:
Q: why is a User Control's BindingSource.CurrentChanged method being called 3 times when a form is loaded first time? I have a user control that contain a bound datagridview and a collection to load data in binding source.
When I want to load control first time from another form the BindingSource.CurrentChanged method being called 3 times! but when I click next button to see next object on loaded datagridview control, BindingSource.CurrentChanged being called only once.
Can someone please explain why CurrentChanged method is being called 3 times in first time but only once when the control is already loaded?

A: CurrentChanged event is raised whenever the Current property changes for any of the following reasons:
The current position of the List changes.

The DataSource or DataMember properties change.

The membership of the underlying List changes, which causes Position to refer to a different item. Examples include adding or deleting an item before the current item, deleting or moving the current item itself, or moving an item to the current position.

The underlying list is refreshed by a new sorting or filtering operation.

For more information refer to https://social.msdn.microsoft.com/Forums/windows/en-US/5f968c71-a979-4e80-9896-94736e832f0c/bindingsource-currentchanged-event?forum=winformsdatacontrols page.


text:
Q: What simple offline GUI database should I use for this application? I am looking an open source application. Application should have :
  * database support ( create two or three table )
  * GUI ( what I have created should be seen )

Example :
Assume that I have created a table ;

       X_table  :          |  A  | B  | C | D |

 After creating  table, I am loading data
                           |  A  |  B   | C  | D  |
                           |  1  |  11  | b  | f  |   -
                           |  3  |  12  | a  | o  |   - data
                           |  4  |  13  | r  | o  |   -

    When I am opening application not for loading data, I want see data in graphical
 interface.

   One day, I want modify existing data. I can just clicking the place then add new
 data

    Assume I want change 12. I am clicking that position and then writing new data
                           |  A  |  B   | C  | D  |
                           |  -  |  --  | -  | -  |   -
                           |  3  |  19  | a  | o  |   - data
                           |  -  |  --  | -  | -  |   -

Are there any open source application which have above feature ?
Application can be so simple,
 * no internet connection
 * support only one database
 * static table creation ( once created never changed )

Application can be run Ubuntu 12.04 and/or Windows.
In other words, I am wanting database viewer and editor.
EDIT:
I should load pdf file, image etc. or give path of the file to the application.
This link can be reference to my question . ( Interface should be like this, just a list )

A: Libre-office Base sounds like what your after, runs on Windows and Linux, has a GUI, just an alternate to MS Access really.
Edit:
Heres me clicking around adding data straight into the table.

A: Firstly make sure your system is up-to-date.  Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.
sudo apt-get upgrade && sudo apt-get update

Firebird is a relational database offering many ANSI SQL standard
  features that runs on Linux, Windows, and a variety of Unix platforms.
  Firebird offers excellent concurrency, high performance, and powerful
  language support for stored procedures and triggers.

Install Firebird Database on Ubuntu Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.
sudo apt-get install firebird2.1-classic

Source: ubuntugeek
Source: help.ubuntu.com

The MySQL database has become the world's most popular open source
  database because of its high performance, high reliability and ease of
  use. It is also the database of choice for a new generation of
  applications built on the LAMP stack (Linux, Apache, MySQL, PHP / Perl
  / Python.) Many of the world's largest and fastest-growing
  organizations including Facebook, Google, Adobe, Alcatel Lucent and
  Zappos rely on MySQL to save time and money powering their high-volume
  Web sites, business-critical systems and packaged software.
MySQL runs on more than 20 platforms including Linux, Windows, Mac OS,
  Solaris, IBM AIX, giving you the kind of flexibility that puts you in
  control. Whether you're new to database technology or an experienced
  developer or DBA, MySQL offers a comprehensive range of database
  tools, support, training and consulting services to make you
  successful.

To install it Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.
sudo apt-get install mysql-server mysql-client

Source: MySQL
MySQL is not just for writing queries, it a full featured Database application.
But if you want something simple, just use LibreOffice Base, its included in the libreoffice suite that installs when you install Ubuntu.  Or you can use the latest OpenOffice Base  To do so Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command below.
sudo apt-get install openoffice.org-base

A: If you are looking for something similar to MS-Acess or Filemaker, then:
Kexi
Kexi is an integrated data management application by KDE, designed to fill the gap between spreadsheets and database solutions requiring more sophisticated development. Kexi can be used for designing and implementing databases, data inserting and processing, and performing queries.
The impetus for developing Kexi came from a noticeable lack of applications having the features of Microsoft Access, FoxPro, Oracle Forms or FileMaker while at the same time being powerful, inexpensive, open-standards-driven and sufficiently portable.
The proprietary version of Kexi 1.x
Kexi is a component of Calligra Suite. It works under Linux/Unix, Mac OS X (using Fink), Solaris, and the Microsoft Windows (using KDE on Windows) operating systems. Kexi application and libraries is available under the LGPL. User and developer documentation is available under the GFDL.
(source: Wikipedia)

A: To meet your needs I recommend mySQL with mySQL workbench (also from the mysql folks).
It it probably the world's most used open source SQL database and it is supported by Sun/Oracle.
You get command line options:

plus a gui to both let see you data:

and a gui to view the models:


text:
Q: Very odd, unknown cause of Internal Server Error When I request this function
    //Add the content to the database
function articleadd() {
    mysql_query("INSERT INTO site_content (title,content,reference,author,userid,authorip,day,month,year,token) VALUES ('$title','$articlebody','$reference','$author','$userid','$ipaddress','$day','$month','$year','$token')");
}

For some unknown reason it produces a Internal Server Error. I honestly have no idea why, I request this function below and it works fine
    //Add a message if the user is not logged in
function message() {
mysql_query("INSERT INTO messages (from,to,subject,content,type,ip) VALUES ('$userid','$userid','The content $title is pending completion.','A article was attempted to be saved, however when the we tried to saved it there was no-one logged in. As a result we saved the article but quarantined it so it will not show on the website. To correct this error, please click the link below, review the article and confirm it should display on the site. $url','$type','$ipaddress')");

}

With both I am requesting them one after the other as follows
    articleadd()
    message()

I have, in the function which does not work replaced all the mysql query with a very simple
    echo "hello world";

And yet I get the error.
I have tried copying and pasting things even the word "function" to make sure I am not making a silly mistake. I unfortunately do not have access to the Server Log with my hosting provider. Lastly I am aware that I am not passing the variables, and that is a separate issue, but on the basis that one works with out variables and the "hello world" test this can not be the issue.

A: As i can see, there is no values for the variables used inside the functions.
You need to set the values of the variables like $userid, $author, $title from parameters or global variables
function articleadd($title,$articlebody,$reference,$author,$userid,$ipaddress,$day,$month,$year,$token) {
mysql_query("INSERT INTO site_content (title,content,reference,author,userid,authorip,day,month,year,token) VALUES ('$title','$articlebody','$reference','$author','$userid','$ipaddress','$day','$month','$year','$token')");}

And call the function like this
articleadd('title','articlebody','reference','author','userid','ipaddress','day','month','year','token');


text:
Q: Most efficient way to compile unique values in a massive text file? I have a set of large text files that in total contain about 3 million rows.
What I want to do is pluck a value from a given column from each row and add it to an array in memory. If the value already exists in the array, then ignore it.
I'm assuming the fastest way is NOT:

*

*Read a value

*if exists (using array's native index or what-have-you method), then push it to the array

Should I be inserting the value in alphabetical order to speed up the match/search?
OR should I keep multiple arrays...for example, one for each letter of the alphabet?

A: Use Set:

Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup.

Example usage:
require 'set'

set = Set.new
set << 1 << 2 << 3  # => #<Set: {1, 2, 3}>
set << 2            # => #<Set: {1, 2, 3}>

A: You could add the values as keys to a hash map, that would take care of removing duplicates automatically. You could even count the number of times each value occurs this way (with the hash value).


text:
Q: Can't run valgrind massif with "page-as-heap" option I am trying to run Valgrind in Ubuntu 14.04 with the following options:
valgrind --tool=massif --pages-as-heap=yes

But get the following error:
valgrind: Bad option: --page-as-heap=yes

This option is described in several places (and it is actually mentioned in valgrind's manual http://valgrind.org/docs/manual/ms-manual.html) to be used with massif.
How can I have this tool/option avaliable?
Thanks

A: Found the error. The correct command is:
valgrind --tool=massif --pages-as-heap=yes

Note the plural "pages".


text:
Q: Inner Shadow in UILabel is it possible to create such a UILabel with inner and outer shadow?
alt text http://dl.getdropbox.com/u/80699/Bildschirmfoto%202010-07-12%20um%2021.28.57.png
i only know shadowColor and shadowOffset
zoomed:
alt text http://dl.getdropbox.com/u/80699/Bildschirmfoto%202010-07-12%20um%2021.39.56.png
thanks!

A: I use FXLabel for inner shadow, look here  https://github.com/nicklockwood/FXLabel.

A: Yes, I have a blog post about it here. The short answer is to borrow the JTAInnerShadowLayer from here, subclass UILabel, and change its layerclass by overriding + (Class)layerClass so that it returns JTAInnerShadowLayer class like this:
+ (Class)layerClass
{
  return [JTAInnerShadowLayer class];
}

Then in the init method for the layer set up the JTAInnerShadowLayer something like this:
[self setBackgroundColor:[UIColor clearColor]];
JTAInnerShadowLayer *innerShadow = (JTAInnerShadowLayer *)[self layer];
[innerShadow setClipForAnyAlpha:YES];
[innerShadow setOutsideShadowSize:CGSizeMake(0.0, 1.0) radius:1.0];
[innerShadow setInsideShadowSize:CGSizeMake (0.0, 4.0) radius:6.0];
/* Uncomment this to make the label also draw the text (won't work well
   with black text!*/
//[innerShadow drawOriginalImage];

(or just borrow the JTAIndentLabel class).

A: Although Steve's answer does work, it didn't scale to my particular case and so I ended up creating an inner shadow by applying a shadow to a CGPath after clipping my context:
CGContextRef context = UIGraphicsGetCurrentContext();

// clip context so shadow only shows on the inside
CGPathRef roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:4].CGPath;
CGContextAddPath(context, roundedRect);
CGContextClip(context);

CGContextAddPath(context, roundedRect);
CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(), CGSizeMake(0, 0), 3, [UIColor colorWithWhite:0 alpha:1].CGColor);
CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:0 alpha:1].CGColor);
CGContextStrokePath(context);

Which results in:

You can change the shadow offset and blur to change the shadow style. If you need it to be darker, you can also successively add and then stroke the same CGPath, which will make the shadows pile up.

A: The answer by dmaclach is only suitable for shapes that can easily be inverted. My solution is a custom view that works with any shape and also text. It requires iOS 4 and is resolution independent.
First, a graphical explanation of what the code does. The shape here is a circle.

The code draws text with a white dropshadow. If it's not required, the code could be refactored further, because the dropshadow needs to be masked differently. If you need it on an older version of iOS, you would have to replace the block and use an (annoying) CGBitmapContext.
- (UIImage*)blackSquareOfSize:(CGSize)size {
  UIGraphicsBeginImageContextWithOptions(size, NO, 0);
  [[UIColor blackColor] setFill];
  CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, size.width, size.height));
  UIImage *blackSquare = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return blackSquare;
}

- (CGImageRef)createMaskWithSize:(CGSize)size shape:(void (^)(void))block {
  UIGraphicsBeginImageContextWithOptions(size, NO, 0);
  block();
  CGImageRef shape = [UIGraphicsGetImageFromCurrentImageContext() CGImage];
  UIGraphicsEndImageContext();
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(shape),
                                      CGImageGetHeight(shape),
                                      CGImageGetBitsPerComponent(shape),
                                      CGImageGetBitsPerPixel(shape),
                                      CGImageGetBytesPerRow(shape),
                                      CGImageGetDataProvider(shape), NULL, false);
  return mask;
}

- (void)drawRect:(CGRect)rect {
  UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:40.0f];
  CGSize fontSize = [text_ sizeWithFont:font];

  CGImageRef mask = [self createMaskWithSize:rect.size shape:^{
    [[UIColor blackColor] setFill];
    CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
    [[UIColor whiteColor] setFill];
    // custom shape goes here
    [text_ drawAtPoint:CGPointMake((self.bounds.size.width/2)-(fontSize.width/2), 0) withFont:font];
    [text_ drawAtPoint:CGPointMake((self.bounds.size.width/2)-(fontSize.width/2), -1) withFont:font];
  }];

  CGImageRef cutoutRef = CGImageCreateWithMask([self blackSquareOfSize:rect.size].CGImage, mask);
  CGImageRelease(mask);
  UIImage *cutout = [UIImage imageWithCGImage:cutoutRef scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp];
  CGImageRelease(cutoutRef);

  CGImageRef shadedMask = [self createMaskWithSize:rect.size shape:^{
    [[UIColor whiteColor] setFill];
    CGContextFillRect(UIGraphicsGetCurrentContext(), rect);
    CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(), CGSizeMake(0, 1), 1.0f, [[UIColor colorWithWhite:0.0 alpha:0.5] CGColor]);
    [cutout drawAtPoint:CGPointZero];
  }];

  // create negative image
  UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
  [[UIColor blackColor] setFill];
  // custom shape goes here
  [text_ drawAtPoint:CGPointMake((self.bounds.size.width/2)-(fontSize.width/2), -1) withFont:font];
  UIImage *negative = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  CGImageRef innerShadowRef = CGImageCreateWithMask(negative.CGImage, shadedMask);
  CGImageRelease(shadedMask);
  UIImage *innerShadow = [UIImage imageWithCGImage:innerShadowRef scale:[[UIScreen mainScreen] scale] orientation:UIImageOrientationUp];
  CGImageRelease(innerShadowRef);

  // draw actual image
  [[UIColor whiteColor] setFill];
  [text_ drawAtPoint:CGPointMake((self.bounds.size.width/2)-(fontSize.width/2), -0.5) withFont:font];
  [[UIColor colorWithWhite:0.76 alpha:1.0] setFill];
  [text_ drawAtPoint:CGPointMake((self.bounds.size.width/2)-(fontSize.width/2), -1) withFont:font];

  // finally apply shadow
  [innerShadow drawAtPoint:CGPointZero];
}

A: You will have to do your own custom drawing to get an inner shadow. There's no way currently to do it with a standard UILabel.
Here's a reasonable explanation on doing inner shadow with Quartz.
Inner shadow in Core Graphics

A: Try PaintCode trial version! For beginners, you'll learn how to create custom drawings. It's very nice! :3 You can use it for practice or for learning, but don't use it all the time, you should also learn how to create drawings on your own.
Disclaimer: I'm not an endorser, I was just amazed by my discovery. ;)


text:
Q: psql \copy "No such file or directory" if file is a variable I want to copy a .csv file into a postgresql table, where the file name is a variable. It fails with a "no such file or directory" error if \COPY and a user other than postgres is used. However, the copy succeeds if COPY and the postgres user is used.
The failing script:
martin@opensuse1:~> ./test1.sh
Null display is "¤".
'/home/martin/20180423.csv'
psql:load.sql:2: :load_csv: No such file or directory
martin@opensuse1:~> cat test1.sh
load_csv=/home/martin/20180423.csv
psql -d test1 -e -f load.sql --variable=load_csv="'$load_csv'"
martin@opensuse1:~> cat load.sql
\echo :load_csv
\copy test_table (col1, col2, col3) FROM :load_csv delimiter ';' encoding 'LATIN1' NULL '';
martin@opensuse1:~>

The working script:
martin@opensuse1:~> ./test1.sh
Null display is "¤".
'/home/martin/20180423.csv'
copy test_table (col1, col2, col3) FROM '/home/martin/20180423.csv' delimiter ';' encoding 'LATIN1' NULL '';
COPY 3
martin@opensuse1:~> cat test1.sh
load_csv=/home/martin/20180423.csv
psql -w postgres -d test1 -e -f load.sql --variable=load_csv="'$load_csv'"
martin@opensuse1:~> cat load.sql
\echo :load_csv
copy test_table (col1, col2, col3) FROM :load_csv delimiter ';' encoding 'LATIN1' NULL '';
martin@opensuse1:~>

What can I do to make this script run without having to use the postgres user?
Martin

A: It seems that the psql variables are not substituted in the \copy command.
A solution is to write the \copy command to a file and execute that file.
The part from my script (load the table par from the tsv-file with the
name stored in :input_file) is:
    -- Tuples only:
    \t on
    -- Output file:
    \o load_cmd.sql
    select concat('\copy par from ''', :'input_file', '.tsv'';');
    -- Standard output again:
    \o
    -- Normal decoration of tables:
    \t off
    -- Now execute the file with the \copy command:
    \i load_cmd.sql


text:
Q: How to provide different mock services to test Angular 2 component? I have two Mock services:
@Injectable()
class UserRegistrationServiceMock {
    registerBasicDetails(details: UserRegistrationDetails) {
        let response: UserRegistrationResponse = new UserRegistrationResponse();
        response.success = false;
        response.userMessage = 'Test Message';
        return Observable.of(response);
    }

    registerAdvancedDetails() {
    }
}

@Injectable()
class UserRegistrationServiceSuccessMock {
    registerBasicDetails(details: UserRegistrationDetails) {
        let response: UserRegistrationResponse = new UserRegistrationResponse();
        response.success = true;
        response.userMessage = 'Test Message';
        return Observable.of(response);
    }

    registerAdvancedDetails() {
    }
}

In my Jasmine test I provide its definition in the "beforeEachProviders" and "beforeEach" methods:
beforeEachProviders(() => [
 provide(UserRegistrationService, { useClass: UserRegistrationServiceMock })
]);

beforeEach(inject([UserRegistrationService], (_userRegistration))

Then in my actual test I can reference the user registration service to initialise the component:
it('should create an instance', () => {
        let component: BasicRegistrationComponent =
            new BasicRegistrationComponent(null, formBuilder, promptWindow, userInfo, translator, userRegistration);
        expect(component).toBeTruthy();
    });

The question here is how can I provide the second mock implementation of the service for my component?

A: You provide the second mock class the same way you provide the first.
Include it in beforeEachProviders() and beforeEach
beforeEachProviders(() => [
  provide(UserRegistrationService, { useClass: UserRegistrationServiceMock }),
  provide(UserRegistrationServiceSuccess, { useClass: UserRegistrationServiceSuccessMock })
]);

beforeEach(inject([UserRegistrationService, UserRegistrationServiceSuccess], (_userRegistration, _userSuccess))

As a tip I would suggest only injecting what you need for each test, not injecting all dependencies into every test. (Unless you only have one test in that file). Keep beforeEachProviders, but instead of using beforeEach, do this in your component test:
it("should create an instance", inject([UserRegistrationService, UserRegistrationServiceSuccess], (_userRegistration : UserRegistrationServiceMock, _userSuccess : UserRegistrationServiceSuccessMock) => {
        let component: BasicRegistrationComponent =
        new BasicRegistrationComponent(null, formBuilder, promptWindow, userInfo, translator, userRegistration);
        expect(component).toBeTruthy();
}));

Also if you are using mock services you should reference them like above:
_userRegistration : UserRegistrationServiceMock. Basically that inject statement means: when the test is looking for UserRegistrationService I am passing it UserRegistrationServiceMock but I'm calling it _userRegistration. Let me know if this does not help :)

A: The best and most readable way I've found to do this is by nesting an extra set of describe statements:
describe('SomeComponent', () => {

   describe("Normal Registration", () => {
       beforeEachProviders(() => [
           provide(UserRegistrationService, { useClass: UserRegistrationServiceMock })
       ]);

       beforeEach(inject([UserRegistrationService], (_userRegistration))

       it('should create an instance', () => {
          let component: BasicRegistrationComponent =
             new BasicRegistrationComponent(null, formBuilder, promptWindow, userInfo, translator, userRegistration);
           expect(component).toBeTruthy();
       });
    });

    describe("Registration Success", () => {
        beforeEachProviders(() => [
            provide(UserRegistrationService, { useClass: UserRegistrationServiceSuccessMock })
        ]);

        beforeEach(inject([UserRegistrationService], (_userRegistration))

        it('should create an instance', () => {
           let component: BasicRegistrationComponent =
              new BasicRegistrationComponent(null, formBuilder, promptWindow, userInfo, translator, userRegistration);
            expect(component).toBeTruthy();
        });
    });
});