text:
Q: Difficulty creating test class on custom controller for table VF page that lists records from custom object i've spent nearly 2 days looking up how to write a test class and so I thought i'd now ask (works great in staging)
I have a custom controller that pulls records from a custom object, and then displays them as a table:
Apex class name: ouController
Custom object name: ou__c

public class ouController{

public List<ou__c> o_uy{get;set;}

 public ouController() {

    o_uy= [SELECT
         Affected_Receive_Country__c,
         Affected_Send_Country__c,
         Detailed_Description__c,
         End_Date__c,
         Incident_Description_for_CS__c,
         Incident_Status__c,
         Incident_Type__c,
         Service__c,
         Start_Date__c,
         Latest_Update__c,
         Customers_Notified__c,
         API_Enabled_Disabled__c,
         Action__c

             FROM ou__c
                 WHERE Incident_Status__c = 'Open'
                     ORDER BY Incident_Type__c DESC];
     }

  }

The VF page is this:
VF page name: o_u

 <apex:page Controller="ouController">

 <style>
 .headerclass{
 text-align:center;
 }
 </style>

<apex:pageBlock >

    <apex:pageBlockTable value="{!o_uy}" var="ou__c" headerClass="headerclass" style="font-size:10.0pt;">>
        <apex:column value="{!ou__c.Start_Date__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.End_Date__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Service__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Incident_Type__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Affected_Send_Country__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Affected_Receive_Country__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Incident_Description_for_CS__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.API_Enabled_Disabled__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Customers_Notified__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Latest_Update__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>
        <apex:column value="{!ou__c.Action__c}" style="{!IF(CONTAINS(ou__c.Incident_Type__c, 'Outage'), 'background-color: #FFC2C2;',IF(CONTAINS(ou__c.Incident_Type__c, 'Maintenance'), 'background-color: #9CDEFF;', 'background-color: #B0FF9C;'))}"/>

    </apex:pageBlockTable>
</apex:pageBlock>

I'm really struggling here, i've gone through forums, Trailhead and the documentation. I understand that the purpose of the class is see what happens when a record from the custom object is passed through the controller
Conceptually, I believe it should be something like:

@isTest
public class TestouController {
static testMethod void insertou() {

   ou__c testou__c = new ou__c();

   ou__c.Start_Date__c= DateTime.now();  //date/time field
   ou__c.End_Date__c= DateTime.now();  //date/time field
   ou__c.Service__c= 'Airtime';  //multi picklist field
   ou__c.Incident_Type__c= 'Maintenance';  //picklist field
   ou__c.Affected_Send_Country__c= 'Austria';  //picklist field
   ou__c.Affected_Receive_Country__c= 'Algeria';  //picklist field
   ou__c.Incident_Description_for_CS__c= 'test';  //text area 255 field
   ou__c.API_Enabled_Disabled__c= 'Enabled';  //picklist field
   ou__c.Customers_Notified__c= 'Email';  //multi picklist field
   ou__c.Latest_Update__c= 'test';  //Text(255) field
   ou__c.Action__c= 'test';  //text(50) field

   insert testou__c;
}
}

However this is not working at all

A: That's a good start. You're inserting one record in your test class.
The problem is, you don't even call your controller in your test, so it can't be test. Your code is never executed.
So after having inserted record, you just have to call your controller.
Finally, you have to make some assertions to verify that your controller query returns your inserted record.
Here's the right test code:
@isTest
public class TestouController {
static testMethod void insertou() {

   ou__c testOu = new ou__c();

   testOu.Start_Date__c= '11/09/2017';  //date/time field
   testOu.End_Date__c= '11/09/2017';  //date/time field
   testOu.Service__c= 'Airtime';  //multi picklist field
   testOu.Incident_Type__c= 'Maintenance';  //picklist field
   testOu.Affected_Send_Country__c= 'Austria';  //picklist field
   testOu.Affected_Receive_Country__c= 'Algeria';  //picklist field
   testOu.Incident_Description_for_CS__c= 'test';  //text area 255 field
   testOu.API_Enabled_Disabled__c= 'Enabled';  //picklist field
   testOu.Customers_Notified__c= 'Email';  //multi picklist field
   testOu.Latest_Update__c= 'test';  //Text(255) field
   testOu.Action__c= 'test';  //text(50) field
   testOu.Incident_Status__c = 'Open';

   insert testOu;

   ouController controller = new ouController(); //here you call your code

   System.assertEquals(testOu.Id, controller.o_uy[0].Id); // here you verify that your controller variable is instantiated with the right value, ie your previously inserted record
}
}


text:
Q: MSTest.exe finds no test cases via cmd, but works fine in VS2015 IDE I have added a Unit Test App(Universal Windows) Project in Visual Studio 2015. It discovers and runs all test cases in Test Explorer in IDE correctly. But when running MSTest.exe from command line, it gives the message "No tests to execute".
Command executed is
MSTest.exe /testcontainer:"F:\Projects\MyUnitTests\bin\Release\MyUnitTests.exe" /resultsfile:F:\testResults.trx

Same result when used 'vstest.console.exe' as suggested here.
Also, most of the examples online provide a dll to mstest. But there is no dll created in outputs in vs2015. Need this to be executed by script in jenkins. Has anyone else faced this issue?

A: When you run against the exe, you should get a warning similar to this that gives you some hints:

Warning: Unit tests for Windows Store and Windows Phone apps cannot be
  run outside appcontainer. Create an app package and run tests in
  appcontainer mode.
  http://go.microsoft.com/fwlink/?LinkId=254169

In order to use the universal test project, you need to create an app bundle and then run the tests against that. To create the bundle, right click on your project and select Store=>Create App Packages.
You will create a local app package, so you can select No for the prompt to upload to the windows store.
Next you will be prompted to fill out the output location, version, ...
On this screen, make sure you select Never for the Generate app bundle option.
After clicking create, open the command line to the location where the app bundles were created.  You will also have to install the certificate. You can do this from the command line using certutil:
certutil -addstore "Root" .\UnitTestProjectName_1.0.0.0_x86_Debug.cer

Finally, now you can run your tests using the vstest.console.exe command line against the app package:
vstest.console.exe .\UnitTestProjectName_1.0.0.0_x86_Debug.appx /InIsolation

This blog post from Microsoft has more information and some other troubleshooting tips. Even though the blog post is marked for the beta of VS11, it seems that most of it still applies.

redpajama_set_name: RedPajamaStackExchange


text:
Q: É possível alterar o template/interface gráfica de um formulário no Windows Forms? Andei pesquisando sobre e os resultando que consegui foram apenas recorrer ao WPF ao invés de usar WinForm, mas ainda tenho está duvida e acredito que seja possível, é possível alterar a template do software desenvolvido em Windows Forms?

A: Existem algumas bibliotecas como o QIOS, o Krypton e o DotNetBar que permitem alterar o look da aplicação, mas não tenho certeza se ele se aplica em forms também.
Pelos meus usos desses componentes eu sei que há modos de você, por exemplo, retirar as bordas de um formulário e adicionar os botões dele no lugar dos botões originais do windows, isso significa que você "mascara" a aplicação, mas no fundo o template é o mesmo, e eles tem umas documentações bem legais que dá pra você trabalhar.
Este site tem uma lista de modelos que podem alterar o skin de um form e seus controles também, porém nunca utilizei.


text:
Q: Nuget install without version number in path Is there a way to add -ExcludeVersion as default behaviour for nuget in VS 2015.

A: The -ExcludeVersion option in NuGet command line used to excludes the version number from the installation folder, which is not a default action for nuget. This is why nuget will provide this option to let users exclude the version number manually.
There has another user has the same requirement, they have submit this requirement to NuGet, you could vote and add your comments in following link for this requirement.
http://nuget.codeplex.com/workitem/1522


text:
Q: Estimating vegetation composition from digital images I am running a Master's project researching Greater prairie-chicken nest and brood survival. Some of my intended covariates include local vegetation measures using digital imagery. I would like to use remote sensing/GIS software to estimate % cover of vegetation classes (i.e. forbs, grasses, dead vegetation).
I need something that can do object-based classification; however, I attend a small university and we do not have an eCognition license, nor can we afford one. I'm in the process of seeing if UW-Madison is using it. If that is the case, I may be able to piggy-back through the UW-system. If not, is there a free trial that I could do this with? Are there any open source software packages or GIS extensions that can be used for these analyses with acceptable accuracy?
Additional Info: I have digital photos (20 mega pixel resolution) of 1 sq. m. daubenmeire frames at nest sites.

A: Yes, there are free object-oriented (segmentation) software available. A few that come to mind are Spring, ITK, Orfeo toolbox and GRASS GIS.
I would however point out that image segmentation is a poor direction to peruse when trying to model fractional cover. A segmentation algorithm is designed to minimize within unit variance and maximize between unit variance. This effectively smooths your data, which is quite undesirable when attempting to model a continuous process such as fractional cover. A regression approach would be much better suited or alternately, a binary classification of each target class where a per-unit fractional cover could be derived.

A: I have attended training in use of the Semi-Automatic Classification Plugin for QGIS. From what I could see it could be what you are looking for. The whole rig is available for free, so money should not be an issue.
Admittedly I am no expert in these tools, but the author says it includes several classification algorithms (Minimum Distance, Maximum Likelihood, Spectral Angle Mapping).
In our training we were able to train SCP and then have the system automatically produce vector layers which classified forests and open land more than well. We used modis land data.

A: Give you've got some experience in coding in Python I'd also recommend looking at the scikit-learn which has a large number of methods available for supervised, unsupervised, and semi-supervised classification, as well as regression.
If as @Jeffrey-Evans says you're looking to perform binary classification you could look at Support Vector Classification, or if you're looking at regression you could look at the corresponding regression (SVR) methods.


text:
Q: Configure Rake with --trace I wonder why rake doesn't print the backtrace by default, but I know it irritates me when I have to run a task again just to get an idea of where the error occurs.
Is there a way to configure my system (ideally system wide or else project wise) so I don't have to type the --trace?

A: I think the RAKEOPT environment variable is what you need. Check out this discussion.


text:
Q: SQL Server : check if table column exists and remove rows I'm currently writing a general SQL Server script to cleanup different databases having more/less the same table structure. This script requires that I wipe certain data from a table if that table exists in the database. here a sample of the script
IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TAB1')
  IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TAB1' AND  COLUMN_NAME = 'COL1')
    delete TAB1 where COL1 not in (select COL2 from TAB2);

As a programmer, I know that the delete command will not be executed if both condition block are false. However, when I run it in SQL it returns

Invalid column name 'COL1'.

Probably my approach is wrong. Can anyone point me to the right direction?

A: The problem is, SQL Server wants to compile the entire batch before it executes any of it.
And it can't compile the batch because there's a missing column.
So you have to make sure that the batch can compile without trying to compile the DELETE statement - so keep it as a string and force it to compile separately:
IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TAB1')
  IF EXISTS( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TAB1'
        AND  COLUMN_NAME = 'COL1')
    EXEC sp_executesql 'delete TAB1 where COL1 not in (select COL2 from TAB2);'

You said:

As a programmer, I know that the delete command will not be executed if both condition block are false.

Assuming, say, a C# background, your original query is like performing two reflection calls to determine whether a type has a particular property, and then having a line of code that directly uses that property on an object of that type - if the type doesn't have the property, the code is not going to compile, so the reflection checks never have a chance to execute.

A: Try this one -
DECLARE
       @Column SYSNAME = 'COL1'
     , @Table SYSNAME = 'dbo.TAB1'
     , @SQL NVARCHAR(MAX)

IF EXISTS (
     SELECT 1
     FROM sys.columns c
     WHERE c.[object_id] = OBJECT_ID(@Table)
          AND c.name = @Column
) BEGIN

     SELECT @SQL = '
          DELETE TAB1
          WHERE COL1 NOT IN (SELECT COL2 FROM TAB2)'

     EXEC sys.sp_executesql @SQL

END


text:
Q: Is it possible to make consoles full screen? Is it possible on to switch a console to full-screen in Windows XP on a single monitor? Meaning on a dual monitor that only the left (or right) screen displays the console while the other one remains on Windows. By full-screen I mean true-fullscreen mode, not just resizing (maximize) to fill in the screen.

A: Windows 7 (and I believe Vista) doesn't support the full-screen feature for MS-DOS or Command Prompt console. It doesn't even allow full-screen when using the Command Prompt via Windows 7's Windows XP Mode. On Windows XP, it can be set to full screen via Alt + Enter or right-clicking the console title bar and selecting Full Screen.
A possible workaround on Windows 7: With Command Prompt open, right click the console title bar, then select Properties. Within the Layout tab, you can adjust the width and height. My suggestion is: Adjust only the width to match the width of your screen. Once the adjustments are made, double click the console title bar. Using this workaround gives it the closest full-screen effect that can be achieved.

A:
Is it possible to make consoles full screen?

Why yes; yes it is, but only up to Windows XP, it is no longer supported in Vista and up. You can get basic full-screen functionality with just Alt+Enter, but for better compatibility and to resolve some issues, you can install the Full screen video driver for console:

*

*Open the Add Hardware applet in the Control Panel

*Click Next, then select Already Connected

*Select Add a new hardware device at the bottom of the list

*Choose Manually Select (Advanced)

*Select Show All Devices

*Under Manufacturer, select Microsoft Corporation

*Under Model, select Full screen video driver for console

*Next, Next, Finish (reboot if prompted)

Now you can press Alt+Enter in console windows to switch them to fullscreen mode (it displays in whichever monitor is set to the primary).

NB: this works best for the command-prompt (ie, text-mode) while graphics-mode games and such tend to have problems (eg hanging). If you want to get games working in full-screen (or at all), then you need to use various hacks to get them to work such as using the nolfb[1] and cli2nop[2] tools and VDMSound.

A: ShiftWindow : Resize an app window to get pseudo fullscreen, this will hide titlebars and window borders for msot applications, you may need to actually increase cmd.exe window width from the properties dialog first to be effective.
I haven't tested the above but this might work, good luck :)

A: Cygwin has a custom terminal that will go "true" full screen.
By default only the scrollbar on the right will be visible. You can turn those off in options if you desire, and also enable block cursor or whatever other flavor you like. It's a completely custom Terminal implementation, not a regular windows window console app.
To toggle cygwin terminal fullscreen mode simply press Alt+Enter
Incidentally the cygwin terminal also supports transparency, if you like to have your log or output in a separate terminal underneath your working terminal, like you can on most linux distros.


text:
Q: Add relative URL to related products title on WooCommerce single product page It would make a lot more sense if the related products title linked to more of the related products being displayed...
Attempting to change the related products title on the single product page to a link to the end category that correlates to the related products query being displayed.
I have the url slug and name for the end category I just can't escape the
 tag to turn it into a link. Any advice?
$translated = ' '.esc_html__(end($term_urls).'Continue Browising '.end($term_names), $domain);
add_filter('gettext', 'change_rp_text', 10, 3);
add_filter('ngettext', 'change_rp_text', 10, 3);

function change_rp_text($translated, $text, $domain)
{
global $woocommerce, $post;

 if ($text === 'Related products' && $domain === 'woocommerce') {

 $term_names = wp_get_post_terms( $post->ID, 'product_cat', array('fields' => 'names') );
        $term_urls = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'slugs') );

     $translated = ' '.esc_html__(end($term_urls).'Continue Browising '.end($term_names), $domain);

 }
 return $translated;

 }

A: Normally you could use the woocommerce_product_related_products_heading filter hook, which allows you to change $heading. But $heading is passed via esc_html()
so you can't add HTML to the output.
Therefore you will have to overwrite the /single-product/related.php file

This template can be overridden by copying it to yourtheme/woocommerce/single-product/related.php.

Replace line 29 - 32  @version 3.9.0
if ( $heading ) :
    ?>

<?php echo esc_html( $heading ); ?>

<?php endif; ?>

With
if ( $heading ) {
    global $product;

    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get terms
        $terms = wp_get_post_terms( $product->get_id(), 'product_cat' );
        $end = end( $terms );

        // URL
        echo 'term_id, 'product_cat' ) . '">' . $end->name . '';
    }
}
?>

A: This appears to work with out having to copy and modify the
/single-product/related.php file. It could be more efficient by using an alternative method.
Using get_term_link( from the answer @7uc1f3r provided
add_filter('gettext', 'change_rp_text', 10, 3);
add_filter('ngettext', 'change_rp_text', 10, 3);

function change_rp_text($translated, $text, $domain)
{
global $woocommerce, $post;

 if ($text === 'Related products' && $domain === 'woocommerce') {

        $term_names = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'names') );
        $term_urls = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'slugs') );
        $term_ids = wp_get_post_terms( $post->ID, 'product_cat',
            array('fields' => 'ids') );

     $last_term_id = end($term_ids);

     $translated = _e('
More ' . end($term_names) . '
', $domain);

 }
 return $translated;

}


text:
Q: whole array printing instead of a single value within it I need to be able to read in a word from a file one at a time and then be able to sort the text into a struct to track how many times words have been repeated however whenever I try to point to a specific word in the file I'm getting the whole file value instead of the specific word I'm trying to retrieve. apologies if the solution is simple, I still struggle with the different types of pointers and file commands
#include <stdlib.h>
#include <stdio.h>

char *inputFilename;
char *outputFilename;

char inputText[5000];
char outputText[5000];

int inputFlag;
int outputFlag;

int readfile(char **data){

    FILE *input;
    input = fopen(inputFilename, "rb");
    int len = sizeof(*input);

    printf("input length is %d\n", sizeof(char));

    //First value is number of integers
    int size;
    fread(&size, sizeof(char), 0, input);

    //allocate memory for that number of values
    *data = (char*)malloc(sizeof(char) * size);

    //Read in rest of data
    fread(*data, sizeof(char), size, input);

    //return size
    printf("size is %d\n", size);
    return size;
}

int valueSearch(char *vData, int argCount, char **argv){

    for(int argLoop = 0; argLoop < argCount; argLoop++){

        //If vData is detected then the next argument is the input file name
        if(strcmp(argv[argLoop], vData) == 0){

            return argLoop + 1;

        }
    }
    return 0;
}

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

    char *data;

    inputFlag = valueSearch("-i", argc, argv);

    printf("input flag is %d\n", inputFlag);

    inputFilename = argv[inputFlag];

    if(inputFlag == 0){

        printf("Please enter the text you would like to sort: ");

        fgets(inputText, 5000, stdin);

    }
    else{

        int size = readfile(&data);

    }

    int i = 0;

    //Value that should be placed into struct
    printf("readfile value 0:\n%s\n", data[i]);

    free(data);

    return 0;

}

A: Your last printf uses %s instead of %c. %s treats the argument as a pointer to a string (char array), and prints each byte until it encounters a byte of 0. You want %c, which prints out a single char.

A: Use %c instead of %s because %s is a identifier of string and that will print whole string.
 printf("readfile value 0:\n%c\n", data[i]);

Hopefully it will work for you.

A: You need to become familiar with compiling with compiler warnings enabled, and then do not accept code until it compiles without warning or error.
You invoke Undefined Behavior on line 19 and again on line 76 by using improper conversion specifiers for int (instead of long int - line 19) and again as already noted on line 76 where you use %s instead of %c.
Further, you do not include string.h which is required for the use of strcmp on line 41. There is no declaration for strcmp so your compiler makes a guess at an implicit declaration.
You will also find unused variables len and size in your code. (lines 17 and 69, respectively).
All of these problems are readily apparent from your compiler output if you compile with -Wall -Wextra (and if wanted -pedantic) on gcc, with -Weverything on clang, or /Wall with VS (cl.exe) (you may want /W3 on VS as /Wall means all (and you will have to individually disable a handful of warning there with /wdXXXX where XXXX is the code for the warning you wish to disable).
While not an error, the standard coding style for C avoids the use of camelCase or MixedCase variable names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you, but failing to follow it can lead to the wrong first impression in some circles.
Moral of the story -- (1) enable compiler warnings, and (2) do not accept code until it compiles cleanly -- without warning. Letting your compiler help you write better code will eliminate a large percentage of the errors you spend time chasing :)


text:
Q: Dart: best type to store currency In Java currency is usually stored in BigDecimal. But what to use to store currency values in Dart? BigInt doesn't seem to be a solution because it is for integer values only.

A: Definitely do not use doubles for an accounting application.  Binary floating point numbers inherently cannot represent exact decimal values, which can lead to inaccurate calculations for seemingly trivial operations.  Even though the errors will be small, they can eventually accumulate into larger errors.  Setting decimal precision on binary numbers doesn't really make sense.
For currency, you instead either should something intended to store decimal values (e.g. package:decimal) or should use fixed-point arithmetic to store cents (or whatever the smallest amount of currency is that you want to track).  For example, instead of using doubles to store values such as $1.23, use ints to store amounts in the smallest unit of currency (e.g. 123 cents).  Then you can use helper classes to format the amounts wherever they're displayed.  For example:
class Money {
   int cents;

   Money({required this.cents});

   @override
   String toString() => (cents / 100).toStringAsFixed(2);

   Money operator +(Money other) => Money(cents: cents + other.cents);

   // Add other operations as desired.
}


text:
Q: Pragma Solidity Error Unused Local Variable uint256 testVar = 5; | What's wrong? I would like to know what's wrong with the code below. I can validate the transactions, but I keep receiving the error "Unused Local Variable "
// SPDX-License-Identifier: MIT
pragma solidity 0.8.8;

contract SimpleStorage {
    //boolean (True False),uint(>0), int(><=0), address, bytes
    bool HasFavoriteNumber = true;
    uint256 public FavoriteNumber;

    function store(uint256 _FavoriteNumber) public {
        FavoriteNumber = _FavoriteNumber;
        uint256 testVar = 5;
    }

    function retrieve() public view returns(uint256){
        return FavoriteNumber;
    }
}

enter image description here

A: It's just a warning you can just ignore it. It is giving you this warning because it is a local variable, i.e the scope of this variable is only inside this function, every time you are calling this function, it is assigning 5 to the variable but it is not stored anywhere. But it you for suppose to make it global and then assign the value to it it will run fine. However, assigning 5 every time to it will be useless so just for the sake of it I am incrementing 5 every time the function is called.
pragma solidity 0.8.8;

contract SimpleStorage {
    //boolean (True False),uint(>0), int(><=0), address, bytes
    bool HasFavoriteNumber = true;
    uint256 public FavoriteNumber;
    uint256 public testVar;

    function store(uint256 _FavoriteNumber) public {
        FavoriteNumber = _FavoriteNumber;
        testVar += 5;
    }

    function retrieve() public view returns(uint256){
        return FavoriteNumber;
    }


text:
Q: Purrr package add species names to each output name in SSDM I have a list of species and I am running an ensemble SDM modelling function on the datset filtering by each species, to give an ensemble SDM per species from the dataset.
I have used purrr package to get it running, and the code works fine when there is no naming convention added in. However, when it outputs the Ensemble.SDM for each species, they are all named the same thing "ensemble.sdm", so when I want to stack them, I cannot as they are all named the same thing.
I would like to be able to name each output of the model something different, ideally linked to the species name picked out in the line: data <- Occ_full %>% filter(NAME == .x)
The working code is written below:
list_of_species <- unique(unlist(Occ_full$NAME))

# Return unique values

output <- purrr::map(limit_list_of_species, ~ {
  data <- Occ_full %>% filter(NAME == .x)
  ensemble_modelling(c('GAM'), data, Env_Vars,
            Xcol = 'LONGITUDE', Ycol = 'LATITUDE', rep = 1)
})

The code I have tried to get it named within it, is below, but it does not work, it names it with lots of repeitions of the row number.
output <- purrr::map(limit_list_of_species, ~ {
  data <- Occ_full %>% filter(NAME == .x)
  label <- as.character(data)
  ensemble_modelling(c('GAM'), data, Env_Vars,
            Xcol = 'LONGITUDE', Ycol = 'LATITUDE', rep = 1,  name = label )
})

Could anyone help me please? I simply want each "output" to be named with the species name specified in the filter. Thank you

A: Try using split with imap -
list_of_species <- split(Occ_full, Occ_full$NAME)

output <- purrr::imap(list_of_species,~{
  ensemble_modelling(c('GAM'), .x, Env_Vars,Xcol = 'LONGITUDE',
                     Ycol = 'LATITUDE', rep = 1, name = .y)
})

split would ensure that the list_of_species is named which can be used in imap.


text: Q: Работа библиотеки QuadFlask.colorPicker в активности вместо диалогового окна Нашел подходящую для меня библиотеку, но представленный код выводит диалоговое окно, как мне изменить его, чтобы всё работало просто в activity?


text:
Q: Maven Include Dependency in Shaded Jar Only I'd like to use maven shade to create a shaded jar, but I'd also like to include a special dependency only in the case of the shaded jar (not in the normal compile dependencies of my project). How can I go about this?
From my understanding the includes/excludes are only whitelists/blacklists so I can't explicitly force something to get included that wasn't included in the actual dependency list.
For more context, I have a JAR dependency which contains a resource that I only want included in one of my shade artifacts, but having that jar on the classpath otherwise would cause errors.
To be clear, I'm looking to generate both a shaded jar, with an additional dependency and a normal jar without it, in one mvn package call.

A: Try using a profile, and having your dependency and shade only in that profile. For example:
<profiles>
    <profile>
        <id>shadeProfile</id>
        <dependencies>
            <dependency>
                <groupId>com.example</groupId>
                <artifactId>some-artifact</artifactId>
                <version>1.23</version>
            </dependency>
        </dependencies>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-shade-plugin</artifactId>
                    <version>2.3</version>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>shade</goal>
                            </goals>
                            <configuration>
                                <shadedClassifierName>shaded</shadedClassifierName>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Now, when you run mvn -PshadeProfile package it will include the artifact as part of your shaded build, and use the classifier shaded for the new artifact. This way your build can produce your unshaded JAR without the problematic resource, and a shaded JAR with that resource, simply by turning on the profile.
Other projects which depend on this can either depend on the shaded or unshaded artifact, as appropriate, since you are using a classifier to generate both.


text:
Q: Can we use ojdbc14.jar with Oracel11g and jdk1.5 I believe there are different flavors of this questions already asked, but I wanted to confirm this again as we are very close to our release and wanted to validate with the community
We have been using Oracle10g and java 1.5 for quite some time now with ojdbc14.jar. I know that ojbc14.jar is catered towards java 1.4. But thankfully we never saw any issue while using this with 1.5 version. Another reason for not moving to ojbc5 was the fact that we did not see ojdbc5.jar in the installed oracle 10g at all.
We have upgraded our DB to be 11g now and I did not see ojdbc14.jar. Does this mean we have to move to ojdbc5.jar?
We are willing to make the change. But can the people who made the switch confirm if they saw any issue when they changed the JDBC driver to ojdbc5.jar from ojdbc14.jar
Related to it, it would be good if someone can elaborate little more about dms flavors of this jar and how it is to be used.

A: Below are the suggestions from Oracle :

the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.
If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

A: Take a look at Oracle's JDBC drivers list. For 11g and 11g2, only ojdbc5.jar and ojdbc6.jar are listed. This could mean that only they are officially supported, so if you have problems with ojdbc14.jar, Oracle probably won't help you.
If Oracle's support is important for your management, I'd recommend upgrading to ojdbc5.jar.

A: ojbc14 should work just fine with Oracle11g. The primary differences between ojbc14 and later versions is the later version support newer versions of the JDBC API, as well as new features of the newer versions of oracle.
If your application gets along with ojbc14 as it is, there's little reason to upgrade the driver, other than the fact that it's always a good idea to try and track new revisions as they come along, to keep your system current.


text:
Q: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b I have a dictionary which maps XY tuples to RGB tuples. For example,
d = {
    (0, 0): (0, 0, 0),
    (0, 1): (0, 0, 200),
    }

I wish to plot some sort of heatmap, which, at a given XY coordinate, will have color which is the average of the colors in the dict, weighted by their reciprocal distances; as if they were "sources of light" or so.
In the given example, the coordinate (0, 0.5) should be colored with (0, 0, 100) and the coordinate (0, 0.1) should be colored with (0, 0, 20).
My question is rather technical: how do I let pyplot plot a pixel image with colors retrieved from a function f(x, y) -> (r, g, b)?

A: If you have your X-Y grid:
import numpy
from matplotlib import pyplot as plt

width, height = 300, 500

xs = numpy.arange(width)
ys = numpy.arange(height)
data = numpy.dstack(numpy.meshgrid(xs, ys))

You should just map these to (r, g, b) tuples. The following is pretty slow, but how to speed it up depends on what your function does.
from colorsys import hsv_to_rgb

import random
def data_to_color(x, y):
    return (
        (x/width)**(0.5+random.random()*2),
        (y/height)**3,
        (x/width*y/height)*0.6 + random.random()*0.4
    )

colors = [[data_to_color(x, y) for x, y in row] for row in data]
colors = numpy.array(colors)
colors.shape
#>>> (500, 300, 3)

Then imshow can give the wanted output:
plt.imshow(colors, origin='lower')
plt.show()

Now, if you want to interpolate from your points as you say, you can use scipy.interpolate. I'll make a dictionary to extrapolate from the function above:
from scipy.interpolate import griddata

gridpoints = data.reshape(width*height, 2)
d = {(x, y): data_to_color(x, y) for x, y in gridpoints if not random.randint(0, 1000)}

len(d)
#>>> 142

Extract the dictionary into numpy arrays, and separate the colours (it might be possible to avoid the separation, but you can test that yourself):
points, values = zip(*d.items())

points = numpy.array(points)
values = numpy.array(values)

reds   = values[:, 0]
greens = values[:, 1]
blues  = values[:, 2]

Then run griddata on the points:
new_reds   = griddata(points, reds,   (data[:, :, 0], data[:, :, 1]), method='linear')
new_greens = griddata(points, greens, (data[:, :, 0], data[:, :, 1]), method='linear')
new_blues  = griddata(points, blues,  (data[:, :, 0], data[:, :, 1]), method='linear')

new_colors = numpy.dstack([new_reds, new_greens, new_blues])
new_colors[numpy.isnan(new_colors)] = 0.5

And plot:
plt.triplot(points[:,0], points[:,1], 'k-', linewidth=1, alpha=0.5)

plt.imshow(new_colors, extent=(0, width, 0, height), origin='lower')
plt.show()

And, finally, if you want extrapolation too, I copied some code from here:
import scipy

def extrapolate_nans(x, y, v):
    '''
    Extrapolate the NaNs or masked values in a grid INPLACE using nearest
    value.

    .. warning:: Replaces the NaN or masked values of the original array!

    Parameters:

    * x, y : 1D arrays
        Arrays with the x and y coordinates of the data points.
    * v : 1D array
        Array with the scalar value assigned to the data points.

    Returns:

    * v : 1D array
        The array with NaNs or masked values extrapolated.
    '''

    if numpy.ma.is_masked(v):
        nans = v.mask
    else:
        nans = numpy.isnan(v)
    notnans = numpy.logical_not(nans)
    v[nans] = scipy.interpolate.griddata((x[notnans], y[notnans]), v[notnans],
        (x[nans], y[nans]), method='nearest').ravel()
    return v

new_reds   = extrapolate_nans(data[:, :, 0], data[:, :, 1], new_reds)
new_greens = extrapolate_nans(data[:, :, 0], data[:, :, 1], new_greens)
new_blues  = extrapolate_nans(data[:, :, 0], data[:, :, 1], new_blues)

new_colors = numpy.dstack([new_reds, new_greens, new_blues])

plt.imshow(new_colors, extent=(0, width, 0, height), origin='lower')
plt.show()

EDIT: Maybe something more like
import numpy
from matplotlib import pyplot as plt
from numpy.core.umath_tests import inner1d

width, height = 300, 500

xs, ys = numpy.mgrid[:width, :height]
coordinates = numpy.dstack([xs, ys])

light_sources = {
    (0, 0): (0, 0, 0),
    (300, 0): (0, 0, 0),
    (0, 0): (0, 0, 0),
    (300, 500): (0, 0, 0),
    (100, 0): (0, 0, 200),
    (200, 150): (100, 70, 0),
    (220, 400): (255, 255, 255),
    (80, 220): (255, 0, 0),
}

weights = numpy.zeros([width, height])
values = numpy.zeros([width, height, 3])

For each light source:
for coordinate, value in light_sources.items():

Compute the (inverse) distances. Use +1e9 to prevent infinities, although this will have silly failures so a more rigorous fix would be important later:
    shifted_coordinates = coordinates - coordinate + 1e-9
    inverse_distances = (shifted_coordinates ** 2).sum(axis=-1) ** (-1/2)

Add it to the sum and the sum weighting:
    weights += inverse_distances
    values  += inverse_distances[:, :, numpy.newaxis].repeat(3, axis=-1) * value / 255

Divide by the weighting to have the average:
values /= weights[..., numpy.newaxis]

And show...
plt.imshow(values, origin='lower')
plt.show()

For this:

The reason I didn't go for this originally is because the value at (0, 0.1) in your example is not (0, 0, 20) but:
distances = [0.9, 0.1]
inverse_distances = [10/9, 10]
sum_weighting = 100 / 9
blue_levels = 200 / (109/90) = 18

so it should be (0, 0, 18) by this definition.


text:
Q: android.permission.DEVICE_POWER error When I did some job on android widget of setting, I got this error:

java.lang.SecurityException: Neither user 10097 nor current process has android.permission.DEVICE_POWER.

I have pushed the widget apk to the system/app.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fly.widget.setting02"
android:versionCode="1"
android:versionName="1.0">

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIMAX_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIMAX_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY"/>
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" />
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.SET_KEYBOARD_LAYOUT" />
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.MANAGE_USERS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.CONFIGURE_WIFI_DISPLAY" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
<uses-permission android:name="android.permission.DEVICE_POWER"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <receiver android:name=".SetProvider" >
        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/appwidget_provider"
            android:enabled="@bool/has_powercontrol_widget"/>
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
           <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
            <action android:name="android.appwidget.action.APPWIDGET_DISABLED" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            <action android:name="android.net.conn.BACKGROUND_DATA_SETTING_CHANGED" />
            <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
            <action android:name="android.location.PROVIDERS_CHANGED" />
            <action android:name="com.android.sync.SYNC_CONN_STATUS_CHANGED" />
        </intent-filter>
    </receiver>
</application>

A: The DEVICE_POWER permission is not accessable by third-party applications like yours.
public static final String DEVICE_POWER
Added in API level 1

Allows low-level access to power management.

Not for use by third-party applications.
Constant Value: "android.permission.DEVICE_POWER"


text:
Q: Add some content after user login Good day.
I created rest api with node.js and strongloop.
Also there is app based on angular.js.
When user login, server send accessToken and it store in cookies.
Every request i send accessToken, and it checks.
So, what is the better way to add some content to Single page app after user login and hide when logout.
Also i created form in angular modal dialog.

A: If you need to disable some views, accessible by link, like profile view, you could use ui router, create login state and state(s), that can be shown only for logged user using resolve option. Please review this example, loginRequired function usage. You are not required to use satellizer (but you could, this lib is really awesome).
If you need to just hide some partial or html snippet, like a "logout" button you can use ng-if="isAuthenticated()".
Hope it helped.


text:
Q: Additional GetXYZ methods in EntitySetController I want to be able to have additional GetXYZ methods in my EntitySetController derived controller class.  For example:
[HttpGet]
 [Queryable]
        public string GetAirportsWithinRadius(int airportId, int radius)
        {

            var resultAirports = GetAirportsWithinRadius2(airportId, radius);

            return resultAirports;
        }

This is what I have for config:
ActionConfiguration getAirportsWithinRadius =  modelBuilder.Entity<Airport>().Collection.Action("GetAirportsWithinRadius");
        getAirportsWithinRadius.Parameter<int>("airportId");
        getAirportsWithinRadius.Parameter<int>("radius");
        getAirportsWithinRadius.ReturnsCollectionFromEntitySet<Airport>("Airports");

I want this action to be composable just like the default Get Queryable action, but this would be an alternative that supports all odata parameters but additionally an airportId and radius.  This would first filter airports by a radius search (this I know how to do - it's irrelevant to the question) and then return the Queryable so that it can be further filtered by odata params.
Everything I read says this would be an odata action and therefore must be a POST, but Get is also an action and that is a GET, so why not allow extended getters with additional parameters?  Am I missing something?  How do I accomplish what I want to get done?
I would call this from an ajax client as such:
GET /odata/Airports?$inlinecount=allpages&$top=25&airportId=2112&radius=50
as opposed to a regular odata GET:
GET /odata/Airports?$inlinecount=allpages&$top=25
Thanks
EDIT:
I understand now that this is an odata "function" and it is under consideration as a future feature.  Let's forget for second the odata meaning of this.  It is essentially a WebApi HttpGet that returns a Queryable, right?  So, as long as I don't care about the metadata advertising of this "function", how can I make sure that it is a reachable HttpGet form a route perspective inside of an ODataController?  The ODataController needs the MapODataRoute and can I additionally add non odata routes using additional MapHttpRoutes?
I ask this because it seems to me that I should be able to, but all my tries have failed (trying to hit the HttpGet through fiddler).  I can find no examples on extending an ODataController with additional non-odata GETs.  Can someone help me understand if and how this can be done with the example?:
[Queryable]
        public IQueryable<Airport> Get()
        {
            return db.Airports;
        }
    [HttpGet]
     [Queryable]
            public string GetAirportsWithinRadius(int airportId, int radius)
            {

                var resultAirports = GetAirportsWithinRadius2(airportId, radius);

                return resultAirports;
            }

A: You are looking for OData Functions, which is not yet supported out of the box. We have an issue over here. You can up-vote it.
http://aspnetwebstack.codeplex.com/workitem/881


text:
Q: Both box shadow and linear gradient conflict I am having a problem with creating a linear gradient and box shadow for a button. The problem is gradient works for cross broswers but box shadow does not(inset is not needed). Mainly i needed it for ie8.
My requirement is to write css for a single class(like .submit) with supporting linear gradient and box-shadow for all the browsers.

A: You can apply shadow using this example.
.shadow{
     filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=3,MakeShadow=true,ShadowOpacity=0.30);
     -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=3,MakeShadow=true,ShadowOpacity=0.30)";
     zoom: 1;
}

you can make your own variations here at css3 pie

A: Take a look at shadow filter.
This would add a shadow on each side of an element:
.boxshadow {
        zoom: 1;
        filter: progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=0, Strength=3)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=45, Strength=2)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=90, Strength=3)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=135, Strength=2)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=180, Strength=3)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=225, Strength=2)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=260, Strength=3)
        progid:DXImageTransform.Microsoft.Shadow(color='#999999', Direction=305, Strength=2);
}

Should work in IE down to Version 6.


text:
Q: Hard disk much slower when performing several long simultaneous reads Summary

*

*From a traditional (spinning platters) hard disk

*read one big file, get good performance

*read another big file simultaneously, get total throughput divided by 5 to 10. Quite a performance drop!

Plus the disk head mechanically moving back and forth several times per second can be heard and felt with the hand.  Also after a few hours temperature was observed to be higher.
If this happens rarely or for a short amount of time, that's ok.  If this is often or for an extended period of time, not only performance is bad and it announces shorter lifespan.
Example

*

*Disk: a 2 terabyte Western Digital disk.

*Throughput when reading one big file can be 50-100MB/s.

*Effect most extreme with big files: video files (example 1GB to 13GB in size).  Also happens when reading raw photo (~25MB) files.

*As soon as another program reads another file simultaneously, total throughput drops to 5-10MB/s.

Additional information
It's not a matter of file fragmentation.  If files were fragmented, throughput would be slow (much slower than nominal 50-100MB/s) even when reading only one file.
Question
Can something be done to get total throughput reasonably high when reading several big files simultaneously?

A: Quick answer

*

*(1) Figure out what is the correct block device (for example with mount).

*(2) Get root permission.

*(3) Tune read_ahead_kb for the device.

In my case, issuing this command:
echo 100000 > /sys/block/sdb/queue/read_ahead_kb

brought back performance and mechanical relief in a matter of seconds.
What does this parameter change mean concretely?
TL;DR: it causes the kernel to read big files in one go, which means only one back-and-forth mechanical motion instead of many, solving the problem.
More precisely, this parameter tells the kernel that when it opens a file, you allow it to read in advance a lot of data (in this case, up to 100MB, from the default 128kB) even before knowing if the process requesting the read will actually need that much data.  As a result, with an example of a process opening a 30MB file (typical raw photo) while another process already reads as much as possible other file(s), then instead of having the mechanical head move back and forth at least (30000/128)=234 times guaranteed, the kernel knows you allow it to possibly read all the file at once, making just one back-and-forth mechanical motion.
The downside is, if you only need part of the file (e.g. a 100kB thumbnail from a 30MB file), the kernel might (or might decide to not) read too much data.  Also, the data being read will occupy some RAM pages which increases memory pressure.  Linux being made for general purpose, including servers with lot of parallel activity and memory pressure, it certainly has a number of heuristics to guess what to do.  The truth is in the kernel source code.
Why this value?
Default value is 128.  I observed some effect increasing it to other values first, like 4096, and got satisfied at 100000, but I guess (1) most of the effect is obtained with initial increase, (2) most ill-effects (if any depending on the situation, like memory pressure) are proportional to the value and (3) there might be some value above which increasing does not actually change anything.
But what about your situation?
Details

*

*Official documentation on https://www.kernel.org/doc/Documentation/block/queue-sysfs.txt https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-bdi is very short: "Maximum number of kilobytes to read-ahead for filesystems on this block
device."

*RedHat documentation 6.4.3. Noop explains a bit more, with hints about when increasing might or might not be a good idea (hint: memory pressure).  So it looks like this parameter is used by the Noop IO scheduler.

*storage - Linux - real-world hardware RAID controller tuning (scsi and cciss) - Server Fault has hints about cases (streaming video, database access) and how to make an educated guess.
Also, parameter can be set not only through /sys tree but also using blockdev command.
Or you might as well use the source, luke:

*

*https://github.com/torvalds/linux/search?q=read_ahead_kb

*https://github.com/torvalds/linux/search?q=read-ahead

*https://github.com/torvalds/linux/search?q=ra_pages

A: Spoiler: There will be a YES answer at the bottom of the post
Short answer:
NO.
Medium-sized answer:
NO, because
there are 2 processes that want to access one ressource (the hard disk) at the same time. Each process will read different data, so the head needs to jump to the place where the process needs data from the platter. This jumps take a lot of time and decrease the total throughput of your hard-disk a lot!
Long answer,
because you seem to lack some (basic) understanding of the working principle of a hard disk:
NO, because
your spinning platters hard drive behaves like a book.
Imagine that you have a book with only empty pages. That's your hard disk when you buy it. No data stored on it.
Then you put it into your computer (let's say as a 2nd drive, so we don't have to deal with the operating system here).
When you write a long text document (called 'text A') and save it on the disk, then it's like writing the first 10 pages (pages 1 to 10) in your book. Then you copy a jpg picture onto the disk, that's like make a drawing of your house on the next 5 free pages in your book (p. 11-15).
The table of content of your book now has 2 entries:

*

*text A: p. 1-10

*pic of house: p. 11-15

All data on your hard disk can be erased again, that's why you have written and drawn everything with a pencil, and not a ball-pen.
Now you write a shopping list into your book: p. 16-17.
Next, you don't like or need that drawing any more and want to erase it, so you remove it with a rubber. Pages 11-15 are blank.
Your TOC looks like:

*

*text A: p. 1-10

*shopping list: p. 16-17

Now you want to draw an image of the local supermarket, which is bigger than your house. So you need 12 pages. You could start at page 11, which means you'd have not enough consecutive pages and you need to continue at 18, or you could start at 18 and have enough space to draw it in one go.
Most or all operating systems are smart enough to choose a chunk of free space that is large enough for the whole data, but if there is no sufficiently large free space, it will have to divide the file into smaller pieces that fit into the existing free areas. This is called Fragmentation.
Let's imagine you also need to do that. Your TOC looks like:

*

*text A: p. 1-10

*pic of supermarket, fragment 1 of 2: p. 11-15

*shopping list: p. 16-17

*pic of supermarket, fragment 2 of 2: p. 18-24

Now we start READING the book.
You want to know the items on your shopping list. The TOC tells you to go to page 16. You start reading until you reach the bottom of p.17. Done.
Next: you want to see how the supermarket looks like where you want to go shopping. The TOC tells you to go to p.11 (you are on p.18 (= end of p.17) and have to browse 7 pages back. On a hard disk the read-write head needs to do a jump. Then you start reading until you reach end of p.15, then you browse to p.18 (head jumps again) and continue.
Browsing in a book takes less time than reading, but on a hard-disk it's almost the other way round. The head cannot just move to the next track/cylinder, but has to 'search' the correct cylinder (acceleration, motion, deceleration, settling time). See Wikipedia. So due to fragmentation your reading takes longer than if the file was stored consecutively.
And now, we do READING WITH 2 PEOPLE:
You want to see the supermarket image and I want to read your text A.
You browse to page 11 and start reading.
When you have read p.11, I browse to p.1 and start reading.
When I have read. p.1, you browse to p.12 and continue reading.
When you have read. p.12, I browse to p.2 and continue reading.
...
you can imagine that it takes a lot longer to read the pages just because the many browsing takes so long.
Same with your hard-disk. You can't do nothing about it but avoiding simultaneous access as this always makes it slower.
Now, finally, the YES answer:
YES:  Buy a SSD.
This is a electronic disk and it operates like RAM, so you have almost no seek times and the total throughput is always close to the maximum possible throughput (if there are no other bottlenecks elsewhere).


text:
Q: Why does this result happen playerlevel = 1
playerattack = 10
playerhealth = 100
playerexp = 0

print (playerlevel)
answer = input('have you played before? yes or no: ')
if answer == 'yes':
    level = input('what was your level: ')
    playerlevel *= level
    playerattack *= level
playerhealth *= level
else:
    pass

print ("player level: %s" % playerlevel)
print ("player health: %s" % playerhealth)
print ("player attack: %s" % playerattack)
print ("player exp: %s" % playerexp)

when i run this program it runs player level fine if level is 2 it prints 2 but the others it prints -> 2222222222222222222222222222222 for each. for exp its 0

A: level = input('what was your level: ')

input returns a string*. When you multiply a string by an integer, you get the string repeated that many times. For example, "2" * 3 is "222".
If you want actual numerical multiplication, convert level to an integer before using it.
level = int(input('what was your level: '))

*Applicable only in Python 3.X. input can return other types in 2.7 and below, but you should use raw_input instead in those versions.


text:
Q: C/C++ Code coverage fails to generate gcda files I am trying to run the code coverage on a C/C++ software.
The generation of gcno files is fine (I have more than 6000 of them) while I only get 240 gcda files.
I am running Mac OS X 10.9.3 with Xcode 5.5.1.
Building with:
export CFLAGS="-fprofile-arcs -ftest-coverage"
export CXXFLAGS="-fprofile-arcs -ftest-coverage"
export LDFLAGS="-fprofile-arcs -ftest-coverage --coverage"

I saw a potential solution with gcov_flush():
Generate gcda-files with Xcode5, iOS7 simulator and XCTest
but I don't want to touch the sources of the software or the tests (and I would like to avoid Objective-C). Any clue?


text:
Q: UnsatisfiedLinkError when enabling JProfiler on armhf I am trying to start a JProfiler agent in a docker container running on a Raspberry PI 3. Here is the complete Dockerfile.
FROM balenalib/raspberrypi3-openjdk

RUN ["cross-build-start"]
RUN curl -SL http://download-keycdn.ej-technologies.com/jprofiler/jprofiler_linux_11_0.tar.gz | tar -xz -C /usr/local && \
  echo 'sudo -u root /usr/local/jprofiler11.0/bin/jpenable -g -p 8849' > /jprofile.sh && \
  chmod +x /jprofile.sh
RUN [ "cross-build-end" ]

ENV JPAGENT_PATH="-agentpath:/usr/local/jprofiler11.0/bin/linux-armhf/libjprofilerti.so=nowait"
ENV JAVA_OPTS=""
EXPOSE 8849

ADD build/libs/myproject-0.0.1-SNAPSHOT.jar /app.jar

ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar

For profiling, run:
docker exec -it mycontainer /bin/bash -c "/jprofile.sh"

Here is the complete output:
Connecting to app.jar [1] ... ERROR: The agent could not be loaded: Exception in thread "main" java.lang.UnsatisfiedLinkError: sun.tools.attach.LinuxVirtualMachine.isLinuxThreads()Z
        at sun.tools.attach.LinuxVirtualMachine.isLinuxThreads(Native Method)
        at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:343)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:195)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at com.jprofiler.attach.proxy.a.e$b.invoke(ejt:110)
        at com.sun.proxy.$Proxy0.attach(Unknown Source)
        at com.jprofiler.attach.a.main(ejt:119)

It seems like the native library loads fine when I call System.loadLibrary("attach") from jshell. Any ideas what could be causing this exception?

A: Solved via support@ej-technologies.com - if you place the correct file in lib/libattach.so, you can add the following snippet to the Dockerfile to make it work.
Offical support for armhf is scheduled to release with 11.0.1.
# ...
# Add ARMHF remote attach library (acquired via EJ Technologies support)
# See https://stackoverflow.com/questions/56307915/unsatisfiedlinkerror-when-enabling-jprofiler-on-armhf
ADD lib/libattach.so /usr/local/jprofiler11.0/bin/linux-armhf/
RUN chmod a+x /usr/local/jprofiler11.0/bin/linux-armhf/libattach.so

RUN [ "cross-build-end" ]

Special thanks to Ingo Kegel!


text:
Q: System Random Hard Freeze. Are my CPU's pins bent? I've just upgraded RAM and CPU in my MSI-G31 P21(MS-7529) motherboard to 2X2GB DDR2(800Mhz) and CPU - Core 2 Duo 3.14Ghz 2 Core.
Before upgrading, my PC used to randomly hard freeze. I thought if I upgrade my problem will be gone. But the problem persisted even that sometimes playing games, watching movies, typing in notepad and even while booting up.
Here's what I've done so far:

*

*Updated BIOS

*Updated all drivers

*Did HDD and RAM test (No problem found)

*Checked CPU temp: it stays around 57-60°C

*Ambient temperature stays around : 36-37°C

*My PSU - 200W on 12V it gives 20A

*My CPU fan stays around 1700-1900 RPM. Sometimes,  it stays on 2000RPM.

*Reinstall of Windows

None of these worked.
Here's my CPU socket pins image. I doubt that the CPU pins are bent. Look at the image and tell me, please.


text:
Q: Promises angularjs Tengo el siguiente método
$scope.export= function() {
    var promises = [];
    var result = 0;

    promises.push(TestService.getValue1());
    promises.push(TestService.getValue2());

    $q.all(promises).then(function(res) {
        res.forEach(function(a, index) {
            result = result + a
        })
    });
}

Me gustaria llamar a: TestService.getValue3(result); => este método hace muchas cosas y tarda en devolver uan respuesta, he probado lo siguiente:
    $q.all(promises).then(function(res) {
        res.forEach(function(a, index, array) {
            result = result + a
            if (index === array.length - 1){
                  promises.push(TestService.getValue3(result));
            }
        })
    });

Otra forma que he probado
    $q.all(promises).then(function(res) {
        res.forEach(function(a, index, array) {
            result = result + a
        })
    }).finally{
        var total = TestService.getValue3(result)
        console.log(total); => aqui me muestra undefined
    };

Error en ambos casos:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

Si llamo asi a ese metodo funciona, solo que cuando esta dentro de un $q.all tengo ese problema:
$scope.export= function() {
    var promises = [];
    promises.push(TestService.getValue3(100));

    $q.all(promises).then(function(res) {
        res.forEach(function(a, index) {
            console.log(a)
        })
    });
}


text:
Q: change screen resolution without clicking resolution on desktop or using graphics card settings How can I change screen resolution without using Explorer.exe or my graphics card settings.
Both crash every time I try.

A: More than likely, you have a bad/incorrect driver installed.  However, here is a program that will let you change resolutions quickly.


text:
Q: Insert value of more than 32k chars into long column in oracle I have a table with a column type of LONG. I know I could solve my problem by changing the column type to CLOB but I don't have that option in this case. I need to insert a value of more than 32k characters into this column.
Say i have a table called test with column named c1 of type LONG.
The following statement will produce error.
insert into test(c1)values('string longer than 32k chars');

error:ORA-01704: string literal too long.

Thanks in advance for any help.
Using tony's example from below I want to do something like the following:
declare
   x varchar2(40000) := rpad('x',40000,'x');
begin
   insert into test (c1) values (x);
end;

I know you can't make varchar(2) that big but i want to exercise the idea.

A: You can insert 32K characters from PL/SQL:
declare
   x varchar2(32767) := rpad('x',32767,'x');
begin
   insert into test (c1) values (x);
end;


text:
Q: How to fill names with NA based on a different column How can I fill the second column with NaN if the first column has NaN?
I tried this
df1.type2.fillna(value=df1.type1, inplace=True)

input
,type1,type2
2020-01-02 6:00,NaN,ABC
2020-01-02 12:00,NaN,DEF
2020-01-02 18:00,60,GHI

output
,type1,type2
2020-01-02 6:00,NaN,NaN
2020-01-02 12:00,NaN,NaN
2020-01-02 18:00,60,GHI

A: Use DataFrame.loc with Series.isna:
df.loc[df.type1.isna(), 'type2'] = np.nan

Or Series.mask with default value NaN, so not necessary set:
df['type2'] = df['type2'].mask(df.type1.isna())
print (df)
                  type1 type2
2020-01-02 6:00     NaN   NaN
2020-01-02 12:00    NaN   NaN
2020-01-02 18:00   60.0   GHI

A: you can also use pandas.DataFrame.where
>>> df.type2.where(df.type1.notna(),inplace=True)
>>> df
         Unnamed: 0  type1 type2
0   2020-01-02 6:00    NaN   NaN
1  2020-01-02 12:00    NaN   NaN
2  2020-01-02 18:00   60.0   GHI


text:
Q: How to send a form contained in a JSP page to a Servlet properly I have this form declaration in my JSP page:
<form name="login" method="post" action="loginServlet">

Assume that the servlet is appropriately declared in the web.xml file; with this pattern <url-pattern>/loginServlet</url-pattern>;
this servlet contains a doPost method.
But what happens is that when I press the button associated to the login form, the server complains that this servlet is not found. What kind of path should I use in order to make it work?
This is the folder structure of my project:
-Project0
   -jsppages
      login.jsp
   +htmlpages
   -WEB-INF
      -classes
          LogIn.class

I guess there's a problem with the path. How could I fix this. Thank you!
Edit: the web.xml contains exactly this referred to my servlet:
  <servlet>
      <servlet-name>LogInServlet</servlet-name>
      <servlet-class>LogIn.class</servlet-class>
   </servlet>

   <servlet-mapping>
      <servlet-name>LogInServlet</servlet-name>
      <url-pattern>/loginServlet</url-pattern>
   </servlet-mapping>

SOLVED:
When calling the action releted to the form, it was necessary to go out of the JSP folder in my project folder by using the path ../loginsServlet so it becomes like this.
<form name="login" method="post" action="../loginServlet">

A: check your web.xml which is present in WEB-INF directory
below is sample
<web-app>
<display-name>HelloWorld Application</display-name>
<servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>SERVLET CLASS NAME WITH PACKE</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/loginServlet</url-pattern>
</servlet-mapping>

and change your action value
<form name="login" method="post" action="./loginServlet">

A: add this to your web.xml file . your page will map to your Servlet
<servlet>
    <servlet-name>loginservlet</servlet-name>
    <servlet-class>package.LogIn</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>loginservlet</servlet-name>
    <url-pattern>/loginServlet</url-pattern>

Note:- Please Put the complete package name (eg com.login.ClassName) before your class name.

Thank You


text:
Q: How to capture sqlplus command line output in unix file I am running below : sqlplus ABC_TT/asfddd@\"SADSS.it.uk.hibm.sdkm:1521/UGJG.UK.HIBM.SDKM\"
afte that I am executing one stored procedure exec HOLD.TRWER
I want to capture return code of the above stored procedure in unix file as I am running the above commands in unix. Please suggest.

A: I guess you are looking for spool
SQL> spool output.txt
SQL> select 1 from dual;

1
----------
1

SQL> spool off

Now after you exit. the query/stroed procedure  output will be stored in a file called output.txt

A: If by return code you mean output then:
command > file

If by return code you mean exit status then:
command
echo "$?" > file

If you mean something else, let us know.

A: You can store command return value in variable
value=`command`

And then checking it's value
echo "$value"

For your case to execute oracle commands within shell script,
value=`sqlplus ABC_TT/asfddd@\"SADSS.it.uk.hibm.sdkm:1521/UGJG.UK.HIBM.SDKM\" \
       exec HOLD.TRWER`

I'm not sure about the sql query, but you can get the returned results by using
value=`oraclecommand`.

To print the returned results of oracle command,
 echo "$value"

To check whether oracle command or any other command executed successfully, just
check with $? value after executing command. Return value is 0 for success and non-zero for failure.
if [ $?=0 ]
then
 echo "Success"
else
 echo "Failure"
fi


text:
Q: Mark menu item as current-menu-item for category I have some categories on my WP website. When users sees this categories and posts from them i want to mark one of menu items as active.
How can i set one of my menu items to have class "current-menu-item" for this categories and posts?

A: I use this functions. First of all, you have to add some custom class to your menu item (allow class input in Screen options, it's not visible by default).
function mark_menu_item_as_active($classes, $item) {

    if( in_array('my-custom-class',$classes) && ( is_category('my-category') /* OR ...*/  ) )   {
        $classes[] = 'current-menu-item';
    }

    return $classes;
}
add_filter('nav_menu_css_class', 'mark_menu_item_as_active', 10, 2);

This function iterates through all menu items, and you will find your target item with that custom menu class. Then you will check whatever conditions you have (is_category, ...), and add another class to its classes (current-menu-item, ...).


text:
Q: Why does the scroll bar sometimes shows up and sometimes it doesnt in a chrome extension If my chrome extension has too much data, a scroll bar shows up and some times it doesnt and just shows a white gap like the screenshot below. Is there a way to disable scroll bars completely? It's currently showing up in my body tag.

A: Remove always the scrollbar from the body
If you access with js
 document.documentElement.style.overflow = 'hidden';  // firefox, chrome
 document.body.scroll = "no"; // ie only

If you acess with css
body{
 overflow: hidden;
}


text:
Q: I cannot select a range of dates in my query I get no answer for my Between query I am trying to send this message through C# to an access database. The user input are two dates selected through a datePicker. The date picker itself is selected as short format. and the access db field is also selected as a short date time. following is my code
"SELECT PLADS,COUNT(*)AS Total FROM OptagetPladser " +
"WHERE( Dato Between #" + date_1 + "# AND #" + date_2 + "# AND Optaget= 0) " +
"GROUP BY PLADS HAVING Total >= " + diffResult;

The problem seems to be the between statement. I have tested using >= date 1 and i get all the results greater than date 1. I then try with just the results <= date 2 and this works but >=date 1 and and <= date 2 gives an empty answer

A: Try using parameters:
StringBuilder sb = new StringBuilder();
sb.AppendLine("SELECT PLADS, COUNT(*) AS Total FROM OptagetPladser");
sb.AppendLine("WHERE ((Dato Between ? AND ?) AND Optaget= 0)");
sb.AppendLine("GROUP BY PLADS HAVING Total >= ?");

Using an established connection:
using (OleDbCommand cmd = new OleDbCommand(sb.ToString(), cn)) {
  cmd.Parameters.AddWithValue("?", date_1);
  cmd.Parameters.AddWithValue("?", date_2);
  cmd.Parameters.AddWithValue("?", diffResult);
  using (OleDbDataReader rdr = cmd.ExecuteReader()) {
    while (rdr.Read()) {
      // do something
    }
  }
}

For OleDb, the parameters are based on an index of when they appear in the SQL string, hence, the "?" values have to be entered in the same order they appear in the query string.

A: Are you sure you can use a column alias in your Having clause?
HAVING Count(*) >= " + diffResult;

Suggestion:  Copy and paste the sql string you built with all the values into the query designer and make sure it runs there.

A: But what if you are using an OleDbDataAdapter() instead of OleDbCommand() so that you can get the data into a datagridview in windows forms?


text:
Q: Windows cmd docker command piping I found this instruction on piping commands in Windows CMD:

The "pipe" redirects the output of a program or command to a second program or command.
Syntax:
Command1 | Command2

[Source] (at the very bottom)
Yet docker ps -aq | docker start or any similar combination just returns errors.
The only working combination to start all stopped container works in PowerShell.
docker start $(docker ps -a -q -f "status=exited")

A: You can pipe into docker containers (-i), but you can't pipe arguments to the docker command itself.
In PowerShell use a loop for starting a list of stopped containers:
docker ps -a -q -f "status=exited" | ForEach-Object { docker start $_ }

In CMD use a loop for starting a list of stopped containers:
for /f "tokens=*" %i in ('docker ps -a -q -f "status=exited"') do docker start %i


text:
Q: Serializing struct containing char* I'm getting an error with serializing a char* string error C2228: left of '.serialize' must have class/struct/union I could use a std::string and then get a const char* from it. but I require the char* string.

A: The error message says it all, there's no support in boost serialization to serialize pointers to primitive types.
You can do something like this in the store code:
int len = strlen(string) + 1;
ar & len;
ar & boost::serialization::make_binary_object(string, len);

and in the load code:
int len;
ar & len;
string = new char[len]; //Don't forget to deallocate the old string
ar & boost::serialization::make_binary_object(string, len);

A: There is no way to serialize pointer to something in boost::serialization (I suspect, there is no actual way to do that too). Pointer is just a memory address, these memory addresses are generally specific for instance of object, and, what's really important, this address doesn't contain information where to stop the serialization.
You can't just say to your serializer: "Hey, take something out from this pointer and serialize this something. I don't care what size does it have, just do it..."
First and the optimal solution for your problem is wrapping your char* using std::string or your own string implementation. The second would mean writing special serializing routine for char* and, I suspect, will generally do the same as the first method does.

A: Try this:
struct Example
{
  int i;
  char c;
  char * text; // Prefer std::string to char *

  void Serialize(std::ostream& output)
  {
     output << i << "\n";
     output << c << "\n";

     // Output the length of the text member,
     // followed by the actual text.
     size_t  text_length = 0;
     if (text)
     (
         text_length = strlen(text);
     }
     output << text_length << "\n";
     output << text << "\n";
  };

  void Input(std::istream& input)
  {
     input >> i;
     input.ignore(1000, '\n'); // Eat any characters after the integer.
     input >> c;
     input.ignore(1000, '\n');

     // Read the size of the text data.
     size_t  text_length = 0;
     input >> text_length;
     input.ignore(1000, '\n');
     delete[] text; // Destroy previous contents, if any.
     text = NULL;
     if (text_length)
     {
         text = new char[text_length];
         input.read(text, text_length);
     }
};

Since pointers are not portable, the data must be written instead.
The text is known as a variable length field.  Variable length fields are commonly output (serialized) in two data structures:  length followed by data OR data followed by terminal character.  Specifying the length first allows usage of block reading.  With the latter data structure, the data must be read one unit at a time until the terminal character is read.  Note:  the latter data structure also implies that the terminal character cannot be part of the set of data items.
Some important issue to think about for serialization:
1.  Use a format that is platform independent, such as ASCII text for numbers.
2.  If a platform method is not available or allowed, define the exact specification for numbers, including Endianness and maximum length.
3.  For floating point numbers, the specification should treat the components of a floating point number as individual numbers that have to abide by the specification for a number (i.e. exponent, magnitude and mantissa).
4.  Prefer fixed length records to variable length records.
5.  Prefer serializing to a buffer.  Users of the object can then create a buffer of one or more objects and write the buffer as one block (using one operation).  Likewise for input.
6.  Prefer using a database to serializing.  Although this may not be possible for networking, try every effort to have a database manage the data.  The database may be able to send the data over the network.


text:
Q: How to start properly http server and host many of sources files in different folders So, the question is:
I have some files that I need to host for my running app, in order to get all that stuff in response from the HTTP server. If I started the HTTP server in the source folder - then all works fine and I can get all my files. But I need to start the HTTP server above my source folder because I have many of them. Suppose that I have 100 different source folders. is it mean that I need to start 100 servers? To avoid it I wanna run single global HTTP server. Also, I have in my source folders mapping that gives the path (hardcoded) to resources and this path starts from source folder like: source/some_file.png
If I run the server in this directory then I will be able to access the file on url
http://localhost:8083/some_file.png.
But if I start the server in the folder above like: main_dir/source then I cannot access the file http://localhost:8083/some_file.png. And my response fails with error code 404.
I've tried to intercept the request and inject the path folder so I get the url file address http://localhost:8083/source/some_file.png. It's working, but then I have different error..
May be there is some other way to start a global http server and access the file one folder below in path?

A: I've found a doc about serving file with NodeJS built in server: doc.
So, 2 possibilities:

*

*Serve files yourself with a list

const fs = require('fs');
const http = require('http');

const folderArray = ["main_dir", "another_dir", ...];

http.createServer(function (req, res) {

  folderArray.forEach((folder) => {
  try {
    fs.accessSync(`${folder}/${}req.url` /* Change req.url for your url or parameter */, fs.constants.F_OK);
    console.log('File exists');
    const data = fs.readFileSync(`${folder}/${}req.url`); // Handle this error correctly
    res.writeHead(200);
    res.end(data);
    // You would want to break the loop here as it's already served.
  } catch (err) {
    console.error('No file!');
  }
  });
}).listen(8080);

*

*Or let a module do it for you: node-static (of course, adapte server folder with your folder array :D).

If you want to download the file, check out this answer: download file with express.
Cheers  !


text:
Q: Extjs failing store.getRootNode().findChild('idelement', record.data.idelement, true) after the first success load I'm building a tree on demand, I mean, if I double click a node then it fetches data from an api rest and then populates the node.
This is what I'm doing:
itemdblclick: function (item, record, eOpts) {
    var store = Ext.getStore('mystore');
    var newStore = Ext.create('mycomponent.mystore', {
        autoDestroy: true
    });
    var node = store.getRootNode().findChild('idelement', record.data.idelement, true);
    var parentid = record.data.idelement;

    var that = this;

    newStore.proxy.extraParams = {
        sort: 'clave',
        'filter[active]': true,
        'filter[idparent]' = parentid
    };

    newStore.load({
        callback: function(items) {
            for (var i = 0, l = items.length; i < l; i++) {
                var item = items[i].data;
                var child = {
                    idparent = parentid,
                    ...
                };
                node.appendChild(child, true);
            }
            node.expand();
        }
    });
}

The first call returns the data properly and inserts it into the node. From there on, every double click producess and error telling me this:

Uncaught TypeError: Cannot read property 'appendChild' of null

Is there any way to solve this? How can I get this working?

A: You are using reference param in asynchronous callback method (load).
You should assign node parameter inside and check if still node exists.
itemdblclick: function (item, record, eOpts) {
    var store = Ext.getStore('mystore');
    var newStore = Ext.create('mycomponent.mystore', {
        autoDestroy: true
    });
    var parentid = record.data.idelement;

    var that = this;

    newStore.proxy.extraParams = {
        sort: 'clave',
        'filter[active]': true,
        'filter[idparent]' = parentid
    };

    newStore.load({
        callback: function(items) {
            var node = store.getRootNode().findChild('idelement', parentid, true);
            if (node) {
                for (var i = 0, l = items.length; i < l; i++) {
                    var item = items[i].data;
                    var child = {
                        idparent = parentid,
                        ...
                    };
                    node.appendChild(child, true);
                }
                node.expand();
            }
        }
    });
}


text:
Q: Can we replace one variable with multiple variables using sed I have a config file where i need to replace the entire line with new values. It can be either a word or a URL. I am trying to write a script to replace only this particular parameter with new values.
I have tried using grep to extract the line using the parameter and divided the values separately and saved in two different variables.
Now I am trying to replace the whole line with the parameter along with new value or url usind sed
jaram=`grep -i "$a" app.properties`;
param=`grep -i "$a" app.properties |sed 's/\'$a'=*//'`;

sed -e 's~'$jaram'~'$a=''$changed_param'~g' app.properties

The config file contains:
abc1=http://howareyou:scema=olk
abc2=http://howareyou:scema=olk

Here I am trying to replace the url of only abc1. though both have same value. I need to replace the entire url with something different url or a word.
Here I am trying to find the line which contains abc1 and this line url after = is saved in a different variable.
I tried to replace the url with new one using sed:
sed -i 's~'$jaram'~'$a=''$param'~g' app.properties
sed: -e expression #1, char 0: no previous regular expression

Seems like I am doing wrong at some syntax when using sed
trying to replace something like
sed 's/jaram/'{$a=$param}/'

Expecting an output like
abc1=http://jalkek:kj/iuwerj
abc2=http://howareyou:scema=olk

A: The following script with comments:
# recrete the input config file
cat <<EOF >input
abc1=http://howareyou:scema=olk
abc2=http://howareyou:scema=olk
EOF

# some input variables
name="abc1"
newvalue='http://jalkek:kj/iuwerj'

# the sed script
sed -i 's'$'\01''^'"$name"'=.*'$'\01'"$name"'='"$newvalue"$'\x01' input

# and the output
cat input

produces the following output:
abc1=http://jalkek:kj/iuwerj
abc2=http://howareyou:scema=olk

Notes:

*

*I used the 0x01 byte as the separator for s command inside sed. So it should work with all printable characters.

*Remember about quoting. All variables should be inside " double quotes, but all the rest would be best if inside ' single quotes.

*I match the name= with ^, so from the beginning of the line. So that for example blablaabc1= doesn't match.

*I use ANSI-C Quoting from bash to generate the unredable 0x01 bytes to delimit sed command.

A little more readable version of the sed script could be this one, that just uses " for quoting and uses ~ as a separator:
 sed "s~^${name}=.*~${name}=${newvalue}~"


text:
Q: passing one function variable as a argument to another function of a Class I am new to PHP. What i am trying i have performed insertion and i will have to grab the its id so i used ;insert_lastid(); function which is same as mysqli_last_insert_id ,so dont get confused with it .i tried to hold that last id on basis of last id i will perform select  operation in another function
Here is the code which will clear more my problem . This function is for  insertion
public function cars_insert($_POST,$path) {
    $this->insert_query="insert into `_cars` (`_year`,`_make`,`_model`,`_version`,`_city`,`_color`,`_mileage`,`_engine_capacity`,                                                                                `_engine_type`,`_assembly`,`_image`)VALUES('" .$_POST['year'] . "','" .$_POST['make'] . "','" .$_POST['model'] . "','" .$_POST['version'] . "','" .$_POST['city'] . "','" .$_POST['color'] . "','" .$_POST['mileage'] . "','" .$_POST['engine_capacity'] . "','" .$_POST['engine_type'] . "','" .$_POST['assembly'] . "','" .$path . "')";
    return $this->insert();
    global $car;
    $this->car=insert_lastid();
}

Here it is the second function it will Select on basis of insert_lastid();
 public function cars_id($this->car){
    $this->select_query="SELECT * FROM `_cars` WHERE `_id`='$this->car'";
    return $this->select();
}

A: The reason that the ID isn't being set is that you have a return statement before you set the variable. The moment you hit the return statement the function stops executing. Move  your code so that the variable assignment is done before the function returns.
$insert = $this->insert();
$this->car=insert_lastid();

return $insert;

Your global $car statement and the parameter in cars_id are both unnecessary because $this->car is a member of the class and is accessible from any member function of that class without having to be passed in or global'ed as you would with a normal variable.
public function cars_id(){
    $this->select_query="SELECT * FROM `_cars` WHERE `_id`='$this->car'";
    return $this->select();
}

As a side note, your code is currently extremely vulnerable to SQL injection attacks unless you have some kind of code in $this->insert() that is checking your SQL statements before running them. Make sure you properly escape all $_POST variables before using them in a query, or use prepared statements.


text:
Q: Launching python3 script using a python2 script is there a way to launch a script running on python3 via a python2 script.
To explain briefly I need to start the python3 script when starting the python2 script.
Python3 script is a video stream server (using Flask) and have to run simultaneously from the python2 script (not python3 script first and then python2 script).
The ideal would be to get a function in the python2 script which "open a cmd window and write" it in : python3 script_python3.py

A: *

*create command in bash file. command is to run script_python3.py, ex: python script_python3.py

*then from python2 file, run the .bash file. ex:
import os
os.popen('sh /scripts/my_bash.sh')

A: You could use something like explained in this answer.
That use case of that question is a bit different, but the answer should work.


text:
Q: Unexpected type (File) of the resource with URI with JasperReports I have a main report, and need one of the fields to be a hyperlink to another report (using that field as the parameter of the second report).

*

*I right clicked, and clicked Hyperlink

*Link Target - Blank

*Link Type - ReportExecution

Parameters:

*

*Name: _report Expression: /ca_ppm/resources/PSR_MilestoneReportV2.jrxml

*Name: program Expression: $F{name}
The parameter program is used in the sub-report to pull the information.
The expression for _report is the correct path for the .jrxml file of the sub-report, and I also have that .jrxml file marked as a resource in Controls and Resources for the main report...
Yet I am getting this error:
Unexpected type (File) of the resource with URI/ca_ppm/resources/PSR_MilestoneReportV2.jrxml

This seems to be a path issue.
Am i missing something?

A: _report needs to be a report unit with data source and son on (same type of resource/entity as the main report) and not a JRXML file resource.
And if you want to pass "program" as a parameter, you'll need to define an input control for it (in addition to the JRXML report parameter) in the target report unit.


text:
Q: How to get all model objects from a Wicket datatable I'm using a Wicket DefaultDataTable. It contains some text fields that the user is supposed to put values in. The table is in a form. When I submit the form, I want to get hold of all the "rows" so that I can iterate through them. I don't want to use AJAX.
I've managed to bind the table to a "Contact" object, with an EditablePropertyColumn that shows the right fields and input boxes in the columns I want.
How can I get hold of the row items? dataTable.getDefaultModelObject() returns null when the form is submitted.

A: Honestly, it sounds like you have some other (more fundamental) thing wrong.  As martin-g mentions, the editable property column uses a property model, which means that when the form is submitted (if all validation, etc, passes), it will call setObject on that model, which in turn will call setFoo (where "foo" is the property for that column) on the POJO that backs that row of data in your table.
You could (as Don mentions) use a visitor to iterate through the children of your table.  However, in general, this means that you're doing something else wrong.  Wicket is written so that you do not have to go pull data from a form submission and push it yourself onto your POJOs.  The model should do that for you.  You should not be "pushing" data around yourself.
Showing some code would help, but short of that: wherever your table gets its data from (some list of Contacts, etc) - try to just pull the data from those same objects.  It should already be populated for you.  If it's not, post some code - especially where you're initializing the table and its data provider.

A: The submitted data is populated in the Contact object. This is how PropertyColumn works.

A: the DefaultDataTable have a method newRowItem in thath method you can catch the models that are displayed of the table:
  private List<IModel<T>> models= new LinkedList<IModel<T>>();
    @Override
    protected Item<T> newRowItem(final String id, int index,
            final IModel<T> model) {
              models.add(model);
    }

A: It would be easier to be specific if you showed the code you've got, but I can think of two general approaches to this.
One way is to just maintain a list of references to the models somewhere outside the DefaultDataTable as you're constructing it.
If it's difficult to find a way to do that, another possible approach is to use an implementation of Wicket's IVisitor to search the components inside your datatable for components containing the models.
The WebMarkupContainer class has a method
public final <S extends Component> Object visitChildren(final Class<?> clazz,
    final IVisitor<S> visitor)

which can be used to traverse all contained components of a specific class, and a method
public final Object visitChildren(final IVisitor<Component> visitor)

which does the same but without restricting to a specific class.
The IVisitor<T extends Component> interface requires you to define a method
public Object component(T component)

which is called by these "visit" methods with each component found as argument.  The return value is a signal to continue or exit the traversal, and the method you define can collect things it finds in the component into a list.


text:
Q: Serving different charsets per virtual host On a centos Server 6.5, apache 2.2.15 is it possible to server multiple charsets to different virtual hosts?
I know that setting the default Charset is done by adding into the httpd.conf file:
AddDefaultCharset UTF-8

However some of the websites we have need to be encoded using ISO-8859-1 but the other websites that are served by Symfony need to be encoded with UTF-8. Is it possible to add a default charset per virtual host or does this need to be done using .htaccess files?

A: You can specify the default charset per directory or vhost, see httpd.apache.org.
In short:
<Directory /some/dir>
    CharsetDefault ISO-8859-1
</Directory>

You'll also need to ensure that the mod_charset_lite module is enabled.


text:
Q: cannot restart postgres on mac os x I cannot restart the postgres server on Mac OS X.
How can I fix this?
Tried two ways:
pg_ctl restart returns:
pg_ctl: PID file "usr/local/var/postgres:/postmaster.pid" does not exist
Is server running?
starting server anyway
pg_ctl: could not read file "usr/local/var/postgres:/postmaster.opts"

The server does not restart
pg_ctl -D /usr/local/var/postgres restart results in:
   pg_ctl: PID file "/usr/local/var/postgres/postmaster.pid" does not exist
   Is server running?
   starting server anyway
   server starting
   LOG:  could not bind IPv4 socket: Address already in use
   HINT:  Is another postmaster already running on port 5432? If not, wait a few seconds and retry.
   LOG:  could not bind IPv6 socket: Address already in use
   HINT:  Is another postmaster already running on port 5432? If not, wait a few seconds and retry.
   WARNING:  could not create listen socket for "*"
   FATAL:  could not create any TCP/IP sockets

A: 1 - Your data directory might be wrong.  Make sure you use the right path.
2 - If you install more than one postgres, you need to specify which pg_ctl to use.
I installed postgres 9.2 manually, here's how I start it:
/Library/PostgreSQL/9.2/bin/pg_ctl -D /Library/PostgreSQL/9.2/data start

I installed postgres 9.1 via HomeBrew, here's how it gets started:
/usr/local/Cellar/postgresql/9.1.5/bin/pg_ctl -D /usr/local/var/postgres-9.1.5 start


text:
Q: Predicting 5 next value based on sequence of numbers I am trying to find a way to predict the next 5 numbers based on a sequence of numbers.
training set:

prediction:

I want to use LSTM to learn the training set to predict the next 5 numbers in the test set.
Do you have any idea how can I do this with LSTM?

A: A simple solution is to create a LSTM layer of 3 hidden states to learn.
Create sequence training set for LSTM from your data mentioned in the question, for example:
7 9 27 13 10 -> 60, will turn into these samples:
[7 9 27] -> 13
[9 27 13] -> 10
[27 13 10] -> 60
For a long input sequence, eg. [1 2 3 4 5 x1 x2 x3], with x1 x2 x3 are any last 3 values:

*

*Feed [x1 x2 x3] to the model to find x4

*Feed [x2 x3 x4] to the model to find x5

*Repeat again until you have enough predicted values, those'll be [x4 x5 x6 x7 x8]

Harder solution is to

*

*Create a LSTM layer with the number of hidden states of max_len(sequence).

*Pad those sequences not enough length by zeros

*Train the model with expected values on the right column

Inference:

*

*From input sequence, pad zeros to have enough length

*Feed to model

*Feed 5 times, after each feed, append the result to input sequence and get max_len items at tail to feed again