text:
Q: Symfony: Forms with inherited classes I'm trying to figure out how to handle forms when using inherited class types with Symfony (2.8.6).
I have created a [very] simple example case of what I'm trying to do below. There are problems with it, but it's only to illustrate my question.

*

*How can I supply just one form going from the controller to a twig template so that there can be a field to choose what "type" (discriminator) should be used? Should I simply create another variable, such as "type" that is hardcoded in each class?

*Once a form is submitted, how can I figure out which class should be used in the controller, in either a "new" or "edit" action? I've tried plucking it out of the ParameterBag, creating an appropriate entity and form, then using $form->handleRequest($request); ...but it doesn't seem to work when there are extra fields that might belong to another type.

If someone could even point me to a Github repo or something that shows something like this happening, I'd be very grateful. Thanks for your time.
If these are my classes:
 /**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap("truck" = "Truck", "Car" = "Car", "suv" = "SUV")
 */
abstract class Vechicle {
    private $make;
    private $model;
    private $numberOfDoors;

    // getters and setters //
}

class Truck extends Vehicle {
    private $offRoadPackage;
    private $bedSize;

    // getters and setters //
}

class Car extends Vehicle {
    private $bodyType;
}

class SUV extends Vehicle {
    // no additional fields //
}

then something like these would be my form types:
class VehicleType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('make')
            ->add('model')
            ->add('numberOfDoors');
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\Entity\Vehicle'
        ));
    }
}

class TruckType extends VehicleType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        parent::buildForm($builder, $options);
        $builder
            ->add('offRoadPackage')
            ->add('bedSize');
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\Entity\Truck'
        ));
    }
}

class CarType extends VehicleType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        parent::buildForm($builder, $options);
        $builder
            ->add('bodyType')
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\Entity\Car'
        ));
    }
}

class SUVType extends VehicleType {
    public function buildForm(FormBuilderInterface $builder, array $options) {
        parent::buildForm($builder, $options);
    }

    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\Entity\SUV'
        ));
    }
}

A: This is going to be a bit of a lengthy one but bear with me. The gist of this idea is that you deal with your forms in an array. You create a list of types which you iterate to build the actual form objects. This way the only thing you edit is the list of form types if you wish to add more.
In your template you iterate over all the forms to render them and wrap them in a div you can hide. Next you can add a select element that controls a piece of javascript showing/hiding the form of the type the user has selected.
After sbumission you can test if the action has been POSTed to and reiterate the forms to check which one of them has been submitted and handle it appropriately.
Below is a crude untested code snippet:
The controller/action:

class SomeController
{
    public function addAction()
    {
        $types = [
            'Form1' => Form1::class,
            'Form2' => Form2::class,
            'Form3' => Form3::class,
        ];

        // create the forms based on the types indicated in the types arary
        $forms = [];
        foreach ($types as $type) {
            $forms[] = $this->createForm($type);
        }

        if ($request->isMethod('POST')) {
            foreach ($forms as $form) {
                $form->handleRequest($request);

                if (!$form->isSubmitted()) continue; // no need to validate a form that isn't submitted

                if ($form->isValid()) {
                    // handle the form of your type

                    break; // stop processing as we found the form we have to deal with
                }
            }
        }

        $views = [];
        foreach ($forms as $form) {
            $views = $form->createView();
        }

        $this->render('template.html.twig', ['forms' => $views, 'types' => $types]);
    }

}

The template:
<select id="types">
    {% for type in types|keys %}
        <option value="vehicle_type_{{ loop.index }}">{{ type }}</option>
    {% endfor %}
</select>
{% for form in forms %}
    <div class="form hidden" id="vehicle_type_{{ loop.index }}">
        {{ form_start(form) }}
        {{ form_widget(form) }}
        {{ form_end(form) }}
    </div>
{% endfor %}

And finally the piece of javascript controlling what form is shown/hidden:
<script>
    // On select change hide all forms except for the on that was just selected
    $('#types').on('change', function () {
        $('.form').addClass('hidden');
        $('#' + $(this).val()).removeClass('hidden');
    });
</script>


text:
Q: Any way of show hide multiple passwords at the same time in Javascript? I am trying to find a solution if is possible to show / hide the password at the same time?
I could only show / hide for the first original password.
Does anybody know a solution for it or if is even possible?
Here is JavaScript and HTML code

function Toggle() {
  let btt = password
  if (btt.type === "password") {
    btt.type = "text";
  } else {
    btt.type = "password";
  }
}

function checkPassword(register) { //correct
  let fisrtPassword = register.password.value;
  let retypedPassword = register.retypedpassword.value;
  if (fisrtPassword === retypedPassword) {
    return true;
  } else {
    passwordMatchError.setAttribute("class", "error");
    passwordMatchError.innerHTML = ("Passwords do not match. Please retype");
    return false;
  }
}

A: In your Toggle function you are currently only updating the field with the id password. So when you change the type of that field, only that field is changed. You are not checking the other field called retypedpassword, therefor it won't be changed. Check out the my addition to your code here below for a working version of your toggle for BOTH fields.
function Toggle() {
    const fields = [password, retypedpassword]

    fields.forEach( x => {
        if (x.type === "password") {
            x.type = "text";
        } else {
            x.type = "password";
        }
    });
}

And a second exmample using the style of your current code:
function Toggle() {
    let btt = password
    if (btt.type === "password") {
        btt.type = "text";
    } else {
        btt.type = "password";
    }

    let otherfield = retypedpassword
    if (otherfield.type === "password") {
        otherfield.type = "text";
    } else {
        otherfield.type = "password";
    }
}

A: Try this. Note I remove the toggle from the password field click and gave the fields a class
I also streamlined your submit handler and fixed spelling and added required

document.getElementById("showpasswords").addEventListener("click",function() {
  [...document.querySelectorAll(".password")].forEach(p =>
    p.type = p.type === "password" ? "text" : "password"
  )
})
document.getElementById("registerdetails").addEventListener("submit", function(e) {
  const errSpan = document.getElementById("passwordmatcherror");
  let firstPassword = this.password.value;
  let retypedPassword = this.retypedpassword.value;
  errSpan.classList.toggle("error", firstPassword !== retypedPassword);

  if (firstPassword !== retypedPassword) {
    errSpan.innerHTML = ("Passwords do not match. Please retype");
    e.preventDefault();
  }
});

    <form id="registerdetails" action="fma_t3confirm.html">

        * Password (Must be 8 characters and include one uppercase, one lowercase and
      one numeric):

        <input type="password" class="password" id="password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,8}$" required>
        <input type="checkbox" id="showpasswords"> Show passwords

        * Retype your password:

        <input type="password" class="password" id="retypedpassword">

      <input type="submit" />
    </form>

A: A simple way is just adding another button for the second input:
function Toggle() {
    let btt = password;
    let btt2 = retypedpassword;

    if (btt.type === "password") {
        btt.type = "text";
        btt2.type = "text";
    } else {
        btt.type = "password";
        btt2.type = "password";
    }
}

A: Add a class pwd in both password fields. Also remove the Toggle method call on click of 2nd password field
<input type="password" class="pwd" id="password"
                                       pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,8}$">
<input type="password" class="pwd" id="retypedpassword">

Your Toggle function:
In the Toggle function, get all the pwd fields and then toggle the type of all fileds.
  function Toggle() {
    let pwdFiels = document.querySelectorAll('.pwd');

    for (let fields in pwdFiels) {
        if (pwdFiels[fields].type === "password") {
            pwdFiels[fields].type = "text";
        } else {
            pwdFiels[fields].type = "password";
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having trouble using group by in angularJS So I have this select-window that I want to group by 2 object arrays. I have subcategory- and rootcategory-objects. Subcategory have a relation id that is used to link up to rootcategory's id. What I want is for the dropdown window to group the subcategories by the rootcategory name. As of right now, I only got it to group by the different relation ids. Not using the rootcategory at all. Any advice?
From the html-page;
<div ng-controller="categoryController">
    <select ng-model="$parent.subCategoryObject" data-ng-options="subCategories.subCategory group by subCategories.relation for subCategories in subCategories">
        <option value="">Velg en kategori</option>
    </select>
</div>

From the controller.js
wikiControllers.controller('categoryController', ['$scope', 'categoryService',
function($scope, categoryService){
  categoryService.getCategories().then(function(data){
    $scope.rootCategories = data[0];
    $scope.subCategories = data[1];
    $scope.titles = data[2];
    console.log($scope.titles);
  });

}]);

A: You can add a function to the $scope that retrieves the name of the root category by an id, then use that function in the group by.
For example:
$scope.getRootCategoryName = function (id) {
  return $scope.rootCategories.filter(function (category) {
    return category.Id === id;
  })[0].Name;
};

And:
data-ng-options="subCategories.subCategory group by getRootCategoryName(subCategories.relation) for subCategories in subCategories"

Demo: http://plnkr.co/edit/rors7R55Z5fLE8DY0ja1?p=preview


text:
Q: Google Sheets SheetNames function for Visible Sheets Only I have a spreadsheet with a seperate sheet for each of our staff. I am wanting a dashboard page that will have a list of staff names when new sheets are added and also remove old staff when their sheet is hidden.
I am trying to figure out a way to run this code and only return the sheet names that aren't hidden, is this even possible? I have had a play around for the last few days but can't seem to get anything to work
    function SheetNames() {
    try {
    var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets()
    var out = new Array( sheets.length+1 );
    //out[0] = [ "Name" , "gid" ];

    for (var i = 3 ; i < sheets.length+1 ; i++ ) out[i-6] = [sheets[i-1].getName()];
    return out
    }
    catch( err ) {
    return "#ERROR!"
    }
    }

A: You can use the method isSheetHidden()
Sample:
function SheetNames() {
  try {
    var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
    var out =[];
    for (var i = 3 ; i < sheets.length+1 ; i++ ){
      if(sheets[i-1].isSheetHidden()==false){
        out.push(sheets[i-1].getName());
      }
    }
    return out;
  }
  catch( err ) {
    return "#ERROR!";
  }
}


text:
Q: Cron Job for Windows error: Could not find a file Hi When I run my C# Console Application manually just opening it, my internal code in which opens the file \server\folder\database.mdb  works fine, but when I run the same C# Console Application openning through a Cron job for Windows It returns the error:

Could not find the file \server\folder\database.mdb

How is it possible, it is inside my c# code, what does Cronjob that gives me this error?
Is there any #path configuration or environment variable or even a default folder that cron job uses, do I need to change something to work with Cron jobs?

A: The user under which task scheduler is running may not have permissions  to that folder


text:
Q: How to make my react app server side rendering on APACHE SERVER without NodeJS? I'm running my react app on apache server, and it is client side rendering. I add react to my website using CDN links
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js" integrity="sha256-FiZMk1zgTeujzf/+vomWZGZ9r00+xnGvOgXoj0Jo1jA=" crossorigin="anonymous"></script>

Now, I want to shift it to be server side rendering without using Nodejs.
What is the proper way to do that?

A: You can't, at least not without a vast amount of work.
To get server-side rendering you need to execute the JavaScript on the server. Node.js is the premier out-of-browser JavaScript runtime and all the tools designed to enable server-side rendering for React.js (like Next.js) are designed to work with Node.js.
To get server-side rendering with Apache HTTPD and without Node.js you would need to:

*

*Select a JS runtime

*Implement something akin to Next.js using that runtime

*Configure Apache HTTP to communicate with that runtime (possibly involving the writing of a whole new Apache module)


text:
Q: didCellParse does not return cell I'm trying to center a row. My <td> has colspan across the table.
I have a data tag in the <td> because I have dynamic subheaders in the tables. With willDrawCell and didDrawCell I can access the cell.raw property and check the data tag to apply the style.
When I use didCellParse the CellHookData has cell as undefined.
With the willDrawCell and didDrawCell, I can alter the halign property, but it DOES NOT render in the center of the row in pdf.
didParseCell: data => {
             if($(data.cell.raw).data('subhead') == true){
                 data.cell.halign = 'center';
             }
       }

With didParseCell I receive an error, because cell is undefined.
https://codepen.io/lightningmd/pen/gOOaezM
This code pen is using willDrawCell. You can see the subheader is found, and the cell.styles.halign is applied. Just change to didParseCell for the error.

A: You need to set the styles on the cell styles object, not the cell: data.cell.styles.halign = 'center'.
Seems there also is a bug where didParseCell is called with a null value for data.cell when there are colspans/rowspans. All in all, this should work:
   didParseCell: data => {
         if (data.cell && $(data.cell.raw).data('subhead') == true) {
             console.log('Subheader Found;')
             data.cell.styles.halign = 'center';
         }
   }


text:
Q: Continuous Deployment multiple projects from one solution c# I have one solution with multiple projects inside:
Project1 - Class Library
Project2 - MVC
Project3 - Class Library
Project4 - WCF
I now want TFS to build all projects but also automatically deploy the MVC project to http://somehost/MVC
and the WCF to http://somehost/WCF.
I have tried to change my build definition but it is only the MVC that gets deployed.
By the way: Gated Check-in is enabled on the TFS.

A: I had this exact issue, and I solved it by manually editing the project files.
This way TFS will deploy both projects on build. Note the build configuration names - I've created these especially for my TFS build definitions to point at (I have 2 build definitions: Dev & QA). Applying the propery group to these definitions mean the projects don't get deployed every time you build the projects in your dev environment when running the debug config. It also means that I can deploy to different locations depending on whether I'm running a QA or Dev build.
Example:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DEV-BUILD-|AnyCPU'">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <DeployOnBuild>true</DeployOnBuild>
    <DeployTarget>MsDeployPublish</DeployTarget>
    <MSDeployPublishMethod>RemoteAgent</MSDeployPublishMethod>
    <MSDeployServiceUrl>http://DEV-SERVER-ADDRESS</MSDeployServiceUrl>
    <DeployIisAppPath>PROJECTminder.API-MAINTENANCE</DeployIisAppPath>
    <UserName><MACHINE-NAME>\BuildUser</UserName>
    <Password>*****</Password>
    <AuthType>Basic</AuthType>
    <AllowUntrustedCertificate>true</AllowUntrustedCertificate>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'QA-BUILD|AnyCPU'">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <DeployOnBuild>true</DeployOnBuild>
    <DeployTarget>MsDeployPublish</DeployTarget>
    <MSDeployPublishMethod>RemoteAgent</MSDeployPublishMethod>
    <MSDeployServiceUrl>http://QA-SERVER-ADDRESS</MSDeployServiceUrl>
    <DeployIisAppPath>PROJECTminder.API</DeployIisAppPath>
    <UserName><MACHINE-NAME>\BuildUser</UserName>
    <Password>*****</Password>
    <AuthType>Basic</AuthType>
    <AllowUntrustedCertificate>true</AllowUntrustedCertificate>
  </PropertyGroup>

Update:
I should add that this was my solution for VS2010. I believe in newer versions (2012+) you can actually define publish profiles per project (.pubxml) which TFS will pick up.

A: I use Octopus Deploy for this. With the default build process template you can
trigger a Post-build Powershell script. In this script you can create NuGet packages, create a release and deploy them to a number of servers.
In the Octopus Deploy documentation is a way to create packages to deploy Create Packages with TFS. There is a blog post about the integration of TFS and Octopus Deploy here.


text:
Q: How to make a delivery URL for a webhook in WooCommerce? I have a problem when I want make WooCommerce hook. It says:

Make delivery URL

I do not know exactly how I made it! Any help will be much appreciated!

A: First, make the product, and then pass the URL of the product into the "Delivery URL" tab.


text:
Q: MVC login if cookie exist I don't know much about web authorization, but there is one page which after login into gives the user coockie of name AUTH_WEBSITE, and this website redirects to my website which is mvc. Now I would like to only check if this user has that auth cookie and if it has, then I would like to authorize it in my website as well.
Now, I assume that checking cookies this way and givin admin rights based on cookie is NOT safe because other user can create this cookie for him self right ? so what would be better ?
And what is best place in mvc to check if other user is already authorized or has this cookie to prevent forcing user to click login button ?

A: To solve this issue you can use 2 ways:

*

*When you create your custom cookie, use encryption methods. Encrypt user's role, password, even id etc. So other people can not decrypt them all to create other legal cookie.

*For security, the best way is that to check user is exist in system or not in every action start. In your Authorize attribute, take values from cookie and check user, if it just exist continue, else alert : cookie values are wrong.


text:
Q: Regex to Replace filepath in a string with some other filepath in Java I have a below text file in String 'str'
 # Configuration file for the Jakarta ISAPI Redirector

# The path to the ISAPI Redirector Extension, relative to the website
# This must be in a virtual directory with execute privileges
extension_uri=/jakarta/isapi_redirect.dll

# Full path to the log file for the ISAPI Redirector
log_file=C:\\\\Programs\\\\Org\\\\Pro\\\\Client\\\\apache-tomcat-8.0.33\\\\logs\\\\isapi_redirect.log

# Log level (debug, info, warn, error or trace)
log_level=info

# Full path to the workers.properties file
worker_file=C:\\\\Programs\\\\Org\\\\Pro\\\\Client\\\\apache-tomcat-8.0.33\\\\conf\\\\workers.properties

# Full path to the uriworkermap.properties file
worker_mount_file=C:\\\\Programs\\\\Org\\\\Pro\\\\Client\\\\apache-tomcat-8.0.33\\\\conf\\\\uriworkermap.properties

and i want to replace all occurrences of
C:\\\\Programs\\\\Org\\\\Pro\\\\Client\\\\apache-tomcat-8.0.33

with
C:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 9.0

so that my final 'str' looks like below
# Configuration file for the Jakarta ISAPI Redirector

# The path to the ISAPI Redirector Extension, relative to the website
# This must be in a virtual directory with execute privileges
extension_uri=/jakarta/isapi_redirect.dll

# Full path to the log file for the ISAPI Redirector
log_file=C:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 9.0\\\\logs\\\\isapi_redirect.log

# Log level (debug, info, warn, error or trace)
log_level=info

# Full path to the workers.properties file
worker_file=C:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 9.0\\\\conf\\\\workers.properties

# Full path to the uriworkermap.properties file
worker_mount_file=C:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 9.0\\\\conf\\\\uriworkermap.properties

Basically i want to replace filepath after '=' till i encounter 'apache'. this 'apache' could sometimes be 'Tomcat' as well
I visited almost every answers/solutions in stackoverflow and tried to tweak them but none of them yield desired output.
I have tried around 8-9 Regex since its too many i didn't post them

A: "\" is a meta character in Regex which means you should code "\\" , meanwhile "\" needs to be escaped in Java so that If you want to match a "\" character you should code "\\\\".


text:
Q: Why has io.sort.record.percent been removed? Why has the io.sort.record.percent property been removed from Hadoop 1.x onwards?

A: It's there in 2.x but the only difference is that its name has changed:

mapreduce.task.io.sort.mb: The total amount of buffer memory to use while sorting files, in megabytes. By default, gives each merge stream 1MB, which should minimize seeks.

Default value is still 100 mb. Please find more information on this link.

A: io.sort.record.percent is a percentage applying to io.sort.mb (old name).
Map output data is placed in an in-memory buffer. When the buffer fills up, the framework sorts it and then spills to disk.  A separate thread merges the sorted on-disk files into a single larger sorted file. The buffer consists of two parts: a section with contiguous raw output data and a metadata section that holds pointers for each record into the raw data section. In MR1, the sizes of these sections were fixed, controlled by io.sort.record.percent, which says how much percent of the io.sort.mb space is used for metadata secton. This meant that, without proper tuning of this parameter, if a job had many small records, the metadata section could fill up much more quickly than the raw data section. The buffer would be spilled to disk before it was entirely full. This affects performance.
MAPREDUCE-64 fixed this issue in MR2 by allowing the two sections to share the same space and vary in size. Thus io.sort.record.percent is no longer required to minimize the number of spills in MR2. That's why this property has been removed


text:
Q: Calculated column in view performance issue I've got a table with location data (Lat/Lngs) stored as geography type.
Now this location data represents a Journey, so I want to calculate the distance travelled during the Journey, distance per day and distance per month. So for this I need a property to calculate the distance from the next location in the Journey.
If I do this using a Select from the table with a Window Function, the performance is very good and the Execution Plan seems fine. Execution Plan
This is the Query -
Select
    iVehicleMonitoringId,
    iAssetId,
    iDriverId,
    dtUtcDatetime,
    sptGeoLocaitonPoint,
    fAngel,
    sDirection,
    fSpeedKPH,
    eEventCode,
    fDistanceTravelled = sptGeoLocaitonPoint.STDistance(LEAD(sptGeoLocaitonPoint) OVER(PARTITION BY iAssetId ORDER BY dtUTCDateTime)),
    eIgnition,
    eDoor,
    eSeatbelt,
    eIgnition2,
    sAddress
From dbo.VehicleMonitoringLog

Where iAssetId = 1
    AND dtUTCDateTime BETWEEN N'2017-12-27' AND N'2017-12-27 23:59:59.997'

Now because I need this Distance Calculated property in my code. I decided to create an SQL View with the fDistanceTravelled property.
CREATE VIEW [dbo].[TB5_xPT_VehicleMonitoringLogs]
AS
    Select
        iVehicleMonitoringId = ISNULL(iVehicleMonitoringId, -1),
        iAssetId,
        iDriverId,
        dtUtcDatetime,
        sptGeoLocaitonPoint,
        fAngel,
        sDirection,
        fSpeedKPH,
        eEventCode,
        fDistanceTravelled = sptGeoLocaitonPoint.STDistance(LEAD(sptGeoLocaitonPoint) OVER(PARTITION BY iAssetId ORDER BY dtUTCDateTime)),
        eIgnition,
        eDoor,
        eSeatbelt,
        eIgnition2,
        sAddress
    From dbo.VehicleMonitoringLog
GO

But when I import this View into my Entity Framework, it gets a timeout. So I checked the Execution Plan and it doesn't match that of selecting from the Table.
View Execution Plan
This is the query -
Select
    *
From TB5_xPT_VehicleMonitoringLogs
Where iAssetId = 1
    AND dtUTCDateTime BETWEEN N'2017-12-27' AND N'2017-12-27 23:59:59.997'

To do this in code I need to loop through all the location logs in the list.
DbGeography prevPoint = null;
foreach (var historyLog in historyLogs)
{
    var distanceFromPrevPoint = 0.0;
    if (prevPoint != null)
    {
        var distance = prevPoint.Distance(historyLog.sptGeoLocaitonPoint);
        if (distance != null)
            distanceFromPrevPoint = Math.Round(((double)distance * .001), 2);
    }

    var locationLog = Mapper.Map<LocationLogDTO>(historyLog);

    locationLog.DistanceTravelled = distanceFromPrevPoint;

    prevPoint = historyLog.sptGeoLocaitonPoint;

    historyDto.LocationLogs.Add(locationLog);
}

I don't want to do this. I need a better way of doing this.
EDIT
Image Explaining the fDistanceTravelled column calculation.


text:
Q: problem about differential forms
Let $M$ be  connected, and let $\pi: M\times N \rightarrow N$ be the
   natural projection. Prove that a $p$-form $w$ on $M\times N$ is $\delta \pi(\alpha)$ for some $p$-form $\alpha$ on $N$ if and only if
   $i(X)w = 0$ and $L_X w=0$ for every vector field $X$ on $M\times N$
   for which $d\pi(X(m,n)) = 0$ at each point $(m,n) \in M\times N$.

$i(X)$ is the interior multiplication my the vector field $X$, and $L_X$ is the Lie-derivative w.r.t. the vector field $X$. $d$ is exterior differentiation, and $\delta$ is its transpose or adjoint.
Could you give me some hints for this problem? I tried to do the forward direction just by applying the formulas in the book, and I do not know how to approach the reverse direction.
What I have done so far, first I want to prove the forward direction, given $w=\delta\pi(\alpha)$, then for any vector fields $Y_1, \cdots Y_{p-1}$ on $M\times N$ we have
$$
\begin{align}
i(X)(\delta\pi(\alpha))(Y_1, \cdots Y_{p-1}) (m,n) &=(\delta\pi(\alpha))(X,Y_1, \cdots Y_{p-1}) (m,n)  \\
&= \alpha_{\pi((m,n))}\big(d\pi(X(m,n)), \cdots, d\pi(Y_{p-1}(m,n))\big)\\
&= \alpha_{\pi((m,n))}\big(0, \cdots, d\pi(Y_{p-1}(m,n))\big)\\
&=0
\end{align}$$
Next to show $L_X(w) = 0$, we use the formula that $L_X = i(X)\circ d + d\circ i(X)$. The second part is zero by above calculation, and for the first part, note that
$$i(X) d(\delta\pi(\alpha)) = i(X) \delta \pi(d\alpha)$$
then this would be a similar calculation as above, just $d\alpha$ instead of $\alpha$.
Are my calculations correct? and could you give me some hints for the reverse direction.


text:
Q: How to make menu items span across menu bar evenly I have a site that I am working on.. and would like to know how to span the menu items evenly across the menu bar.
I know how to do it technically, but I want to make sure it's correct.
I want to be able to add another menu item and still have it look normal or overflow properly, etc.
The site is http://phillysuburbanhomes.com

Okay, so I added
.wpsight-menu li {
    width:14%;
    text-align:center
}

(more menu items were added)
My issue now is, that the full menu item doesn't show now
http://phillysubrubanhome.com - you can see what it's doing live

A: Use CSS to give your anchors (a) the same padding and margins on the left and right and a percentage width of the li, like this;
ul#main-menu {
   width: 100%;
}

ul#main-menu li {
   width: 20%; /* for 5 menu items */
   padding: 0;
   margin: 0;
   display: inline-block;
}

ul#main-menu li a {
   padding: 0px 5px;
   margin: 0px auto;
   display: block;
}

and change the width of the li depending on the number of menu items.
That should do the trick!

A: Currently there are 5 menu items, im assuming you would be adding another menu item thus making it 6 menu items.
The width of the container is 980px. Divide it in 6 parts which comes to 163.33. We need to give the width in percentage i.e 16.66%.
Set the width for each li as 16.66% and center-align the text.
Your css would be as follows:
ul#main-menu li{
    width:16.66%;
    text-align:center
}

A: Okay so I combined one of your methods with this this and it worked:
.wpsight-menu li {
    width:14%;
    text-align:center
}

.wpsight-menu a {
    display: inline-block;
    margin: 0 5px 0 0;
    text-decoration: none;
}


text:
Q: MySQL - Export two columns from large table without causing a lock I am a sysadmin who doesn't do a ton of dba stuff. For a project, I have access to a production server--which I am not the sysadmin for--with an enormous 40,000,000 row >10 GB MySQL InnoDB table. I want to export two small columns, one of which is an INT(11), and the other of which is a VARCHAR(20) from that table to a CSV or .SQL file (either is fine, I'll write a crosswalk for the next step no problem).
We can call the columns ColumnA and ColumnB and the table SampleTable.
MySQLdump is not the right tool for this because I can't specify the columns and I don't need to export a massive massive table just got two tiny columns.
I know I can do a SELECT INTO statement (either to create a new table with just the columns or to do a SELECT INTO OUTFILE to skip the intermediate step), but I am concerned that this will cause a table level lock on a production server. The table is InnoDB.
What's my best bet to avoid inconveniencing any live traffic on the server or locking anything?
Thanks

A: Many experts share many ways on how to overcome this problem. These are my suggestions to play a safe game.
Try to set the below command in a seperate session.
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
use db;
SELECT COLA, COLB into outfile '/tmp/data.csv' from TABLE_NAME;
COMMIT;
exit;

Doing by this way the SELECT statements are performed in a nonlocking fashion, but a possible earlier version of a row might be used. Thus, using this isolation level, such reads are not consistent.When you say not-consistent it means recently changing records i.e.. DML transactions that are currently in process will not be read. I assume which is in your case it is acceptable. This is also called a "dirty read." Otherwise, this isolation level works like READ COMMITTED.
If I were to be you, the below order is what I follow.

*

*Check for non-peak hours for DB server also for the table that you mind to do select. By this the outfile reads/write, IOs shouldn't cost much to the server.

*Manually run this in the server back ground. And keept monitoring the server health.

$ cat bg_loaddata.sh

mysql -uroot -p*** << EOF
use db;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;
SELECT COLA, COLB into outfile '/tmp/data.csv' from TABLE_NAME;
COMMIT;
exit;
EOF

$ nohup ./bg_loaddata.sh > bg_loaddata.log &

*

*If you see any inserts or updates that are taking longer time to complete in show processlist; You may wait for sometime, but if it is causing severe turbulence then goahead and kill the connection id in processlist for your select ...into outfile ...  [I'm 99% sure this will not happen, but always to be prepared for any back fires]

By this way you can be sure for N number of records to be retrieved it taks N number of seconds, and no issues can be faced by doing this way. And whenever you need this to be run next time put the script in cron and have a sound sleep. :) [Ofcourse you have monitoring metrics to wake you up]-> Just to be aware before someone surprises you with the NEWS.
All the best !!


text:
Q: Showing that an action of a group on a set is proper Let $X$ represent the set = $\{1, 2, 3, 4, 5, 6, 7, 8\}$
Then the elements of the symmetry group (Dihedral Group- $D_8$) permute the elements of the set.
How do I show that the action of $D_8$ on the set is proper?
I understand that the group G must be a topological group (which is continuous) and so it must therefore be infinite.
What I am stuck on is that the group is not infinite.
I have used this website but I am unsure of what I am doing wrong.
Thank you for reading.

A: I would think that you would include:
G×X->X×X(g,x)|->(gx,x) and relate it to the answer, although I cannot be certain.
Sorry :P


text:
Q: MySQL singling out multiple rows I have a database which logs users events.
A simplified table looks like this
userid    eventtype     lastupdate
1          sent          5
1          opened        10
1          clicked       15
2          sent          5
3          sent          5

I'm trying to get the userid's that have the sent eventtype but not the opened OR clicked eventtype between a range of lastupdate.
SELECT * FROM table WHERE (`eventtype` != "opened" AND (`lastupdate` BETWEEN 0 AND 10)) OR (`eventtype` != "clicked" AND (`lastupdate` BETWEEN 0 AND 10))

Is as far as I got, but will obviously not work since it will grab userid 1, 2 and 3.
While I want it to grab only 2 and 3.
The actual table is much more complicated as it also has to work with joins and some other columns, but if we can figure this part out I can do the rest.

A: If you want to find out the user_ids and I take your question literal, then this should be what you are looking for:
SELECT user_id
  FROM events
  WHERE eventtype NOT IN ('opened', 'clicked')
    AND lastupdate BETWEEN 0 AND 10
  GROUP BY user_id;

This indeed will also select user_ids 2 and 3, since they too have sent matching events...

A: Try this without any exists clauses, maybe it suits your needs
   select *
   from tst
   where userid not in (
   select userid from tst where eventtype in ('opened', 'clicked'))
   and lastupdate between 0 and 10;

Tested it: sqlfiddle

A: You can do it using NOT EXISTS:
SELECT *
FROM mytable AS t1
WHERE lastupdate BETWEEN 0 AND 10
      AND eventtype = 'sent'
      AND NOT EXISTS (SELECT 1
                      FROM mytable AS t2
                      WHERE t1.userid = t2.userid
                            AND t2.lastupdate BETWEEN 0 AND 10
                            AND t2.eventtype IN ('opened', 'clicked'))

The above will select users:

*

*whose lastupdate is BETWEEN 0 AND 10 and

*have in this interval an eventtype = 'sent' and

*don't have an eventtype IN ('opened', 'clicked') within the same interval.

Demo here


text:
Q: Why hasMany Relation still working even i removed relation in Laravel

In the above both models i commented the method  itemDestribution()  but still it is working

A: This relation displays a Data because of following reasons.

*

*In your ItemDestributionModel, You have set relation with UserModel and ItemModel both.

*In your ItemModel and UserModel you haven't declare any public function and add Relation Class.
When you call UserModel it will find hasMany Relationship in ItemDestributionModel and user() function is available with belongsTo relationship.
That's why laravel fetch data without declaring public function. But you should declare relationship inside public function. :)


text:
Q: How to change width of colored progress bar with background linear? I have this css and html code.
My problem is that I see always linear color except color which I defined to 60% as green. From 0 - 60% of width I want to see only green and not others. I thought that when bar is defined as background-image then it will work, but its not.

.bar-line {
    width: 100%;
    min-width: 120px;
    display:inline-block;
    position:relative;
    vertical-align: middle;
    color: #000;
    background-color: #f1f1f1;
}
.bar-container {
    padding: 0;
    min-height: 24px;
    max-width: 100%;
    color: #000;
    background-image: linear-gradient(to right, green 60%, yellow 85%, red 95%);
}
.bar-container:after, .bar-container:before {
    content: "";
    display: table;
    clear: both;
}
.bar-container span {
    position: absolute;
    left: 5px;
}

        30%

How to do it without JS?

A: Although it is more nice to do the html part different

   .bar-line {
    position: relative;
    width: 100%;
    height: 24px;
    display:inline-block;
    position:relative;
    vertical-align: middle;
    color: #000;
    background-image: linear-gradient(to right, green 60%, yellow 85%, red 95%);
    overflow: hidden;
}
.bar-container {
  position: absolute;
  top: 0;
  left: 0;
  padding: 0;
  min-height: 24px;
  z-index: 0;
}

.bar-container span {
  text-indent: -100%;
  display: block;
  background-color: #f1f1f1;
  position: absolute;
  top: 0;
  bottom: 0;
  width: 1000vh;
  right: -1000vh;
  z-index:1;
}

        30%

Just change the width value and see the result :).
The dirty trick here is to have a very large span, positioned after the bar-container and overlaying the rest of the colored bar-line

A: Use multiple background and adjust the background-size:

.bar-line {
    width: 100%;
    min-width: 120px;
    margin-bottom:10px;
    display:inline-block;
    position:relative;
    vertical-align: middle;
    color: #000;
    background-color: #f1f1f1;
}
.bar-container {
    padding: 0;
    min-height: 24px;
    max-width: 100%;
    color: #000;
    background:
      linear-gradient(#f1f1f1,#f1f1f1) right/calc(100% - var(--d)) 100% no-repeat,
      linear-gradient(to right, green 60%, yellow 85%, red 95%);
}

.bar-container span {
    position: absolute;
    left: 5px;
}

        30%

        50%

        80%


text:
Q: Is the search bar in desktop Unity 8 really going to be on the right side? I noticed that, at least in the tablet version of Unity 8, the search bar is on the right side of the screen. However, people keep telling that the desktop version will come afterwards, so I don't know if that's the intended place for it to be across versions. I hope not, because it's a major UI problem.
This is the way Windows 8 does it, and it's terrible, because as you type on it (on the right side), the results appear on the left side, so your eyes have to move across the screen all the time, especially if your screen is a large one.
I know one can ask "but isn't that where search bars have been all along? Firefox and Windows Explorer etc.
Well, not quite. On these programs, it's intended that you finish your search key and then type Enter and only so look for the results. Unity's search bar, however, shows results dynamically, so you always want to look at the results, so you know if you can press Enter without having to write the whole sentence, and you also want to look at what you're typing, so you know there are no typos.
That being said, I wanted to know if this is really where the search bar will be and if it will not spread across the top part of the screen (that would be a good solution, since "Home Scope" and other scope titles don't need to be showing when you're typing). If that's final, then I will fill a bug.

A: I think the idea is that Unity will adapt itself to the different sort of screen it is running on and will change the location of the search text area so it is different on a phone and a laptop.


text:
Q: A counterexample to Weyl theorem on complete reducibility A well known result from Lie algebras' representations is the Weyl Theorem (Theorem 6.3 of Humphreys' Introduction to Lie Algebras and Representation Theory), which states the following:

Let $\phi: \mathfrak{g} \to \mathfrak{gl}(V)$ be a (finite dimensional) representation of a semisimple Lie algebra. Then $\phi$ is completely reducible.

In the context of the book, $\mathfrak{g}$ is a finite dimensional Lie algebra. My question is: Is there some (easy, in the sense that do not demand too much previous knowledge) example of a finite-dimensional representation of an infinite-dimensional semisimple Lie algebra that is not completely reducible?


text:
Q: How to get every possible distinct combination? Given the following
CREATE TABLE #Test
(
ItemName VARCHAR(2)
);

INSERT INTO #Test (ItemName)
VALUES  ('x1'),
    ('x2'),
    ('x3'),
    ('x4');

How can I get every possible combination regardless of the order of the values? For example x1, x2 is the same as x2, x1 so I don't need both. Also, x1, x2, x3 would be the same as x3, x1, x2 or x2, x1, x3
The output would be:
x1, x2
x1, x3
x1, x4
x2, x3
x2, x4
x3, x4
x1, x2, x3
x1, x2, x4
x1, x3, x4
x2, x3, x4
x1, x2, x3, x4
My values would probably go to x16 so I'm trying to keep this simple for the sake of the example.
I've read a bunch of similar questions, but they all stop with combining just 2 values.
Thanks!


text:
Q: How to solve " ImportError: No module named mechanize " I have mechanize module into required folder and still showing problems...
How to solve " ImportError: No module named mechanize "
i saw these:
import mechanize
ImportError: No module named mechanize

import mechanize
ImportError: No module named mechanize

noobs = mechanize.Browser()
NameError: global name 'mechanize' is not defined


text:
Q: Implementation of Planar Point Location using slabs I am looking into a Planar Point Location, and right now thinking about make use of The Slabs approach.
I've read through a couple of articles:

*

*Planar Point Location Using Persistent Search Trees

*Persistent Data Structures

*Point location on Wikipedia
I understand the concept behind a persistent balanced binary search tree, but let's omit them in this question, I don't really care about extra storage space overhead. The thing with the articles is they are discussing how speed can be improved, but don't explain basic stuff. For example:
Could you please correct me if I am wrong:

*

*We draw a line across all intersections.

*Now, we have slabs that are split by the segments at different angles.

*Every intersection with any line is considered a vertex.

*Slabs are sorted by order in a binary search tree (let's omit a partially persistent bst)

*Somehow, sectors are sorted in those respective BST's, even though the segments dividing them are almost always at an angle. Does each node has to carry a definition of area?

Please refer to this example image:

Questions:

*

*How would I actually figure out if the point lies in Node c and not in Node b? Is it somehow via area?

*Do I instead need arrange my nodes to contain information about the segments? I could then check if the query point lies above a segment (if that's how I should determine my sectors)? If so, would I then search through a Polygon List after, to see which polygon this particular segment belongs to?

*Maybe I need to store BST for each line and not a slab?

*Would I then have to look at 2 BST's belonging to line on the left, and the 2nd one of the line to the right from the vertex? I could then sort the vertexes by y coordinate in each tree and return the y coordinate of a vertex (the end of a segment) right below my query point. Having done this for left and right line, I would then do a comparison to see if the names of the segment those vertexes come from actually match.

*However, this will not give me the right answer, since even if the names do match, I might be below or above the segment (if I am close to it). Also, this implies I have to do 3 binary searches (1 for lines, 1 for the y-coordinate on left line, 1 for the right one), and the books says I only need to do 2 searches (1 for slab, 2nd for sector).
Could someone please point me in the direction to do it?
I probably just missed some essential thought or something.
Edit:
Here is another good article, that explains the solution to the problem, however, I don't quite understand how I would achieve the following:
"Consider any query point q ∈ R2. To find the face of G that contains q, we first use binary search with the x-coordinate of q to find the vertical slab s that contains q. Given s, we use binary search with the y-coordinate of q to find the edges of Es between which q lies. "
How exactly to find those 2 edges? Is it as simple as checking if the point lies below the segment? However, this seems like a complicated check to do (and expensive), as we descend down the tree, inspecting the other nodes.

A: Well, this was asked a year ago so I guess you're not going to be around to accept the answer.  It's a fun question, though, so here goes anyway...

*

*Yes, you can divide the plane into slabs using vertical lines through every intersection.  The important result is that all line segments that touch a slab will go all the way through, and the order of those line segments will be the same across the entire slab.

*In each slab, you make a binary search tree of those line segments, ordered by their order in the slab.  The areas that you call "nodes" are the leaves of the tree, and the line segments are the internal nodes.  I will call the leaves "areas" to avoid ambiguity.  Since the order of the line segments is the same across the entire slab, the order in this tree is valid for every x coordinate in the slab.

*to determine the area that contains any point, you find the slab that contains the point, and then do a simple search in the BST to find the area.

*Lets say you're looking for point C, and you're at the node in slab 2 that contains (x2,y2) - (x3,y4). Determine whether C is above or below this line segment, and then take that branch in the tree.
For example, if C is (cx,cy) then the y coordinate of the segment at x=cx is:
testy = ((cx-x2)/(x3-x2)) * (y4-y2) + y2
If cy < testy, then take the upward branch, otherwise take the downward branch. (assuming positive Y goes downward).
When you get to a leaf, that's the area that contains C.  You're done.
Now... Making a whole new tree for every slab takes a lot of space, since you can have N^2 intersection points and therefore N^2 slabs.  Storing a separate tree in every slab would take O(N^3) space.
Using, say, persistent red-black trees, however, the slabs can actually share a lot of nodes.  Using a simple purely functional implementation like Chris Okasaki's red-black tree takes O(log N) space per intersection for a total of O(N^2*log N) space.
I seem to remember that there is also a constant-space-per-change persistent red-black tree that would give you O(N^2), but I don't have a reference.
Note that for most real-life scenarios there are closer to O(N) intersections, because lines don't cross very much, but it's still nice to save the space by using a persistent tree.


text:
Q: jQuery code works for console but not in-page I have a form element defined as:

            Last name: *

        <%= Html.TextBox("User.LastName", Model.LastName)%>
        <%= Html.ValidationMessage("User.LastName")%>

and a jQuery selector that is supposed to detect when the input gets focus and highlight the parent:
    $("input").focus(function() {
    //watching for an event where an input form comes into focus
        $(this).parent().addClass("curFocus").children("div").toggle();
    });

If i paste this code into firebug's console - things work as planned. However, i'm running this from a 'RenderPartial' .net mvc page. Other jQuery code sitting within the same      $(document).ready(function() { block work correctly.
The form uses html helpers to generate the inputs which might complicate the process somewhat - but even so... i'm seeing correct behavior when that code's in console but not in a 'real-time' page.
How do i troubleshoot this?

A: When you're rendering a partial, the $("input") selector doesn't find the element to rig this up to, because it isn't there yet.  If you change it to a live event, it'll work on elements added after document.ready executes.
To fix it, use .live() like this:
$("input").live('focus', function() {
  $(this).parent().addClass("curFocus").children("div").toggle();
});

Note: requires jQuery 1.4.1+

A: Use setTimeOut
  setOut(function(){
        $("input").focus(function() {
             //watching for an event where an input form comes into focus
             $(this).parent().addClass("curFocus").children("div").toggle();
        });
  },500)


text:
Q: Proving that $ \mid z+1\mid^{2}=2\mid z\mid^{2} \Leftrightarrow \mid z-1\mid^{2}=2 $ Let z be a complex number.
How does one prove, using the properties of the conjugate and the modulus, that:
$$ \mid z+1\mid^{2}=2\mid z\mid^{2}
\Leftrightarrow
\mid z-1\mid^{2}=2 $$

A: Hint: Use (three times) the fact that $|z|^2=z.\overline z$.

A: The two esential properties that you have to use are $\overline{w_1 + w_2} = \overline{w_1} + \overline{w_2}$ and ${|w|}^2 = w \overline{w}$ for each $w , w_1 , w_2 \in \mathbb{C}$.
Fix $z \in \mathbb{C}$. With these two properties, you should see that (as $z + \overline{z} = 2 Re z$)
$$
{|z + 1|}^2 = {|z|}^2 + 2 (Re z) + 1 \qquad \mbox{ and } \qquad {|z - 1|}^2 = {|z|}^2 - 2 (Re z) + 1\mbox{.}
$$
Thus,
$$
{|z + 1|}^2 = 2 {|z|}^2 \quad \Longleftrightarrow \quad {|z|}^2 = 2 (Re z) + 1 \quad \Longleftrightarrow \quad {|z - 1|}^2 = 2\mbox{.}
$$

A: An elementary solution:
First, note that $|x+iy|^2=x^2+y^2,|x+1+iy|^2=x^2+2x+1+y^2$, and $|z-1  |^2=(x-1)^2+y^2.$
We have then
$$ x^2+2x+1+y^2=2x^2+2y^2$$
or $$x^2-2x+1-2+y^2=0$$
which is equivalent with the following
$$(x-1)^2+y^2=2$$
and again, this is what we needed
$$|z-1  |^2=2.$$


text:
Q: Python 3.xx - Deleting consecutive numbers/letters from a string I actually need help evaluating what is going on with the code which I wrote.
It is meant to function like this:
input: remove_duple('WubbaLubbaDubDub')

output: 'WubaLubaDubDub'

another example:
input: remove_duple('aabbccdd')

output: 'abcd'

I am still a beginner and I would like to know both what is wrong with my code and an easier way to do it. (There are some lines in the code which were part of my efforts to visualize what was happening and debug it)
def remove_duple(string):
    to_test = list(string)
    print (to_test)
    icount = 0
    dcount = icount + 1
    for char in to_test:
        if to_test[icount] == to_test[dcount]:
            del to_test[dcount]
            print ('duplicate deleted')
            print (to_test)
            icount += 1
        elif to_test[icount] != to_test[dcount]:
            print ('no duplicated deleted')
            print (to_test)
            icount += 1
    print ("".join(to_test))

A: Don't modify a list (e.g. del to_test[dcount]) that you are iterating over. Your iterator will get screwed up. The appropriate way to deal with this would be to create a new list with only the values you want.
A fix for your code could look like:
In []:
def remove_duple(s):
    new_list = []
    for i in range(len(s)-1):  # one less than length to avoid IndexError
        if s[i] != s[i+1]:
            new_list.append(s[i])
    if s:                      # handle passing in an empty string
        new_list.append(s[-1]) # need to add the last character

    return "".join(new_list)   # return it (print it outside the function)

remove_duple('WubbaLubbaDubDub')

Out[]:
WubaLubaDubDub

As you are looking to step through the string, sliding 2 characters at a time, you can do that simply by ziping the string with itself shifted one, and adding the first character if the 2 characters are not equal, e.g.:
In []:
import itertools as it

def remove_duple(s):
    return ''.join(x for x, y in it.zip_longest(s, s[1:]) if x != y)

remove_duple('WubbaLubbaDubDub')

Out[]:
'WubaLubaDubDub'

In []:
remove_duple('aabbccdd')

Out[]:
'abcd'

Note: you need itertools.zip_longest() or you will drop the last character. The default fillvalue of None is fine for a string.


text:
Q: Does high heat make a boiling pot of water evaporate faster? According to another answer, the rate at which water evaporates depends on

the temperature of both air and water, the humidity of the air, and the size of the surface exposed.

The air temperature, humidity, and surface area are all essentially constant. The water temperature is too–roughly 100ºC, right?
So am I correct in thinking that whether I set my stove to medium or high, as long as the water is boiling, the evaporation rate is constant?

A: You are mixing two phenomena: boiling that occurs within the bulk and indeed only at 100°C at atmospheric pressure, and evaporation that can happen at any temperature and is a surface phenomenon.
However, if you are strictly speaking about boiling, the boiling rate depends on the energy you input into your system. If you put your stove from medium to high, your water will stay at 100°C but will boil faster (by this I mean that more water gets converted into vapor per second) because you input more energy per second into your system.
In fact, the enthalpy of vaporization of water is 2257 kJ/kg, which means that you need 2257 kJ of energy to vaporize 1 kg of water at 100°C and atmospheric pressure. Imagine you want to boil 1 kg of water with a 2 kW heating plate. The minimum time required to boil the entire quantity would be
$$t = \frac{2257\ kJ}{2\ kW} \approx 1000\ \text{seconds}$$ which is about fifteen minutes. In fact you need more time than that because of all the energy losses through radiation, diffusion in surrounding materials...


text:
Q: Django REST Framework - query limit on nested serializer? I have a situation in which one table is related to another via a foreign key as follows:
models.py
class Container(models.Model):
    size  = models.CharField(max_length=20)
    shape = models.CharField(max_length=20)

class Item(models.Model):
    container = models.ForeignKey(Container, related_name='items')
    name  = models.CharField(max_length=20)
    color = models.CharField(max_length=20)

serializers.py
class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item

class ContainerSerializer(serializers.ModelSerializer):
    items = ItemSerializer(many=True)

    class Meta:
        model = Container
        fields = ('size', 'shape', 'items')

This works fine, but my problem is that all the items in the container get serialized.  I only want items with color='green' to be serialized.

A: class ContainerSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()

    def get_items(self, obj):
        query = Item.objects.filter(item_set__color='green')
        serializer = ItemSerializer(query, many=True)
        return serializer.data

    class Meta:
        model = Container
        fields = ('size', 'shape', 'items')

A: Instead of changing how serializer works, a simplier way, its just filter you Container with green color items and them try to serialize it
You can do something like this:
container_objects = Container.objects.filter(id='your_container_id',item_set__color='green')
serialized_containers = YourContainerSerializer(data=container_objects)


text:
Q: Is there a function for sleeping a set amount in C++ for windows? I know there is one in C, Sleep(ms), but is there one for C++? I am trying to return an error, then print to the console, then sleep enough for the user to read it before returning the errorcode. Code in C would be:
#include <stdio.h>
#include <windows.h>

int main (int argc, const char *argv[]) {
  char *err = "Have an error!";
  printf("Error: %s. Program terminating in 5 seconds...", err);
  Sleep(5000);
  return 1;
}

A: You could include <windows.h> and just call the WinApi function Sleep just as you would from C. This is mostly pure C++ :
#include <iostream>
#include <string>
#include <chrono>
#include <thread>

using namespace std;

int main (int argc, const char *argv[]) {
   string err = "Have an error!";
   cout << "Error: " << err << ". Program terminating in 5 seconds..." << endl;

   std::chrono::milliseconds timespan(5000);
   std::this_thread::sleep_for(timespan);

  return 1;
}


text:
Q: Why is the modal dialog in MFC actually internally modeless? This question arose in my miind after reading this article: http://www.codeproject.com/Articles/3911/The-singular-non-modality-of-MFC-modal-dialogs. He mentions that the modal dialog in MFC is not strictly modal, but implemented as a modeless dialog(internally) with bells and whistles to make it behave as a modal one.
Specifically, he says:

The MFC command routing mechanism uses a combination of message maps
  and virtual functions to achieve what it does and a true modal dialog
  will totally wreck this mechanism because then the modal message loop
  is controlled outside the scope of the MFC command routing machinery

Could anyone elucidate this statement? An example of what would have gone wrong if they had tried to implement a truly modal dialog would greatly clear things up.

A: A modal dialog stops your message loop, but there must still be a message loop to handle the events for the dialog. So a modal dialog simply a non-modal dialog with its own internal message loop.


text:
Q: Any efficient solution for that   declare

       cursor cur1 is select * from address where aid in
        (select Min(aid) from address group by
        country,state,city,street_name,locality,house_no);

       cursor cur2 is select * from address;

        cur1_aid                address.aid%type;
        cur1_country            address.country%type;
        cur1_city               address.city%type;
        cur1_state              address.state%type;
        cur1_streetAddress      address.street_name%type;
        cur1_locality           address.locality%type;
        cur1_houseNo            address.house_no%type;

        cur2_aid                address.aid%type;
        cur2_country            address.country%type;
        cur2_city               address.city%type;
        cur2_state              address.state%type;
        cur2_streetAddress      address.street_name%type;
        cur2_locality           address.locality%type;
        cur2_houseNo            address.house_no%type;

begin
         open cur1;
            loop
            fetch cur1 into cur1_aid,cur1_country,cur1_state,cur1_city,cur1_streetAddress,cur1_locality,cur1_houseNo;
            exit when cur1%NOTFOUND;
                open cur2;
                    loop
                    fetch cur2 into  cur2_aid,cur2_country,cur2_state,cur2_city,cur2_streetAddress,cur2_locality,cur2_houseNo;
                    exit when cur2%NOTFOUND;
                        if(cur1_country=cur2_country) and (cur1_state=cur2_state) and (cur1_city=cur2_city) and (cur1_streetAddress=cur2_streetAddress) and (cur1_locality=cur2_locality) and (cur1_houseNo=cur2_houseNo) then
                            if (cur1_aid!=cur2_aid) then
                                    update employee_add set aid=cur1_aid where aid=cur2_aid;
                                    delete address where aid=cur2_aid;
                            end if;
                        end if;
                    end loop;
                close cur2;
            end loop;
        close cur1;
    DELETE FROM employee_add a
    WHERE ROWID > (SELECT MIN(ROWID) FROM employee_add b
    WHERE b.eid=a.eid and b.aid=a.aid
    );
    end;
    /

I have three table Employee(eid,ename) ,Address(aid,country,state,city,streetaddress,locality,houseNo) and a relationship table (M2M) MANY TO MANY TABLE employee_add(eid,aid),
I want to remove duplicates from address table and employee_add table without data loss

A: Assuming this is a one time de-duplication you could:

*

*Create a new temporary set of eid <-> aid relationships based on the current address attached to an employee and always pick the min address record with matching data (this is what you are doing above)

*Delete existing eid <-> aid relationships

*Insert new relationships from step 1, drop step 1 data

*Delete addresses that no longer have any employee attached

Something like this (untested as you did not provide any DDL or DML to create a working example from):
-- Step 1
CREATE TABLE employee_add_new AS
  SELECT ea.eid,
         (SELECT MIN(a2.aid)
            FROM address a2
           WHERE a2.country = a.country
             AND a2.state = a.state
             AND a2.city = a.city
             AND a2.street_name = a.street_name
             AND a2.locality = a.locality
             AND a2.house_no = a.house_no) AS aid
    FROM employee_add ea
   INNER JOIN address a
      ON a.aid = ea.aid;

-- Step 2
TRUNCATE TABLE employee_add;

-- Step 3
INSERT INTO employee_add
  (eid,
   aid)
  SELECT eid,
         aid
    FROM employee_add_new;

DROP TABLE employee_add_new;

-- Step 4
DELETE FROM address a
 WHERE NOT EXISTS (SELECT NULL
          FROM employee_add ea
         WHERE ea.aid = a.aid);

You could also change step 2 and 3 to drop the existing employee_add table and rename employee_add_new to employee_add, but I have no idea what your table structure looks like (columns, FKs, indexes, etc).


text:
Q: How to adjust intraday bar prices for split, dividends etc. in rbbg? Is there a friendly and knowledgeable person out there with experience in the R "Rbbg" library (wrapper for connecting Bloomberg's API to R)? I have create code all the library's functions (bdh, bdp and bds) and moved to the "bar" function which is used to extract intraday bar prices on securities.
Everything went well until pulled 5-minutes bar data on Apple since 2014-01-01 (see code example below). The function extracts the unadjusted prices which make them useless as Apple introduced a 7:1 split not long ago.

library(Rbbg)
conn <- blpConnect()
prices <- bar(conn, "AAPL US Equity", "TRADE", "2014-01-01 09:30:00.000", "2014-06-24 16:00:00.000", "5")
print(conn$BOOLEAN_OPTION_NAMES)

According to the Rbbg manual PDF (p. 15) it is possible to use Option Settings to make changes to the output. The last line in the code example gives you a string named "adjustmentFollowDPDF" which should be set with a following boolean value. This option is possible within the "bdh" function for historical data with "DAILY" as the highest frequency.
The DPDF is a function in the Bloomberg Terminal to set your adjustment configuration. So the API should allow to import these settings in your data query.
I have tried all possible combinations to include the "adjustmentFollowDPDF" in the "bar" function without luck.
Is there anyone out there that experience in this field. Without adjusted prices the "bar" function is completely useless and wrong.
UPDATE: I just want to let everyone know that the issue is solved by the kind people that still maintains the "Rbgg" package.


text:
Q: Add language to Sublime 3.2.2 GPSS language support is provided at:
https://github.com/dseight/Sublime-GPSS-H
Questions:

*

*Which directory destination should be selected for the github clone?

*What Sublime steps are required to configure.GPS an .LIS files to be recognized as GPSS input / output files?


text:
Q: resume for XID raised 0: unknown I am using Spring 3.0.5, Hibernate 3.6.7, Atomikos TransactionEssentials 3.7.0 and MySQL 5.5
I recently faced the problem, that connections in my connectionpool timedout after 8 hours and were reset by the server causing a message "resume for XID '???' raised 0: unknown
Here is my datasource configuration:
<bean id="myDataSource"
      class="com.atomikos.jdbc.AtomikosDataSourceBean"
      init-method="init"
      destroy-method="close"
      depends-on="myConfigurer">
    <property name="uniqueResourceName" value="myPUDataSource" />
    <property name="xaDataSourceClassName" value="$CONF{database.XAdriver}" />
    <property name="poolSize" value="10" />
    <property name="xaProperties">
        <props>
            <prop key="user">$CONF{database.user}</prop>
            <prop key="password">$CONF{database.password}</prop>
            <prop key="URL">$CONF{database.url}</prop>
            <prop key="pinGlobalTxToPhysicalConnection">true</prop>
            <prop key="autoReconnect">true</prop>
        </props>
    </property>
</bean>

As I was investigating I found out that the option autoReconnect=true only reconnects my faulted connection after a delay of 2 seconds (which is configurabe I think).
Browsing the web I found solutions suggesting to increase wait_timeout in the MySQL-Server, which I think is not a real solution.
The application should be able to handle dead connections and reconnect automatically, because there may be other issues causing a connection loss, too.
(And I don't want to make any directives to Servers whatever kind the application uses).
At last I found a good solution for this, which I will post as answer to help people facing the same or similar problems.

A: By inserting the line:
<property name="testQuery" value="SELECT 1"/>

on the data source's configuration, it seems the connection is tested before use and reconnected if it's dead.
I tried it with wait_timeout=60 and even with a restart of the MySQL-Server while my application was running...
Result: no more Exceptions and Errors!


text:
Q: How do I inject a constructor dependency into a ViewModel using Xamarin and Autofac? I have a ViewModel and I want to inject another Class into it. I am using Visual Studio with the latest version of Xamarin. I'm using Autofac for registering en resolving dependencies. But I'm new to it and I'm facing a problem which I can't find the solution to, even though it's probably simple.
This is the Class in which I want to inject another Class:
public IMessagingCenterWrapper MessagingCenterWrapper;

public LoginViewModel(IMessagingCenterWrapper messagingCenterWrapper){
            MessagingCenterWrapper = messagingCenterWrapper;
        }

Then in entry point of the app I have a function which initializes the container which registers and resolves dependencies
static IContainer container{ get; set; }

public App ()
        {
            InitializeComponent();

            InitializeIOCContainer();
        }

void InitializeIOCContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<LoginViewModel>();
            builder.RegisterType<MessagingCenterWrapper>().As<IMessagingCenterWrapper>();
            container = builder.Build();

            var wrapper = container.Resolve<IMessagingCenterWrapper>();
            var viewModel = container.Resolve<LoginViewModel>();
        }

But I get an error when building at the line in the login View:
 BindingContext = new LoginViewModel();

I'm getting the error because I don't initialize the parameter in the call.
But if I do that won't I destroy the whole principle of the IoC pattern. Eventually new class calls will be nested with other dependencies and I want to avoid that.
So my question is: how do I actually inject the the class parameter in the constructor?

A: This is actually a service locator injection, since the injected element is a messaging center service.  That's good news.
You don't have to pass in service constructors to view model constructors. Just request the service where you need it:
public LoginViewModel()
{
   MessagingCenterWrapper = App.Container.Resolve<IMessagingCenterWrapper>();
}

Don't stick the view models into AutoFac unless they are indeed global.  There are a lot of problems with this sort of fake IOC.
To make it easier overall, how about this:
// MUST BE PUBLIC
public static IContainer Container{ get; set; }

static App()
{
   InitializeIOCContainer();
}

public App ()
{
   InitializeComponent();
}

private static void InitializeIOCContainer()
{
   var builder = new ContainerBuilder();
   builder.RegisterType<MessagingCenterWrapper>().As<IMessagingCenterWrapper>();
   Container = builder.Build();

   // Don't stick view models in the container unless you need them globally, which is almost never true !!!

   // Don't Resolve the service variable until you need it !!!! }
}

The complete code for these remarks is at https://github.com/marcusts/xamarin-forms-annoyances.  See the solution called AwaitAsyncAntipattern.sln.
The GitHub site also provides links to a more detailed discussion on this topic.


text:
Q: Sql Server 2008 Update query is taking so much time I have a table name Companies with 372370 records.
And there is only one row which has CustomerNo = 'YP20324'.
I an running following query and its taking so much time I waited 5 minutes and it was still running. I couldn't figure out where is the problem.
UPDATE Companies SET UserDefined3 = 'Unzustellbar 13.08.2012' WHERE CustomerNo = 'YP20324'

A: You don't have triggers on update on that table?
Do you have a cascade foreign key based on that column?
Are you sure of the performance of your server? try to take a look of the memory, cpu first when you execute the query (for example on a 386 with 640mb i could understand it's slow :p)
And for the locks, you can right click the database and on the report you can see the blocking transactions. Sometimes it helps for concurrent access.

A: Try adding an index on the field you are using in your WHERE clause:
CREATE INDEX ix_CompaniesCustomerNo ON Companies(CustomerNo);

Also check if there are other active queries which might block the update.

A: Try this SQL and see what is running:
SELECT TOP 20
        R.session_id, R.status, R.start_time, R.command, Q.text
FROM
        sys.dm_exec_requests R
        CROSS APPLY sys.dm_exec_sql_text(R.sql_handle) Q
WHERE R.status in ('runnable')
ORDER BY R.start_time

More details:
List the queries running on SQL Server
or
http://sqlhint.com/sqlserver/scripts/tsql/list-long-running-queries
Once I found someone shrinking database and blocking all other people.

A: More likely than not your UPDATE is not doing anything, is just waiting, blocked by some other statement. Use Activity Monitor to investigate what is causing the blocking. Most likely you have another statement that started a transaction and you forgot to close it.
There could be other causes too, eg.  database/log growth. Only you can do the investigation. An index on CustomerNo is required, true, but lack of an index is unlikely to explain 5 minutes on 370k records. Blocking is more likely.
There are more advanced tools out there like sp_whoisactive.

A: 5mn is way too long for 370k rows, even without any indexes, someone else is locking your update. use sp_who2 (or activity monitor) and check for BlockedBy Column to find who is locking your update

A: I would suggest to rebuild your indexes. This should surely help you.
If you do not have index on CustomerNo field you must add one.

A: In my case, there was a process that was blocking the update;
Run: 'EXEC sp_who;'
Find the process that is blocked by inspecting the 'blk' column; Let's say that we find a process that is blocked by '73';
Inspect the record with column 'spid' = '73' and if it's not important, run 'kill 73';

A: 370k records is nothing for sql erver. You should check indexes on this table. Each index makes update operation longer.


text:
Q: "Type a tag" text cut off I've noticed that the background text "Type a tag" at the bottom of the "Ask Question" page is cut off:

Reproduced in Microsoft Edge.

A: Fixed on Friday Sept. 14 - code intended for the internal Teams editor snuck into the public sites without associated styles (or consideration of what guidance is needed for tagging on public sites). Jisoo corrected this by limiting this behavior to Teams.


text:
Q: Difference between OpenGL files glew.h and gl.h/glu.h I've built an OpenGL program with my glu and gl header files default included in windows 7 professional edition. Now, I've bought a book that describes OpenGL game development. The author of this book said, I have to include the glew header into my project. After I've done this I got some unresolved external symbol errors.
So, now I'm really confused.
I've worked earlier with glBegin and glEnd statements in my program. Now I've to work with glBindBuffers and glGenBuffer etcetera, but I get the unresolved external symbol errors, like that:
1>cWindows.obj : error LNK2001: unresolved external symbol __imp___glewBindBuffer
1>cMdlLoader.obj : error LNK2001: unresolved external symbol __imp___glewBindBuffer
1>cMdlLoader.obj : error LNK2001: unresolved external symbol __imp___glewBufferData
1>cMdlLoader.obj : error LNK2001: unresolved external symbol __imp___glewGenBuffers

Is there anyone here who can explain the difference between these header files and what I have to do with them?
I goggled many times, but on different sites there are much more confusing words like "glee" or "glut".

A: You're mixing up 3 different things here:

*

*OpenGL

*the GL Utilities (GLU) which are not part of OpenGL

*and the GL Extension Wrangler (GLEW)

GLEW and GLU are completely different things and you can not replace one with another.
GL/gl.h are the base OpenGL headers, which give you OpenGL-1.1 function and token declarations, any maybe more. For anything going beyond version 1.1 you must use the OpenGL extension mechanism. Since this is a boring and tedious task, that has been automatized by the GLEW project, which offer all the dirty details packed up in a easy to use library. The declarations of this library are found in the header file GL/glew.h. Since OpenGL extensions don't make sense without basic OpenGL, the GLEW header implicitly includes the regular OpenGL header, so as of including GL/glew.h you no longer need to include GL/gl.h.
Then there's GLU, a set of convenience methods, which BTW are seriously outdated and should not be used in any modern OpenGL program. There's no modern GLU, so just forget about it. Anyway, it's declarations are made available by the header GL/glu.h (the one you were asking about).
The errors you get have nothing to do with include files though. Those are linker errors. Just including the declarations is only half of the job. The other half is linking the actual definitions and those are not in the header by the library file; libglew.so or libglew.a on a *nix OS, glew.lib or glew32.lib or glews.lib or glew32s.lib on Windows. If not using the static versions (those without the 's') you also must have installed the right DLL.
So to use GLEW you need to include the header and add it to the list of libraries in the linker options. Also you must call glewInit(); once you've obtained a OpenGL context in your program.

A: *

*gl: This is the base header file for OpenGL version 1.1. That means if you want to use any functionality beyond version 1.1, you have to add any extension library on this.

*glew:  OpenGL Extension Wrangler Library. This is a cross-platform library for loading OpenGL extended functionality. When you initialize this library, it will check your platform and graphic card at run-time to know what functionality can be used in your program.

*glu: This is OpenGL utilities library, which has been not updated for long time. Don't need to use this header file.

*glut: OpenGL Utility Toolkit for Windowing API. This is good for small to medium size OpenGL program. If you need more sophisticated windowing libraries, use native window system toolkits like GTK or Qt for linux machines.

*glfw: OpenGL Frame Work. Another multi-platform library for creating windows and handling events. FreeGlut can be used as an alternative. glfw is designed for game development.

*glm: OpenGL Mathematics. It helps implementing vectors and matrices operations.

I am very new to OpenGL stuff, so please correct me if I'm wrong.


text:
Q: Summary by Row of a Categorical Variable in R I have the following matrix
coin.flip<-expand.grid(c("H","T"),c("H","T"),c("H","T"),c("H","T"))

> coin.flip
   Var1 Var2 Var3 Var4
1     H    H    H    H
2     T    H    H    H
3     H    T    H    H
4     T    T    H    H
5     H    H    T    H
6     T    H    T    H
7     H    T    T    H
8     T    T    T    H
9     H    H    H    T
10    T    H    H    T
11    H    T    H    T
12    T    T    H    T
13    H    H    T    T
14    T    H    T    T
15    H    T    T    T
16    T    T    T    T

I would like to get a row by row summary of the counts of H's and T's. I would also like a table of how many row's had 1 T, 2 T's, etc...
Thanks a lot! I've been searching for this answer for a little bit and haven't found anything yet.

A: > coin.flip$total_H <- rowSums(coin.flip=="H")
> coin.flip
   Var1 Var2 Var3 Var4 total_H
1     H    H    H    H       4
2     T    H    H    H       3
3     H    T    H    H       3
4     T    T    H    H       2
5     H    H    T    H       3
....snipped
> table(coin.flip$total_H)

0 1 2 3 4
1 4 6 4 1

Total T's table is just
> table(4- coin.flip$total_H )

0 1 2 3 4
1 4 6 4 1     # boringly similar to total H table

A: Here's an way using apply and then table:
rs <- t(apply(coin.flip,1,function(x){c(length(which(x=='H')),length(which(x=='T')))}))
table(rs[,2])

I transposed the results from apply since that's the way you probably expect them displayed.

A: Strictly coin.flip is a data.frame not a matrix.
You could use DWin's solution.  Another approach is
> summary(t(coin.flip))
 V1    V2    V3    V4    V5    V6    V7    V8    V9    V10   V11   V12   V13   V14   V15   V16
 H:4   H:3   H:3   H:2   H:3   H:2   H:2   H:1   H:3   H:2   H:2   H:1   H:2   H:1   H:1   T:4
       T:1   T:1   T:2   T:1   T:2   T:2   T:3   T:1   T:2   T:2   T:3   T:2   T:3   T:3

To get the table quickly, combine the answers from DWin and joran
> table(rowSums(coin.flip=="T"))

0 1 2 3 4
1 4 6 4 1


text:
Q: Java - why does char get implicitly cast to byte (and short) primitive, when it shouldn't? Certain functionality of the compiler puzzles me (Oracle JDK 1.7 using Eclipse).
So I've got this book that says char primitive needs to be explicitly cast to short and byte and this all makes sense due the data types' allowed ranges don't overlap.
In other words below code works (but wouldn't work without the explicit type casts):
char c = '&';
byte b = (byte)c;
short s = (short)c;

Printing b or s correctly displays the number 38, which is the numeric equivalent of (&) in Unicode.
Which brings me to my actual question. Why does the following work as well?
byte bc = '&';
short sc = '&';
System.out.println(bc); // Correctly displays number 38 on the console
System.out.println(sc); // Correctly displays number 38 on the console

Now I would certainly understand the following (which works too):
byte bt = (byte)'&';
System.out.println(bt); // Correctly displays number 38 on the console

But this no-compiler-warning char to byte (and short) "sneak conversion" doesn't seem right to me.
Can some one explain, why this is allowed?
Could the reason be in the interpretation of the '<char>' itself, so that it doesn't actually ever get to a char primitive state but is handled as a numeric (octal or hexadecimal etc) value?

A: Basically, the specification of assignment conversion specifies that

In addition, if the expression is a constant expression (§15.28) of
  type byte, short, char, or int:
A narrowing primitive conversion may be used if the type of the
  variable is byte, short, or char, and the value of the constant
  expression is representable in the type of the variable.

Your '&' is precisely "a constant expression of type byte, short, char, or int".

A: This is called compile-time narrowing of constants. It is described in section 5.2 of the Java Language Specification:

The compile-time narrowing of constants means that code such as:
byte theAnswer = 42;

is allowed. Without the narrowing, the fact that the integer literal 42 has type int would
  mean that a cast to byte would be required.

Same goes for character literals: if its value fits in a byte, no conversion is required; if the value does not fit, you must put in a cast, or you would get a compile error.
For example, this would not compile:
byte bc = '\uff12'; // Does not compile without a cast

but this compiles fine:
byte bc = (byte)'\uff12';

A:
Why does the following work as well?

Because '&' is a constant expression whose value fits in byte.
JLS 14.4.2

If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable.

JLS 5.2

Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.
....
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

*

*A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

A: I don't know this explaination is enough or not, but this behavior is defined in the JLS. From the JLS, section 5.2:

In addition, if the expression is a
  constant expression (§15.28) of type
  byte, short, char or int :

*

*A narrowing primitive conversion may
  be used if the type of the variable is
  byte, short, or char, and the value of
  the constant expression is
  representable in the type of the
  variable.

*A narrowing primitive
  conversion followed by a boxing
  conversion may be used if the type of
  the variable is :

*

*Byte and the value
  of the constant expression is
  representable in the type byte.

*Short
  and the value of the constant
  expression is representable in the
  type short.

*Character and the value of
  the constant expression is
  representable in the type char.

A: The expression '&' that is in your initializer for variable bc is a constant expression. The expression c that is in your initializer for variables b and s is not a constant expression. Java performs implicit narrowing conversions of primitives when the context requires it when the value is the result of a constant expression only.


text:
Q: C++ template programming - Deferred function calls I am looking for an elegant solution to the following problem. I have a task struct that I use for deferred function calls.
template <typename T> struct Task1
{
    T Arg1;
    Delegate<T> TaskDelegate;
};

The problem I'm having is this:
Task1<const Foo&> MyTask;

This will result in the parameter being held as a const reference. Does anyone know a nice solution to get round this? I could enforce rules such as the delegate signature always taking const& params but this seems restrictive. I could always have two task structs (one for ref and one for value) but this seems nasty.
The other solution would be to create the following:
template <typename T1, typename T2> struct Task1
{
    T2 Arg1;
    Delegate<T1> TaskDelegate;
};

Is there anyway to default T2 to be the same type as T1? That way whenever I have a method value signature I don't need to have the additional template params.
EDIT:
The template is used for a multithreaded task scheduler. Here is an example:
void MyClass::Populate(const std::string& instrText);

CTaskScheduler::Schedule(Task1<const std::string&>(this, &MyClass::Popluate, "MyString"));

A: You could take a look at the implementation of function<> either in boost or the upcoming standard. As a matter of fact, you can just use function<>. I think that the solution there was (before C++0x) to always store a copy of the arguments, if the user wants reference semantics they can use a reference wrapper.
As to how to get to a value, you can take a look at some simple metafunction to remove const or &:
// Remove reference:
template <typename T>
struct remove_reference {
   typedef T type;
};
template <typename T>
struct remove_reference<T&> {
   typedef T type;
};

Similarly for const.

A: You can use the boost.type_traits library to remove the const-ness of the parameter using boost::remove_const.

A: In addition to boost::type_traits, there is a boos::call_traits library specifically built to handle problems like this.  It also provides mechanisms to avoid the references of references problem.

A: boost::remove_const should help you in this case:
template <typename T> struct Task1
{
    typename boost::remove_const<T>::type Arg1;
    Delegate<T> TaskDelegate;
};

Alternatively, you can avoid using boost if you use template specialization for const types:
template <typename T> struct Task1
{
    T Arg1;
    Delegate<T> TaskDelegate;
};

template <typename T> struct Task1<const T>
{
    T Arg1;
    Delegate<const T> TaskDelegate;
};

(Warning: untested)


text:
Q: Downloading and Caching multiple videos before moving to a new screen in Flutter I have a requirement in a flutter app to play multiple videos in sequence. Basically, one video is played and when I click on a button, the next video should play and so on.
The videos are very short (1-3 seconds) and very small in size. They are stored on Firebase Storage.
The issue is that there can't be any delay in playing the videos. So I am looking for a way to download and cache multiple videos before navigating to the screen that contains the videos.
I have tried using the flutter cache manager like this:
 Future<List<File>> fetchFile(urls) async {

  urls.forEach((url) async {
     var file = await DefaultCacheManager().getSingleFile(url);
     videos.add(file);
   });
   return videos;
}

Here I try to fetch all the videos from a list of urls and then later I use a Future builder and navigate to the next page with the list of videos.
  Navigator.of(context).push(MaterialPageRoute(builder: (context) => LessonScreen(videos)));

But I've faced a lot of problems with this approach, for example videos not playing in order, or not loading at all, or even crashing the app.
Does anyone know how to achieve this with flutter cache manager or any other approach?
Thanks for the help in advance!

A: forEach in Dart is async, so you can't predict execution order of iterations, especially if you have async routines inside the block. If you need to guarantee order with internal async calls use a regular for loop.
for(int i=0;i<urls.length;i++) {
      var file = await DefaultCacheManager().getSingleFile(urls[i]);
      videos.add(file);
    });

This will guarantee videos[] is in the same order as urls[], and that videos[] is populated with File objects before being returned.

A: Another option for anyone with objects that contain video urls, just use a map and reference an ID to ensure it's the correct video:
    Map<String, File> id_with_video_map = Map();
    List<ObjectWithFile> list = await _fireStoreUtils.getObjectsThatHaveVideoFileUrls();

list.forEach((element) async {
          File file = await DefaultCacheManager().getSingleFile(element.video);
          id_with_video_map[element.id] = file; //add the video and associate it with an id
        });

In your widget stack check and display each depending if the file is ready or not:
       id_with_video_map[snapshot.data.id] != null ?
       VideoPlayerThatUsesFiles(id_with_video_map[snapshot.data.id]!) //True, let's pass the video file with it instead of url

                            :

       VideoPlayerThatUsesURLInstead(snapshot.data.url) //false, let's default to the regular video url


text:
Q: Spring Boot deploy on Heroku I have a problem running a spring boot application on Heroku. The application crashes with the following error. Don't know where the problem might be?
    2022-03-11T12:21:22.271773+00:00 heroku[web.1]: State changed from crashed to starting
2022-03-11T12:21:25.029966+00:00 heroku[web.1]: Starting process with command `java -Dserver.port=22103 $JAVA_OPTS -jar target/Vendulka-1.0-SNAPSHOT.jar`
2022-03-11T12:21:25.730599+00:00 app[web.1]: Create a Procfile to customize the command used to run this process: https://devcenter.heroku.com/articles/procfile
2022-03-11T12:21:25.740822+00:00 app[web.1]: Setting JAVA_TOOL_OPTIONS defaults based on dyno size. Custom settings will override them.
2022-03-11T12:21:25.743826+00:00 app[web.1]: Picked up JAVA_TOOL_OPTIONS: -XX:+UseContainerSupport -Xmx300m -Xss512k -XX:CICompilerCount=2 -Dfile.encoding=UTF-8
2022-03-11T12:21:25.785124+00:00 app[web.1]: no main manifest attribute, in target/Vendulka-1.0-SNAPSHOT.jar
2022-03-11T12:21:25.906791+00:00 heroku[web.1]: Process exited with status 1
2022-03-11T12:21:26.402088+00:00 heroku[web.1]: State changed from starting to crashed
2022-03-11T12:21:36.770036+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=cerma.herokuapp.com request_id=44ef8283-7eae-4229-903a-ce32f9dda176 fwd="212.111.4.170" dyno= connect= service= status=503 bytes= protocol=https
2022-03-11T12:21:36.899660+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=cerma.herokuapp.com request_id=21242cc6-f151-4272-bf41-d5aa9b834442 fwd="212.111.4.170" dyno= connect= service= status=503 bytes= protocol=https
2022-03-11T12:21:21.118467+00:00 app[api]: Deploy 8ed3929c by user tcermak4@gmail.com
2022-03-11T12:21:21.118467+00:00 app[api]: Release v13 created by user tcermak4@gmail.com
2022-03-11T12:21:23.000000+00:00 app[api]: Build succeeded
2022-03-11T12:22:17.417029+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=cerma.herokuapp.com request_id=8225fdab-1ffb-447a-a035-da3804e9305f fwd="212.111.4.170" dyno= connect= service= status=503 bytes= protocol=https
2022-03-11T12:22:17.883392+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=cerma.herokuapp.com request_id=fbe85224-b825-4c5d-be85-3d0e50e633d1 fwd="212.111.4.170" dyno= connect= service= status=503 bytes= protocol=https
2022-03-11T12:22:18.132872+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=cerma.herokuapp.com request_id=cab1a218-f1df-443f-9fce-f32d76ac1830 fwd="212.111.4.170" dyno= connect= service= status=503 bytes= protocol=https

A: The error is no main manifest attribute which means the jar file does not have the Main-Class attribute, see Setting an Application's Entry Point
As you are using Springboot you can use the spring-boot-maven-plugin and set the mainClass
<plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.1.7.RELEASE</version>
            <configuration>
                <mainClass>com.example.App</mainClass>
            </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>


text:
Q: How to disable Alt Gr key permanently in windows 10 How to permanently disable the Alt Gr key and make it a normal Alt key ?

A: The Stack Overflow post
How to globally map AltGr key to Alt key?
has several solutions.
Save this as AltGR_to_LeftAlt.reg file and run it (after doing backup in regedit
of the key):
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,02,00,00,00,38,00,38,e0,00,00,00,00

Or you could use AutoHotKey with this script:
LControl & *RAlt::Send {LAlt Down}
LControl & *RAlt Up::Send {LAlt Up}

More information is available in the linked post.

A: Adding this anywhere in my AutoHotKey script fixed my personal issue with AltGr:
RAlt::Alt

If you're interested what the issue was:
Using an international keyboard layout instead of English, I could no longer navigate backwards/forwards in my web browser using the rightalt+leftarrow/rightarrow shortcuts.


text:
Q: Not fully understanding pointers (C) I have to take text input in the form of "add # # ... #" (# just being a number) and create and store the values as vertices in a struct. Whenever I input "add" I get a segmentation fault. I'm confident it's cuz my usage of pointers is wrong, but I'm not sure how.
This is for an intro to C course so I'd appreciate help that follows that level of simplicity.
Below is my main file that calls my add function (handleAdd)
int main() {
    printf("Create a polygon using the add command. Valid commands are add, summary, turn, shift, and quit.\n");
    while (1) { //infinite while loop...
        char* cmdLine;
        char* command;
        char* input;
        printf(">>");
        gets(cmdLine);
        command = strtok(cmdLine, " "); //first word
        input = strtok(NULL, ""); //dont understand

        if (strcmp(command, "quit") == 0) //if command == "quit"
             break;
        else if (!strcmp(command, "add")) { //if command == "add"
            if ((input) == NULL) //add\n
                printf("Too few aguments for add command! It must be in the form of add x1 y1 x2 y2 xn yn.\n");
            else
                printf("test1");

            handleAdd(input);
        }

The next code is the actual handleAdd function
handleAdd(char* addCommand) {
   printf("test1");
   char addCmds[50];
   printf("test2");

   while (addCommand != NULL) {
       printf("test1");
       int i = 0;
       //addCmds[i];
       addCommand = strtok(NULL," ");
   }

   size_t cmdLength = strlen(addCommand);

   for (int i = 1; i <= cmdLength; i++) { //i = 1 becaue 0 has "add"
       if (*(addCommand + i) % 2 == 0) { //if this is even, assign to yCoords
           *(yCoords+(i-1)) = *(addCommand+i); //doubtful it works
       }

       if (*(addCommand + i) % 2 != 0) { //if this is odd, assign to xCoords
           *(xCoords+(i-1)) = *(addCommand+i); //doubtful it works
       }
   }
}

A: You declared cmdLine but you did not specify it as an array or assign some memory using malloc. Make it an array (its the simplest solution) like this: char cmdLine[100];. And read the input using fgets(cmdLine, 99, stdin); I used 99 to leave room for the trailing NUL, part of every string.

Also, don't make command and input into arrays. Leave them be because strtok allocates memory on its own.


text:
Q: sed append a line after a block In a directory, I have too many site.ini.append.php (about 100 files).
They all look like:
[block1]
blabla[]
blabla[]=blabla
...
blabla[]=blabla

[block2]
blabla[]
blabla[]=blabla
...
blabla[]=blabla

[block3]
blabla[]
blabla[]=blabla
...
blabla[]=blabla

However, [block1] has different number of entries depending on the file. It's the same thing for the other blocks.
I need to add a new line at the end of [block2]:
[block2]
blabla[]
blabla[]=blabla
...
blabla[]=blabla
blabla[]=new_entry

And I cannot just use line number because, as I said, blocks have different entries, and [block2] may have 20 lines in a file, and 10 in another etc...
I was thinking about somthing like this
sed -n '/^\[block2\]$/,/^$/ a blabla[]=new_entry' path/to/one_of_the_site.ini.append.php

But it doesn't work, obviously, because /^\[block2\]$/,/^$/ is not an address.
How do I do it (preferably using sed)?
UPDATE
As explained here, /^[block2]$/,/^$/ is a valid address.
However, neither a, nor i fixes the issue for me
sed -n '/^\[block2\]$/,/^$/ a blabla[]=new_entry' path/to/one_of_the_site.ini.append.php

sed -n '/^\[block2\]$/,/^$/ i blabla[]=new_entry' path/to/one_of_the_site.ini.append.php

Environment

$ sed --version
GNU sed version 4.1.5
Copyright (C) 2003 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE,
to the extent permitted by law.

A: Following @don_crissti's suggestion, this seems to work in GNU sed and the BSD one on my Mac:
sed -e $'/^\\\[block2\\\]$/,/^$/ {/^$/i\\\nnew line\n}' < input

However, it does depend on the empty line being there, I'm not sure if your file has it if the block we're looking for is the last one.
We need sed to get an actual newline to start and terminate the i command, so I used the ANSI-C quoting $'' to make one (supported by ksh/zsh/bash). In a standard shell, you'll have to manually insert one.

A:  sed  '/block2/,/^$/s/^$/blabla[]=new_entry\n/g' filename

Above oneliner works fine .it matches the line between block2 and newline and then replaces newline with blabla[]=new_entry\n. Let me know for any issues
output
[block1]
blabla[]
blabla[]=blabla
...
blabla[]=blabla

[block2]
blabla[]
blabla[]=blabla
...
blabla[]=blabla
blabla[]=new_entry

[block3]
blabla[]
blabla[]=blabla
...
blabla[]=blabla


text:
Q: Is it possible to programmatically load an SQL dump file using RMySQL? I'm storing a database structure in the form of a .sql dump file in my package's configuration folder (stored in inst/config).
At the moment I'm using a command line which requires password input:
cat 'filename.sql' | mysql -p databasename

In fact I'm suggesting to the user how to load the dump with this function:
loaddbstructure <- function(sqlfile = system.file("config/dump.sql",
                                                package="mypackagename", mustWork = TRUE)){
    message("This message gives 2 options to load the database structure.\n\n",
            "(1) If a user called 'R' is created in MySQL, you can run this from a shell command line: \n",
            sprintf("$ cat '%s' | mysql -u R -p tradeflows", sqlfile),
            "\n\n",
            "(2) Another option is to call this from a mysql client:\n",
            "mysql> connect tradeflows;\n",
            sprintf("mysql> source %s;", sqlfile))
}

Is it possible to programmatically load this .sql file with a command from RMySQL, using a database connection created with the credentials provided in ~/.my.cnf?

A: Add connection credentials to the mysql option file located in ~/.my.cnf:
[client]
user = R
password = password

Then you can load the database dump with an R command that calls a system bash command (Linux specific):
system("cat 'dump.sql' | mysql  databasename")