text:
Q: angular : sticky navbar not working (display nothing in localhost:4200), but works if put in notepad like normal HTML, WHY? I want to make a webpage in Angular 6, but somehow its not working if i use it in angular but works as in display result(need some adjustment but gives out desired output) when writing the code in NOTEPAD as normal HTML.
I can't figure out whats wrong ....i am new to angular ....it would be great if someone could help me know the reason behind it.
menu.component.css :
body {
    position: relative;
    height:100%;
}
.affix {
    top:0;
    width: 100%;
    z-index: 9999 !important;
}
.navbar {
    margin-bottom: 0px;
}

.affix ~ .container-fluid {
   position: relative;
   top: 50px;
}
#section1 {padding-top:50px;height:500px;color: #fff; background-color: #1E88E5;}
#section2 {padding-top:50px;height:500px;color: #fff; background-color: #673ab7;}
#section3 {padding-top:50px;height:500px;color: #fff; background-color: #ff9800;}
#section4 {padding-top:50px;height:500px;color: #fff; background-color: #00bcd4;}
#section5 {padding-top:50px;height:500px;color: #fff; background-color: #009688;}
.logo{
height:20px;
width:100px;
}
.imgsize{
  background-position: fixed;
  height:70px;
  width:120px;
  margin-top :10px;
  margin-bottom:20px;

}
.bg1{
  background-position: center ;
  background-repeat: no-repeat;
  max-width:100%;
  height:50%;
  background-size:100% 100%;
}
/*body{
  height:100%;
}*/
.center{
  position:absolute;
  top:50%;
  left:60%;
  transform: translate(-50%,-50%);
}
.text{
  position:absolute;
  top:60%;
  left:68%;
  transform: translate(-50%,-50%);
}
.gs{
  max-height:40px;
  max-width:50px;
}
.exp{
  max-height:40px;
  max-width:90px;
}
.ap{
  max-height:50px;
  max-width:100px;
}

Please ignore the header image and layouts ...i have used another img and that part works just fine!! the issue is with the navbar.
menu.component.html

TECHNOLOGY FUSION

WORKSHOP

-sponsored by

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

              </button>

HOME

ABOUT

WORKSHOPS

FAQ

LOGIN

Section 1

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 2

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 3

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 4

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 5

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

notepad version
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

TECHNOLOGY FUSION

WORKSHOP

-sponsored by

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

HOME

ABOUT

WORKSHOPS

FAQ

LOGIN

Section 1

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 2

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 3

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 4

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Section 5

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

Try to scroll this section and look at the navigation bar while scrolling! Try to scroll this section and look at the navigation bar while scrolling!

this is code was taken from w3-school for navbar sticky function.

A: You need to add the path to the css file in the styleUrls array of the component.


text:
Q: What type of SQL does Red Query Builder generate? I have been trying to use Red Query Builder visual query builder on a project, but we are finding that the SQL output is not consistent with the SQL our database (SQLite) expects. That makes me wonder what dialect of SQL is being generated and how can I change it?
Edit:
For example, this is a generated line of SQL.
"SELECT \"x0\".\"ID\", \"x0\".\"NAME\", \"x0\".\"COUNTRYCODE\", \"x0\".\"DISTRICT\", \"x0\".\"POPULATION\" FROM \"CITY\" \"x0\" INNER JOIN \"COUNTRY\" \"x1\" ON \"x0\".\"COUNTRYCODE\" = \"x1\".\"CODE\" WHERE (\"x1\".\"NAME\" = ?)"

From a cursory inspection, the x0 seems to be the alias for the table named CITY, but where is that connection being made?

A: The query runs just fine for me in SQLite after creating the proper tables.  Here's the fully query unescaped and formatted:
SELECT
    "x0"."ID",
    "x0"."NAME",
    "x0"."COUNTRYCODE",
    "x0"."DISTRICT",
    "x0"."POPULATION"
FROM
    "CITY" "x0"
            INNER JOIN
    "COUNTRY" "x1"
            ON
        "x0"."COUNTRYCODE" = "x1"."CODE"
WHERE ("x1"."NAME" = ?)

Here's DDL and inserts to test:
CREATE TABLE Country (CODE text, Name Text);
CREATE TABLE CITY (ID int, Name text, countrycode text, district text, population int);

INSERT INTO Country VALUES ('US', 'United States');
INSERT INTO Country VALUES ('AU', 'Australia');

INSERT INTO City VALUES (1, 'Albany', 'US', 'NY', 1000000);
INSERT INTO City VALUES (2, 'Atlanta', 'US', 'GA', 2000000);
INSERT INTO City VALUES (3, 'Washington', 'US', 'DC', 500000);
INSERT INTO City VALUES (4, 'Melborne', 'AU', 'A', 40000);
INSERT INTO City VALUES (5, 'Sydney', 'AU', 'B', 60000);

Full example (run in console, so query is not parameterized, but ? is accepted parameterization for SQLite).
C:\Windows\System32>sqlite3
SQLite version 3.7.6.3
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> CREATE TABLE Country (CODE text, Name Text);
sqlite> CREATE TABLE CITY (ID int, Name text, countrycode text, district text, population int);
sqlite> INSERT INTO Country VALUES ('US', 'United States');
sqlite> INSERT INTO Country VALUES ('AU', 'Australia');
sqlite> INSERT INTO City VALUES (1, 'Albany', 'US', 'NY', 1000000);
sqlite> INSERT INTO City VALUES (2, 'Atlanta', 'US', 'GA', 2000000);
sqlite> INSERT INTO City VALUES (3, 'Washington', 'US', 'DC', 500000);
sqlite> INSERT INTO City VALUES (4, 'Melborne', 'AU', 'A', 40000);
sqlite> INSERT INTO City VALUES (5, 'Sydney', 'AU', 'B', 60000);
sqlite> SELECT
   ...>         "x0"."ID",
   ...>         "x0"."NAME",
   ...>         "x0"."COUNTRYCODE",
   ...>         "x0"."DISTRICT",
   ...>         "x0"."POPULATION"
   ...> FROM
   ...>         "CITY" "x0"
   ...>                         INNER JOIN
   ...>         "COUNTRY" "x1"
   ...>                         ON
   ...>                 "x0"."COUNTRYCODE" = "x1"."CODE"
   ...> WHERE ("x1"."NAME" = 'United States');
1|Albany|US|NY|1000000
2|Atlanta|US|GA|2000000
3|Washington|US|DC|500000
sqlite>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Name already in use fatal error using composer's autoload in PHPUnit Using PSR-4 autoloading with Composer, when I try to test this class:
namespace User;

use User\Contracts\UserId;
use User\Contracts\User as UserContract;

class User implements UserContract
{
    private $id;

    public function __construct(UserId $id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }
}

using PHPUnit:
use User\Contracts\UserId;

class UserTest extends \PHPUnit_Framework_TestCase
{
    public function test_the_identifier_can_be_used_as_string()
    {
        $identifier = m::mock(UserId::class);
        $identifier->shouldReceive('__toString')->once()->andReturn('foo');

        $user = new User($identifier);

        $this->assertSame('foo', (string) $user->getId());
    }
}

I receive this error in the console
PHP Fatal error:  Cannot use User\Contracts\UserId as UserId because the name is already in use in /src/User/User.php on line 5

This is the file/folder structure:
src
`-- User
    |-- Contracts
    |    |-- User.php
    |    `-- UserId.php
    |-- User.php
    `-- UserId.php
tests
`-- User
    |-- UserIdTest.php
    `-- UserTest.php

I've done a lot of searches about this problems, but I've not found any solution about that.

*

*PHP Version: 5.6.13-1+deb.sury.org~trusty+3

*PHPUnit version: 5.0.3

*OS: Ubuntu 14.04.3 LTS

How can I solve this problem?

A: You cannot import a class into a namespace that is already declared inside it with the same alias.
You have \User\UserId and want to import \User\Contracts\UserId into the \User namespace. This would make the shortcut UserId ambigous.
http://php.net/manual/en/language.namespaces.importing.php#117334
You could either use an alias when importing, or directly use a relative path:
namespace User;

class User implements Contracts\User
{
    private $id;

    public function __construct(Contracts\UserId $id) {}
}

Update 2018-03-20:
There is a bug report https://bugs.php.net/bug.php?id=66773 that complains about PHP triggering this error if used without opcode cache, but not otherwise. The reason is that with opcache the compilation is done per file, and it is a reasonable expectation that the file's contents ONLY are considered. However it seems that the error is that existing class definitions from previously loaded files are in the way when importing "conflicting" classes.
It was fixed in the correct way for PHP 7.0.13: Every single file only accounts for itself, and if you desire to import a class and use it by it's shorthand name, you may do so irrespective of any other classes that may exist in the namespace. You simply loose access to these classes - which is irrelevant because your code doesn't use them in the first place. If you'd wanted that changed, you'd have to change the imports.
As the opcache is usually disabled on the command line, you were likely to trigger this bug when using PHPUnit.

A: Try the following:
use User\Contracts\UserId as UserIdContract;

probably you're getting a naming conflict because you're doing
use User\Contracts\UserId;

but you also have UserId in the same namespace of the User class.
So...
namespace User;

use User\Contracts\UserId as UserIdContract;
use User\Contracts\User as UserContract;

class User implements UserContract
{
    private $id;

    public function __construct(UserIdContract $id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }
}

Hope it helps!


text:
Q: DioError [DioErrorType.response]: Http status error [504] There's an error in my flutter app DioError [DioErrorType.response]: Http status error [504] I don't know why it shows 504 as what I know before, 504 means Gateway Timeout, why it took a long time to respond eventhough it shows the correct response in postman. It ended up with showing "error" in my app's user interface (UI) and my console is look like this:
I/flutter (16822): DioError [DioErrorType.response]: Http status error [504]
I/flutter (16822): Source stack:
I/flutter (16822): #0      DioMixin.fetch (package:dio/src/dio_mixin.dart:488:35)
I/flutter (16822): #1      DioMixin.request (package:dio/src/dio_mixin.dart:483:12)
I/flutter (16822): #2      DioMixin.get (package:dio/src/dio_mixin.dart:61:12)
I/flutter (16822): #3      ApiWrapper.request (package:eoffice/utils/networks/ApiWrapper.dart:66:38)
I/flutter (16822): <asynchronous suspension>
I/flutter (16822): #4      SimpegService.apiRequest (package:eoffice/utils/networks/constans/SimpegService.dart:34:16)
I/flutter (16822): <asynchronous suspension>
I/flutter (16822): #5      LeaveListRepository.fetchResponse (package:eoffice/modules/home/views/widgets/Dashboard/DashboardApp/Leave/LeaveList/repositories/LeaveListRepository.dart:14:9)
I/flutter (16822): <asynchronous suspension>
I/flutter (16822): #6      LeaveListBloc.fetchResponse (package:eoffice/modules/home/views/widgets/Dashboard/DashboardApp/Leave/LeaveList/blocs/LeaveListBloc.dart:33:11)
I/flutter (16822): <asynchronous suspension>
D/EGL_emulation(16822): app_time_stats: avg=62.44ms min=6.19ms max=130.16ms count=15
I/flutter (16822): DioError [DioErrorType.response]: Http status error [504]
I/flutter (16822): Source stack:
I/flutter (16822): #0      DioMixin.fetch (package:dio/src/dio_mixin.dart:488:35)
I/flutter (16822): #1      DioMixin.request (package:dio/src/dio_mixin.dart:483:12)
I/flutter (16822): #2      DioMixin.get (package:dio/src/dio_mixin.dart:61:12)
I/flutter (16822): #3      ApiWrapper.request (package:eoffice/utils/networks/ApiWrapper.dart:66:38)
I/flutter (16822): <asynchronous suspension>
I/flutter (16822): #4      SimpegService.apiRequest (package:eoffice/utils/networks/constans/SimpegService.dart:34:16)
I/flutter (16822): <asynchronous suspension>
I/flutter (16822): #5      LeaveListRepository.fetchResponse (package:eoffice/modules/home/views/widgets/Dashboard/DashboardApp/Leave/LeaveList/repositories/LeaveListRepository.dart:14:9)
I/flutter (16822): <asynchronous suspension>
I/flutter (16822): #6      LeaveListBloc.fetchResponse (package:eoffice/modules/home/views/widgets/Dashboard/DashboardApp/Leave/LeaveList/blocs/LeaveListBloc.dart:33:11)
I/flutter (16822): <asynchronous suspension>

A: are you using a device or emulator? if emulator, when you fetch you must use 10.0.2.2 as localhost. For device use the ip4 in cmd ipconfig.


text:
Q: VBA functions in MS Excel I'm new to VBA, and I have a question, i.e I have a mathematical function 1 + 2x¹ + 3x² + 4x³ + ... +10x⁹ and I need to resolve it into two ways:

*

*I can use raising operations(analog pow in Pascal) and IF statement;

*without rising operations and IF statement...

I have tried this one:
Public Function test(x)

test = 1 + 2*x^1 + 3*x^2 + 4*x^3 + 5*x^4 + 6*x^5 + 7*x^6 + 8*x^7 + 9*x^8 + 10*x^9

End Function

but I think it returns the wrong answer - 2441406 with calling =test(5)
So can anyone give any advice, or help with my problem?

A: If you can't use VBA for this, there is a formula solution.  Assuming your variable x is in cell A1, you would use this formula in another cell (I used B1):
=SUMPRODUCT(ROW($1:$10)*A1^(ROW($1:$10)-1))

When A1 = 5, it returned 23803711 as expected.

A: You will need * as the multiper:
Public Function test(x)
    test = _
         1 _
      + 2 * (x ^ 1) _
      + 3 * (x ^ 2) _
      + 4 * (x ^ 3) _
      + 5 * (x ^ 4) _
      + 6 * (x ^ 5) _
      + 7 * (x ^ 6) _
      + 8 * (x ^ 7) _
      + 9 * (x ^ 8) _
      + 10 * (x ^ 9)
End Function


text:
Q: Setting UserAgent for HttpWebRequest in Silverlight 4 I'm using Silverlight 4 and need to set (override) the UserAgent for a HttpWebRequest. Unfortunately this is not supported.
The platform notes in MSDN state:

"Do not use this member when targeting Silverlight 4."

And if I try, I get a System.NotImplementedException with this StackTrace:
   at System.Net.Browser.ClientHttpWebRequest.SetUserAgent(String value)
   at System.Net.HttpWebRequest.set_UserAgent(String value)
I've tried altering the Headers collection directly but that returns the same error.
Is there any way to do this?
Bonus question: anyone know why this is not supported?


text:
Q: I just need one dependent module, but don't need its dependencies In my project , there is a spring XML config that utilizes ehcache to cache method returns.
xml snippet :
    http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd

  <ehcache:config configLocation="classpath:ehcache.xml"/>

  <ehcache:proxy id="explainRetriever" refId="explainRetrieverImpl">
    <ehcache:caching methodName="get*" cacheName="explainCache"/>
  </ehcache:proxy>

but in runtime , server complains it cannot find definitions of http://www.springmodules.org/schema/ehcache , I know I have to add "spring-modules-cache.jar" to WEB-INF/lib directory.
But my project is maintained by maven , if I add "spring-modules-cache" to the runtime dependency ,  it will bring a lot of dependencies to my WAR file , filling my WAR with a lot of unnecessary jars. I just need one declaration in it , not all of its dependencies ...
Is there any way to tell maven not to include its dependencies to the project ?
Or ... another way , when packaging WAR , just copy another prepared spring-modules-cache.jar to WEB-INF/lib , how to do this ? Thanks !

A: Have a look at this article - basically you need to use exclusions.

A: As mentioned, you can use the exclusions mechanism, but that basically means excluding every runtime dependency declared in the dependency's pom, which is not only a pain, but fragile, since you have to keep tracking the dependency's pom to keep your list of exclusions up to date.
An alternative is to mark the dependency as <scope>provided</scope> and then copy the dependency yourself to the war construction directory under 'target' using the dependency:copy plugin goal. By default a war is built in
${project.build.directory}/${project.build.finalName}. See the war plugin for details.
E.g.
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy</id>
            <phase>package</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <artifactItems>
                <artifactItem>
                  <groupId>org.springmodules</groupId>
                  <artifactId>spring-modules-cache</artifactId>
                  <version>0.8</version>
                  <type>jar</type>
                  <overWrite>true</overWrite>
                  <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/lib</outputDirectory>
                </artifactItem>
              </artifactItems>
            </configuration>
          </execution>
        </executions>
      </plugin>


text:
Q: Passing an instance of a functor to another functor For structural reasons, I'd like to be able to pass an instance of a functor to another functor. At the moment I achieve something equivalent by handing a pointer to a function to my functor.
I've attempted to encapsulate the idea in some minimal code below:
class A
{
private:
    double _x, _y, _z;

public:
    A (double x, double y, double z) : _x(x), _y(y), _z(z) {};

    void operator() (double t) const
    {
        // Some stuff in here that uses _x, _y, _z, and t.
    }
};

class B
{
private:
    // What is the type of the functor instance?
    ??? A ???

public:
    // How do I pass the instance of A into B at initialisation?
    B (??? A ???) :  ??? : {};

    void operator() (double tau) const
    {
        // Something that uses an instance of A and tau.
    }
};

int main(void)
{
    // I want to do something like this:
    A Ainst(1.1, 2.2, 3.3); // Instance of A.
    B Binst(Ainst);         // Instance of B using instance of A.

    Binst(1.0);             // Use the instance of B.

    return 0
}

In essence, I want to be able to chain up functors. As stated above, I currently do this by passing a function pointer to B along with variables x, y, and z. In my code B is templated and the goal is to write it once and then reuse it without any modification later, which means that handing x, y, and z to B is not ideal. A on the other hand will be customised for each program that I write. I don't mind B being quite messy, but I want A to be nice and clean as this is the part that will be exposed.
For those who know some quantum mechanics, B is the Schrödinger equation (or a master equation) and A is a time dependent Hamiltonian. The variables x, y, and z are used to construct the Hamiltonian, and t is time, allowing me to use the odeint library (so I'm using ublas and a couple of other Boost bits).

A: Using references?
class A { /* ... */ };

class B
{
    A &a;

public:
    B(const A &my_a)
        : a(my_a)
    { }

    // ...
};


text:
Q: Detecting whether a destructor has been called Im making a board game where the game ends when one piece is destroyed e.g a king dying in chess.
Now I have the possibility of searching through all my objects and seeing that e.g there WERE two pointers to king objects and now there's only one hence game is over and the team with the remaining king won.
I was however wondering if it would instead be possible to say something along the lines of:
if(king_destructor is called){
     game over;}

But after searching a bit I havent found a way to do that.
More specifically my class structure is:
class pieces{}
class king : public pieces{}

where pieces is an abstract class and there are derived classes for each individual piece. In the derived class for the 'king' piece there is its destructor.
Otherwise:
class game_board{}

which is another abstract class which has data members which are pointers to pieces objects. To be exact, I have a map variable which take the position of the piece on the board as the key and a pointer to a piece object as the value.
Finally I have a derived class :
class game_rules: public game_board{}

it is within this class that I have a function which detects when the game is over.
I experimented with using a static variable that is modified by the 'king' destructor but this is out of the scope of my game_rules class.
Does anyone know whether this is possible?

A: There are probably several ways you could implement something like this. What struck me from your description is the map from board positions to pointers to pieces. You did not specify what kind of pointer, so I'll improvise. Suppose the map holds shared pointers to pieces. Then game_board could maintain weak pointers to the kings. Instead of searching all of your pieces, you could simply see if the weak pointers are expired. Not only does this tell you if the game is over, but it also tells you who lost.

A:
I experimented with using a static variable that is modified by the 'king' destructor but this is out of the scope of my game_rules class.

This seems reasonable. I don't see why scope is a problem. The variable would be private to the king class, but with public read-only access.
class king : public piece {
    public:
        static unsigned count() { return instance_count; }

    private:
        static unsigned instance_count;
};

(Of course, the rest of your class definition would go in there also.)
In the source file for game_rules, you would #include "king.hpp" (or whatever you named that header file) and get the value of the count of kings with the expression king::count(). (A static member function can be called without having an object of that type.) For example, you might write something like the following.
if ( king::count() <= 1 ) {
    // Game over
}


text:
Q: If not null, get the value of the property in one LINQ line I am using LINQ and in it, I have this code which return either a string or null. The problem is if GetUserName return null, it will hit error. How do I write it in one line that if GetUserName is not null, it will return username property?
username = service.GetUserName(t.Id).username

The complete query is something like this below:
var members = data.Select(t => new Members
{ username = service.GetUserName(t.Id).username }).ToList();

If this is not possible, then I have to manually write more code to manually map the properties.

A: You could use the null conditional operator ?. but that means then you will get members with the username property as null - I would suggest to also add a where after the initial select:
var members = data
    .Select(t => new Members{ username = service.GetUserName(t.Id)?.username })
    .Where(m => m.userName is object)
    .ToList();

If the constructor of the Members class is heavy, you can first select the userName, then filter, and then create the Memebers list:
var members = data
    .Select(t => new { service.GetUserName(t.Id)?.username })
    .Where(m => m.userName is object)
    .Select(t => new Members{ username = t.username })
    .ToList();

A: You can use Null Propagation
i.e
 var members = data.Select(t => new Members
{ username = service.GetUserName(t.Id)?.username }).ToList();


text:
Q: ways to transpose the Rows into Columns in SAP HANA Actually i got requirement like i have to transpose the Row data into Column for Dynamically.
Material materiral_type value
20          x1           10
20          x2           20
20          x3           70
20          x4           80
30          x1           10
30          x5           20
Result required in SAP HANA :
material x1    x2  x3  x4  x5 ...etc.,
20       10    20  70  80  0
30       10    0   0    0  20

A: There's no built-in command (like PIVOT/UNPIVOT) in SAP HANA (up to SPS12).
You can create your own dynamic transformations either in SQLSCript or in the information view editor.
This topic has been covered extensibly in the SAP Community Network. Just search there: https://onedx.find.sap.com/s#t=hana%20pivot&n=1&p=default&repo=srh


text:
Q: es6 extend parent class undefined I have 2 very simple classes one is a parent class Calendar the other the child class MonthCalendar:
calendar.js:
import MonthCalendar from './month-calendar';

export default class Calendar {
  constructor() {
    this.date = new Date();
  }

  displayMonthCalendar(){
    var mcal = new MonthCalendar();
    mcal.generate();
  }
}

var cal = new Calendar();
cal.displayMonthCalendar();

month-calendar.js:
import Calendar from './calendar';

export default class MonthCalendar extends Calendar {
  constructor() {
    super()
  }

  generate() {
    alert('working');
  }
}

When I try running this I keep getting the error:
Uncaught TypeError: Super expression must either be null or a function, not undefined
It's telling me Calendar is undefined; however if I don't extend Calendar and use it inside the generate() method it is not undefined:
month-calendar.js:
import Calendar from './calendar';

export default class MonthCalendar {
  generate() {
    console.log(new Calendar());
  }
}

That throws no error.


text:
Q: Java send javascript object to nodejs I am currently developping an Android app in java, and I have to send a javascript object for the node server to interpret it.
Javascript code:
    socket.emit('mousemove', { 'x': x, //int
     'y': y, // int
     'drawing': drawing, //boolean
     'id': id //int
});

I didn't try anything relevant since I was unable to include a boolean in an int[] array
How could I achieve that ?
PS: Someone told me about GSON, is it the right use ? Then, how to use it ?

A: Personnally I use JSON Java. Here's an exemple : http://www.java2s.com/Tutorials/Java/JSON/0100__JSON_Java.htm


text:
Q: How do I update the locations of multiple markers in google maps using phonegap i'm newbie, i have service tracking multi car, i use timmer for receive location, but i dont know how to update old marker with new value. i'm try use delete all marker then add again, but it not smooth. plz help me. Sr for bad english
var markers = [];
var marker = [];

setInterval(function () {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
        markers = [];

        $.ajax({
            type: "POST",
            contentType: "application/xml; charset=utf-8",
            url: "http://localhost:24074/WebService1.asmx/DoWork",
            data: {},
            dataType: "xml",
            crossDomain: true,
            processData: false,
            success: function (xml) {
                var bienSo, soHieu, soCho, vd, kd;
                $(xml).find('T_XeOnline').each(function () {
                    $(this).find("KinhDo").each(function () {
                        kd = $(this).text();
                    });
                    $(this).find("ViDo").each(function () {
                        vd = $(this).text();
                    });
                    $(this).find("BienSoXe").each(function () {
                        bienSo = $(this).text();
                    });
                    $(this).find("SoHieuXe").each(function () {
                        soHieu = $(this).text();
                    });
                    $(this).find("SoCho").each(function () {
                        soCho = $(this).text();
                    });
                    content = '
Biển số xe: ' + bienSo + '
' +
                               'Số hiệu xe: ' + soHieu + '
' +
                               'Số chỗ: ' + soCho + '
' + '
';

                    updateMarker(vd, kd);
                });

            },
            error: function (msg, textStatus) {
                alert("Error " + msg.responseText + "" + msg.statusText + "" + XMLHttpRequest.stat);
            }
        })
    }, 5000);

 function updateMarker(lat, lng) {

    marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
    });

    markers.push(marker);
    addInfoWindow(marker, content);
}

A: There are no build-in function for that, but you can build you own by using the setPosition(latlng) function to update the markers' positions, and use setTimeout(myFun, delay) to wait and make it looks like it is animated.
I created the JSFiddle here.
Hopefully this help.


text:
Q: XPage file upload control loses filename on refresh I'm sure I must be just missing something simple here but I've searched everywhere for an answer and no luck.
I have a bog standard file upload control on my xpage showing initially the standard "No file chosen", I select the "Choose file" button which overwrites the "No file chosen" with the selected filename - all good! BUT on any subsequent partial or full refresh of the page the filename is disappearing and reverting to "No file chosen". If I submit the form anyway the file is still uploaded correctly to the server but this is obviously no good for the user who thinks they have to reselect the file.
Can someone just tell me what I'm doing wrong here??
<xp:fileUpload id="songAlbumUpload1" value="#{submitfile.File1}">
            <xp:eventHandler event="onchange" submit="true"
                refreshMode="complete" disableValidators="true">
            </xp:eventHandler>
</xp:fileUpload>

Note this was my latest attempt using a full refresh but I've tried all other partial refresh options too.  Also my upload control is in a formTableRow so I tried moving it out into the main panel but the issue still occurs.
(I have also discovered the bug where a refresh ends up uploading multiple instances of the same file which as I understand it is fixed by a partial refresh of the panel the upload control is contained in - but of course this required refresh then causes the above issue anyway)!
Many thanks.

A: As indicated by Frantisek, upon refresh the fileUpload returns to a "No File Chosen" display indicating its ready to upload another file.  Try removing the eventHandler to preserve the uploaded filename:
    <xp:fileUpload id="songAlbumUpload1" value="#{submitfile.File1}"></xp:fileUpload>

Or add a fileDownload and bind it to the same RTF to display the status of the uploaded files.
    <xp:fileDownload rows="30" id="fileDownload1" value="#{submitfile.File1}" displayLastModified="true"
        allowDelete="true" hideWhen="false" style="width:100.0%">
    </xp:fileDownload>


text:
Q: Obtener valor parámetro de salida PHP llamando un stored procedure de MySQL con parámetros de entrada y salida Tengo un problema para obtener el valor del parámetro de salida en PHP. Básicamente, la consulta siguiente funciona correctamente, los valores se insertan en una tabla en MySQL y, como notarán, tiene dos parámetros de salida (@sFinal, @sErrorFinal) de los cuales me gustaría obtener su resultado, sin embargo, a pesar de haber visto muchas indicaciones, no he podido lograrlo. Me gustaría que el parámetro de salida @sFinal fuese la información que recibe el return, algo así como return @sFinal.
static public function MdlIngresarVentas($tabla, $datos){

    $sql = 'call Sales_Actualizar(:nroRegistro, :registrosTotales, :cantidad, :precioVenta,
                                  :totalVenta, :fechaVenta, :tipoVenta, :usuario,
                                  :idMedicamento, :codigoBarra, @sFinal, @sErrorFinal)';

    $stmt = Conexion::conectar()->prepare($sql);

    $stmt->bindParam(":nroRegistro", $datos["consecutivo"], PDO::PARAM_STR);
    $stmt->bindParam(":registrosTotales", $datos["registrosTotal"], PDO::PARAM_STR);
    $stmt->bindParam(":cantidad", $datos["cantidad"], PDO::PARAM_STR);
    $stmt->bindParam(":precioVenta", $datos["prventa"], PDO::PARAM_STR);
    $stmt->bindParam(":totalVenta", $datos["total"], PDO::PARAM_STR);
    $stmt->bindParam(":fechaVenta", $datos["fechaVenta"], PDO::PARAM_STR);
    $stmt->bindParam(":tipoVenta", $datos["tipo"], PDO::PARAM_STR);
    $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR);
    $stmt->bindParam(":idMedicamento", $datos["idMedicamento"], PDO::PARAM_STR);
    $stmt->bindParam(":codigoBarra", $datos["codigo"], PDO::PARAM_STR);

    if($stmt->execute()){

        return "ok";

    }else{

        return "error";

    }

    $stmt->close();

    $stmt = null;

}

Agradezco la ayuda que me puedan brindar.

A: Los resultados de salida los recibes en forma de columnas como cualquier SELECT.
Podrías, por ejemplo, cambiar las lineas cuando ejecutas el comando por:
if($resultado = $stmt->execute()){

    // mostramos los resultadss
     echo '<pre>';
     print_r($resultado);
     echo '</pre>';

    return "ok";

}else{

    return "error";

}

Aquí tienes un ejemplo: http://www.mysqltutorial.org/php-calling-mysql-stored-procedures/


text:
Q: Behavior of default model binder with custom object while model binding In the below code my 'tc' object has been initialized after posting, but values are null. What is the root cause of the issue. Why is the default model binder doesn't attempt to populate the properties with incoming posted values? What restriction the default model binder has to behave like this?
  <form id="hello-world" action="/Home/Index">
        <label for="user">User  </label>
        <input id="user" type="text" name="user" required="required">
        <label for="city"> City </label>
        <input id="city" type="text" name="city" required="required">
        <label for="age"> Age </label>
        <input id="age" type="text" name="age" required="required">
        <input type="submit" value="Submit">
    </form>

 public ActionResult Index(TestClass tc)
   {
     ViewBag.TCName = tc.user; // its null
     ViewBag.TCAge = tc.age; // its null
     ViewBag.TCCity = tc.city; // its null
     return View();
    }
public class TestClass
{
    public string user;
    public string city;
    public string age;
}

A: You should use properties and not fields on your view model:
public class TestClass
{
    public string User { get; set; }
    public string City { get; set; }
    public string Age { get; set; }
}

The default model binder can only bind to properties with public getters/setters and not with fields. It simply ignores fields and they will never be initialized.


text:
Q: RMI: Client sends a message to Server I have a problem understanding, on how to make my client to send the object to a server.
So I have one interface called "RMIInterface" and client "RMIClient" and server "RMIServer" classes:
RMIInterface
public interface RMIInterface extends Remote {

   public String getMessage(String text) throws RemoteException;

}

RMIClient
public class RMIClient {

    private void connectToServer() {
        try {
            Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
            RMI rmi = (RMI) registry.lookup("server");
            System.out.println("Connected to Server");

            String text = rmi.getMessage("RMITest Message");
            System.out.println(text);
        } catch (Exception e) {
            System.out.println(e);
        }

    }

    public static void main(String[] args) {
        RMIClient client = new RMIClient();
        client.connectToServer();
    }

}

RMIServer
public class RMIServer extends UnicastRemoteObject implements RMIInterface {

    public RMIServer() throws RemoteException {
        super();
    }

    @Override
    public String getMessage(String text) throws RemoteException {
        return "Your message is: " + text;
    }

    public static void main(String[] args) {
        try {
            Registry registry = LocateRegistry.createRegistry(1099);
            registry.rebind("server", new RMIServer());
            System.out.println("Server started!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

With this program I can connect to a Server with a Client, and print in Client console a message.
My quesiton is, how can I send message from a client to a server, and print that message in server console output? Please make the simplest code example

A: Although it has been over a year, I share solution in case someone comes here looking to solve the question as I did yesterday.
RMIInterface
import java.rmi.*;

public interface RMIInterface extends Remote {

    public void sendMessage(String text) throws RemoteException;

    public String getMessage(String text) throws RemoteException;

}

RMIClient
import java.rmi.*;
import java.rmi.registry.*;

public class RMIClient {

    public static void main(String[] args) {

        String text = "RMI Test Message";
        RMIInterface rmi = null;

        try {
            Registry registry = LocateRegistry.getRegistry("127.0.0.1", 1099);
            rmi = (RMIInterface) registry.lookup("server");
            System.out.println("Connected to Server");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (rmi != null) {
            try {
                rmi.sendMessage(text);
                System.out.println(rmi.getMessage(text));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            System.out.println("Finished");
        }
    }
}

RMIServer
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;

public class RMIServer implements RMIInterface {

    @Override
    public void sendMessage(String s) throws RemoteException {
        System.out.println(s);
    }

    @Override
    public String getMessage(String text) throws RemoteException {
        return "Your message is: " + text;
    }

    public static void main(String[] args) {
        Registry reg = null;
        try {
            reg = LocateRegistry.createRegistry(1099);
        } catch (Exception e) {
            System.out.println("ERROR: Could not create the registry.");
            e.printStackTrace();
        }
        RMIServer serverObject = new RMIServer();
        System.out.println("Waiting...");
        try {
            reg.rebind("server", (RMIInterface) UnicastRemoteObject.exportObject(serverObject, 0));
        } catch (Exception e) {
            System.out.println("ERROR: Failed to register the server object.");
            e.printStackTrace();
        }
    }
}

A: Just add a sendMessage() method to your interface.

A: I'm not gonna provide you the code, cause you already have it. I'm gonna provide you with a solution:
You already have a "channel" where you send a unidirectional message, SERVER -> CLIENT.
If you want to send a message from you server to your client, your CLIENT must be a SERVER too.


text:
Q: Error when I integrate PagerSlidingTabStrip in my Android application I am trying to integrate this PagerSlidingTabStrip (https://github.com/astuetz/PagerSlidingTabStrip) into my Android application, but I get the following error:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
   at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:67)
   at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:144)
   at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
   at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:29)
   at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:26)
   at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:133)
   at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:117)
   at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:456)
   at android.support.v7.app.AppCompatActivity.getSupportActionBar(AppCompatActivity.java:79)
   at com.sch.x.Welcome.<init>(Welcome.java:40)

Here is my code from the Welcome.java file:
package com.sch.x;

import com.astuetz.PagerSlidingTabStrip;
import com.parse.ParseUser;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Welcome extends ActionBarActivity {

    private final Handler handler = new Handler();

    private PagerSlidingTabStrip tabs;

    private Drawable oldBackground = null;
    private int currentColor = 0xFF666666;

    private ActionBar mActionBar = getSupportActionBar();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from singleitemview.xml
        setContentView(R.layout.welcome);

        final ViewPager pager;
        final MyPagerAdapter adapter;

        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        adapter = new MyPagerAdapter(getSupportFragmentManager());

        pager.setAdapter(adapter);

        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                .getDisplayMetrics());
        pager.setPageMargin(pageMargin);

        tabs.setViewPager(pager);

        changeColor(currentColor);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_welcome, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.action_contact:
                QuickContactFragment dialog = new QuickContactFragment();
                dialog.show(getSupportFragmentManager(), "QuickContactFragment");
                return true;

        }

        return super.onOptionsItemSelected(item);
    }

    private void changeColor(int newColor) {

        tabs.setIndicatorColor(newColor);

        // change ActionBar color just if an ActionBar is available
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

            Drawable colorDrawable = new ColorDrawable(newColor);
            Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
            LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable, bottomDrawable });

            if (oldBackground == null) {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    ld.setCallback(drawableCallback);
                } else {
                    mActionBar.setBackgroundDrawable(ld);
                }

            } else {

                TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });

                // workaround for broken ActionBarContainer drawable handling on
                // pre-API 17 builds
                // https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    td.setCallback(drawableCallback);
                } else {
                    mActionBar.setBackgroundDrawable(td);
                }

                td.startTransition(200);

            }

            oldBackground = ld;

            // http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler
            mActionBar.setDisplayShowTitleEnabled(false);
            mActionBar.setDisplayShowTitleEnabled(true);

        }

        currentColor = newColor;

    }

    public void onColorClicked(View v) {

        int color = Color.parseColor(v.getTag().toString());
        changeColor(color);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentColor", currentColor);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        currentColor = savedInstanceState.getInt("currentColor");
        changeColor(currentColor);
    }

    private Drawable.Callback drawableCallback = new Drawable.Callback() {
        @Override
        public void invalidateDrawable(Drawable who) {
            mActionBar.setBackgroundDrawable(who);
        }

        @Override
        public void scheduleDrawable(Drawable who, Runnable what, long when) {
            handler.postAtTime(what, when);
        }

        @Override
        public void unscheduleDrawable(Drawable who, Runnable what) {
            handler.removeCallbacks(what);
        }
    };

    public class MyPagerAdapter extends FragmentPagerAdapter {

        private final String[] TITLES = { "Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
                "Top New Free", "Trending" };

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {
            return SuperAwesomeCardFragment.newInstance(position);
        }

    }

}

A: Isn't the issue related with this var initialiation:

private ActionBar mActionBar = getSupportActionBar();

Have you tried assigning the var in onCreate instead (preferably after the setContentView call)?


text:
Q: What formula would be best to use for returning data from a column after it matches data in another? I have two columns of names.  One column contains several more names than the other.  The column with the shorter list of names is a subset of the larger one, but may contain names that the larger one does not.
With a copy and paste and the use of filters, I can filter the list to yield the information for the subset I want, but I'd really like to learn how to do this with a formula and what I've tried doesn't seem to work.  A picture is worth a thousand words, so allow me to show you one:

This is a work of fiction. Names, characters, businesses, places, events, locales, and incidents are either the products of the author's imagination or used in a fictitious manner. Any resemblance to actual persons, living or dead, or actual events is purely coincidental.
Now, what have I attempted already?  A good number of things combining formulas and functions with INDEX, MATCH, IFERROR.  I've tried so many things over a span of days, that I couldn't tell you what exactly I used at this point and I think it might be less confusing if I kept my initial attempts at this out of this discussion thread.  I'm open to your suggestions, but I'd like to use a formula that does not involve VLOOKUP.  I believe I need to try to make this work for an Office 365 version of Excel, quite possibly the January 2019 version.
Can anyone help me?

A: If the setup is Columns A:D then you can use the following formula in cell D2:
=IF(ISNUMBER(MATCH(C2,A:A,0)),INDEX(B:B,MATCH(C2,A:A,0)),"")


text:
Q: SQL query to export single data row to multiple CSV rows We are trying to automate some steps and I need to setup a query to dump data on a schedule. The problem I am having is taking the single row of data from the SQL table and dumping it to multiple rows of data.
The SQL table is used for a parts order form and has fields for up to 10 parts to be entered (Part01 - Part10) and fields for quantities of each part (Qty01-Qty10). As in most orders, we are not using all 10 lines on every order, so when we export, we also need to test if there is data in the part field (PartXX<>'') to only generate rows for lines that actually have data. There are also fields in the table that would need to be populated in each output row, even though it doesn't change. The query for the first "row" is straight-forward, but my obstacle is the "IF/THEN" part for the subsequent rows and generating the "Line" for the
The output I am looking for is like this:
Ticket# CustID  Account  Line  ShipAttn  ShipAdd  ShipCity ShipState  ShipZip  Part Qty
123456  Cust01  987465   1     Joe Smith Address  AnyTown  IL         01234    Key  2
123456  Cust01  987456   2     Joe Smith Address  AnyTown  IL         01234    Lock 2
Any direction is appreciated.

A: Not knowing your exact schema, you might try something like this to unpivot your records:
;with cte as (
    -- Select for each Part/Qty:
    select Ticket#, CustID, Account, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part01 as Part, Qty01 as Qty, 1 as Line
    from Orders
    where Part01 is not null and Qty01 is not null
    union all
    select Ticket#, CustID, Account, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part02 as Part, Qty02 as Qty, 2 as Line -- 02!
    from Orders
    where Part02 is not null and Qty02 is not null -- 02!
    union all
    select Ticket#, CustID, Account, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part03 as Part, Qty03 as Qty, 3 as Line -- 03!
    from Orders
    where Part03 is not null and Qty03 is not null -- 03!
    --union all...keep going with 04 - 10
)
select Ticket#, CustID, Account
    , row_number() over (partition by Ticket# order by Line) as Line
    , ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part, Qty
from cte
order by Ticket#, Line

A: What you are looking for is a pivot table (or "crosstab"). Every RDBMS has its own solution for that, you failed to provide yours. Exact syntax also depends on your RDBMS.
A standard-SQL query could look like this:
SELECT Ticket#, CustID, Account, 1 AS Line, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part01 AS Part, Qty01 AS Qty
FROM   tbl
WHERE  Part01 IS NOT NULL

UNION ALL
SELECT Ticket#, CustID, Account, 2 AS Line, ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part02 AS Part, Qty02 AS Qty
FROM   tbl
WHERE  Part02 IS NOT NULL

UNION ALL ...

ORDER BY Ticket#, CustID, Account, Line

ORDER BY is applied to the complete result, not just to the last leg of the query. Therefore you don't need a subselect or CTE.

A: Both the solution above requires Union, as you are using SQL Server 2008 R2, you might want to  use inbuilt functionality of UnPivot ... It is still untested, but it should work.
It is based on the solution described : http://mangalpardeshi.blogspot.com/2009/04/unpivot-multiple-columns.html
SELECT Ticket#, CustID, Account
    , row_number() over (partition by Ticket# order by Parts) as Line
    , ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip, Part, Qty
FROM
(
SELECT Ticket#, CustID, Account , ShipAttn, ShipAdd, ShipCity, ShipState, ShipZip,
       Part01, Part02, Part03, Part04, Part05, Part06, Part07, Part08, Part09, Part10,
       Qty01, Qty02, Qty03, Qty04, Qty05, Qty06, Qty07, Qty08, Qty09, Qty10
FROM Suppliers
) Main
UNPIVOT
(
Part FOR Parts IN (Part01, Part02, Part03, Part04, Part05, Part06, Part07, Part08, Part09, Part10)
) P

UNPIVOT
(
Qty For Qtys IN (Qty01, Qty02, Qty03, Qty04, Qty05, Qty06, Qty07, Qty08, Qty09, Qty10)
) Q

WHERE RIGHT(Parts,2) =  RIGHT(Qtys,2)


text:
Q: SharedObject not saving data on Ipad I have been developing a productivity app that uses a SharedObject. It saves custom classes as basic objects and variables. It works perfectly on my computer on the emulator but once I test it on my ipad 1st gen, it doesn't work. The app will background appropriately but when i close the background process and re open the app, all the entries are gone. I haven't payed the developer fee as I'm not sure if I want to invest yet, so I'm using a fake certificate and jailbroken device. Will that stop save data? Again it works exactly as need on pc, but when i close the app process on my ipad, it doesn't save anything.
EDIT: I FIXED IT
Ok, the problem was simply that the flushes weren't calling on the regular changes due to scripting error, and the one on close, doesn't work when the app is closed from backgrounding. Basically I set it to save on home button, and on power button aswell as fixed all the little saves aswell. Works perfectly now. Files were too sketch cause I'm storing an array of custom classes.

A: To avoid adding to the comment chain, I'll just write an answer.
As I said in my comment, most AIR devs avoid using SharedObjects for various reasons. They are limited to ~100kb, you have no control over them, and apparently are flushed on iOS.
With that said, most AIR devs prefer to use File and FileStream which give you direct control over the device's file system.
FileStream features a method called writeObject() which does exactly what you want. Say you have the following strongly typed objects you wish to save (note: only public properties are saved to disk):
var a:Class1 = new Class1();
var s:Class2 = new Class2();
var d:Class3 = new Class3();
var f:Class4 = new Class4();

You'll want to combine them into a single object, or save them individually. For this, I will combine them into a single object.
// you could also use an array, or any other object, to do this
var obj:Object = {objA:a, objS:s, objD:d, objF:f};

Then you want to use File, which is a reference to a file or directory in the file system, and FileStream, which is what communicates with the file system, to write the object.
var f:File = File.applicationStorageDirectory.resolvePath("prefs.conf");
var fs:FileStream = new FileStream();
fs.open(f, FileMode.WRITE);
fs.writeObject(obj);
fs.close() // NEVER forget to close()

And that's it.Your objects are now saved to disk. You can open them using File and FileStream again.
fs.open(f, FileMode.OPEN);
var obj2:Object = fs.readObject();
fs.close();

obj2 will have the same properties as obj and they will match the objects you originally saved. It is worth noting that these objects will not be of the same type as your custom objects. Unless they are primitives (Object, Array, String, Number, int, uint, maybe a few others), every object that is read from a Byte stream (whether it be ByteArray, FileStream, URLStream, etc) will be typed as a standard Object. You can get around this with registerClassAlias(), however.

*

*LiveDocs for File

*LiveDocs for FileStream
EDIT: As a quick note, on iOS, you should always set File.preventBackup to true if they are anything other than preferences. Apple will reject it otherwise. The good news is, though, that those settings should be backed up to iCloud and persist between installations.


text:
Q: How to get Object Label I have object's API Name
How can I get Object's Label ?
I am trying this
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();

Schema.SObjectType schemaObj = schemaMap.get(SObjApiName);

A: You can retrieve label of given object like this:
String objectName = 'Contact';

List<Schema.DescribeSObjectResult> describeSobjectsResult = Schema.describeSObjects(new List<String>{objectName}); // this can accept list of strings, we describe only one object here
String objectLabel = describeSobjectsResult[0].getLabel();

Reference

A:     String type = 'Account';

    Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    Schema.SObjectType leadSchema = schemaMap.get(type);
    Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

    //to get single field label in account
    fieldMap.get(field_Name__c).getDescribe().getLabel()

    //to get all field labels
    for (String fieldName: fieldMap.keySet()) {
      // list of all field API name
      System.debug('-->Field API Name='+fieldName);

      //It provides to get the object fields label.
      AllLabels.add(fieldMap.get(fieldName).getDescribe().getLabel());
    }

A: Just try this code if you want to retrive the object name from a string in visualforce page.
public string selectedobject{get;set;}
public sObject sObj{get;set;}
Map m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(selectedobject) ;
sObj =s.newSObject();


text:
Q: MySQL: Query Optimization SELECT a.FundIDRecv,a.SubscribeDt, b.FundName,
(
    SELECT SUM(c.PricePerWeek)
    FROM tbl_Hive c
    WHERE c.FundID IN
    (
        SELECT FundID from tbl_FundStatic
        WHERE FundID IN
        (
            SELECT FundIDSend
            FROM tbl_FundSubscriptions
            WHERE FundIDRecv = a.FundIDRecv
            AND SubscribeDt >= subdate(CURDATE(), INTERVAL weekday(CURDATE()) DAY)
        )
        AND UserID = '14'
    )
) as Price
FROM tbl_FundSubscriptions a, tbl_Hive b
WHERE a.FundIDRecv = b.FundID
AND a.SubscribeDt >= subdate(CURDATE(), INTERVAL weekday(CURDATE()) DAY)
AND a.FundIDRecv IN
(
    SELECT FundIDRecv
    FROM tbl_FundSubscriptions
    WHERE FundIDSend IN (
        SELECT FundID
        FROM tbl_FundStatic
        WHERE UserID = '14'
    )
)
GROUP BY FundIDRecv

This Query takes a huge amount of time to fetch data.
How can I optimize this query so as to make it execute and fetch results faster than it does?

A: Replace your nested selects by JOIN clauses. Take this for instance:
AND a.FundIDRecv IN
(
    SELECT FundIDRecv
    FROM tbl_FundSubscriptions
    WHERE FundIDSend IN (
        SELECT FundID
        FROM tbl_FundStatic
        WHERE UserID = '14'
    )
)

Why not just join tbl_FundStatic to the outer query like this
FROM tbl_FundSubscriptions a
JOIN tbl_FundStatic s ON (a.FundIDSend = s.FundID)
WHERE s.UserID = '14'

Of course, I don't know if this is still correct, but it'll give you an idea. Also, you should avoid nested selects in the SELECT clause itself. It's better to join tbl_FundStatic and then select fields from it

A: Untested but this will give you a go:
SELECT a.fundidrecv,
       a.subscribedt,
       b.fundname,
       SUM(b.priceperweek) AS price
FROM   tbl_fundsubscriptions a
       JOIN tbl_hive b
         ON a.fundidrecv = b.fundid
       JOIN tbl_fundsubscriptions fs
         ON fs.fundidrecv = a.fundidrecv
       JOIN tbl_fundstatic fst
         ON fst.fundid = fs.fundidsend
            AND fst.userid = '14'
WHERE  a.subscribedt >= SUBDATE(Curdate(), INTERVAL Weekday(Curdate()) DAY)
GROUP  BY a.fundidrecv

You need to add indexes on the following columns:

*

*(a.fundidrecv,a.subscribedt)

*(b.fundid)

*(fs.fundidrecv)

*(fst.fundid,fst.userid)


text:
Q: How to show that the given integral equals a finite value $$I=\int \limits_0^e x^{-x} dx$$
I am VERY confused on how to go about solving this integral. Please help.

A: It is convenient to write the integrand $x^{-x}$ in the form $e^{-xlog(x)}$. This makes it easy to see that the integrand is positive for all $x$, and attains its maximum value when $x= 1/e$. The corresponding maximum value for the integrand of $e^{1/e}$. Since we are integrating over a finite interval (of width $e$), we can conclude that the integral is indeed finite:
$$0 < I < e * e^{1/e}$$

A: As stated in the comments, the function $x^{-x}$ is continuous in the interval (0, e), so it is not necessary to prove or solve anything because
  in any point of this interval the function explodes to infinite or minus infinite. Finding a closed form is something different and I do not believe that this integral has one in which there are no infinite series.
Also remember that $0^ 0$ even if it is an "indeterminate" result, in its limit the function tends to 1.
$\lim_{n\to0^{+}} n^n=1$ and in the same way $\lim_{n\to0^{+}} n^{-n}=1$


text:
Q: Multiple radio button selection without the loading I have gota a form with 2 questions, each with a radio buttons. When I click on a radio buttons either of the questions, I want the event #edit-next to fire, which will make effect on the drupal form
at the moment when i click on 1 questions radio button the event fires but i want 2 radio buttons 1 from each question for the the event to fire
(function ($, Drupal, window, document, undefined) {
$(document).ready(function() {
$('.form-radio').click(function() { $('#edit-next').click(); });
});
})(jQuery, Drupal, this, this.document);

this is the form below
http://goo.gl/bUqvZ
as you can see when you click on one question the whole page loads what i want is when u click on both question then the whole page loads or even better if i could somehow put jquery ajax.

A: Keep the same class name for all radio button ,and i hope left hand side question set and right hand side question set are in diff form.
     $('.form-radio').click(function(){
        if(document.getElementById('radio1').checked &&   document.getElementById('radio2').checked){
            $('#button3').click();
      }
  });

It should work


text:
Q: What are the differences between spatial databases? What is the difference between Oracle Spatial, PostGIS, SQLServer2008, SpatiaLite, and MySQL in terms of their spatial support. Are there specific use cases where each shines. What might you want to avoid with any of these databases.

A: Database Comparison Matrix
In this link you can find the matrix of comparison between databases with spatial capabilities.
http://www.bostongis.com/?content_name=sqlserver2008r2_oracle11gr2_postgis15_compare#221

A: It is a very broad question.

*

*Cost

*Implementation

*Support

*Speed

*Limitations

The bottom line is you get what you pay for.
Oracle Spatial which can only be used with Oracle Enterprise Edition.  One can use Oracle Locator, but has less of the native tools for GIS.  Spatial also has GeoRaster which is an image format stored inside the database.
The next level is SQL Server 2008, but they are very new to the Spatial Storage market.  Most GIS vendors had to build application functionality to service geospatial information in this DB.  But now with spatial capabilities, of which I am not familiar with this.
Now you get into the free world.
PostGIS, SpatialLite, MySQL
PostGIS is the oldest open source, followed by the others.  PostGIS is by far the most mature open source implementation out there.  It seems that there may be limitations to these DB, but for a light implementation, possibly limited in functionality, they are sufficient for the masses.

A: One thing about PostgreSQL/PostGIS is that it is the most likely candidate for having a native interface present in other open source projects.
For example, in QGIS 1.4.0, there is a button sitting right in the menu bar that says "Add PostGIS Layer".
Spatialite also has a toolbar entry,
but there is no similar support for other databases like MySQL.


text:
Q: Cloud CDN for Internal (intranet) Web Site I want to use CDN for caching of static assets for an intranet app currently hosted on GCP.
However this site is only available with privately and has no external access. I understand for CDN I need to have external HTTP load balancer and since external load balancers can only be used for external sites with external IPs, I assume I can't really use CDN of any kind? So my best option is to just host it on Google Cloud Storage buckets?

A: It is possible to create an external load balancer over an instance group who's VMs don't have external IPs, but it would still be exposing the app on an external address.
Buckets might be the way you want to go.


text:
Q: Detect Unexpected Closing of My application Sometimes user presses the home button and close the application from recent list.
I want to warn user with a message like "This application not properly closed last time".
How to detect such unexpected closing of application? Is there any way to do it?
Also i would like to save the data filled by user.
The below method works good but after staying in background for a while and closing the application will not get invoked to this method.
- (void)applicationWillTerminate:(UIApplication *)application

Is there any solution in swift 3.0 ?

A: To save the data filled by the user, you should use the func applicationDidEnterBackground(_ application: UIApplication) function.
This is the function description:

// Use this method to release shared resources, save user data,
  invalidate timers, and store enough application state information to
  restore your application to its current state in case it is terminated
  later.
          // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user
  quits.

As for "This application not properly closed last time" message you want to present the user - it's wrong to show such a message.
The way to close the app is to press the home screen and close it from the list, so this is the expected behavior.

A: Please check this to understand how iOS application lifecycle works - https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html
Now in your project find this following methods to track your app's lifecycle process.
For Objective-C
- (void)applicationWillResignActive:(UIApplication *)application{
      // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application{
     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillTerminate:(UIApplication *)application{
     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
}

For Swift(3.0)
func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
}

Hope this helped.

A: In the Application Delegate, you can check for different events. Check for applicationWillResignActive method or ApplicationDidEnterBackground.
The appropriate location will depend on your usecase.

A: You can do this by listening to UIApplicationWillResignActiveNotification notification.
Detect when home button is pressed iOS

A: This method lets your app know that it is about to be terminated and purged from memory entirely. You should use this method to perform any final clean-up tasks for your app, such as freeing shared resources, saving user data, and invalidating timers. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.
-(void) applicationWillTerminate:(UIApplication *)application{    }

A: You can use AppDelegate Method resignActive for saving data when user send app to background. And save a boolean value true in NSUserDefaults if it launches from didFinishLaunching method and check this boolean and saved data for computation in method didBecomeActive. Using data and boolean value you can show alert and reset both values.

A: If the user kills the app manually while the app is not suspended, the applicationWillTerminate will be called in your app delegate.
When the user just press the home button the applicationDidEnterBackground is called in your app delegate.
If the applicationDidEnterBackground is called, and the applicationWillTerminate is not probably the app was not killed properly.
I said probably because there is no warranty that the applicationWillTerminate is called in case of app kill. In fact if the app is suspended the method will not be called.

For apps that support background execution, this method is generally
  not called when the user quits the app because the app simply moves to
  the background in that case. However, this method may be called in
  situations where the app is running in the background (not suspended)
  and the system needs to terminate it for some reason.

source: https://developer.apple.com/reference/uikit/uiapplicationdelegate/1623111-applicationwillterminate
The scenario when a manual kill would not cause this method to be called is when the user push the home button, and after a while he double press the home button and kill the app. In this scenario iOS would call applicationDidEnterBackground in your delegate when the user press the home button, and after ~5 seconds the app would get the status of suspended. When the user kills the app later on, its status would be suspended, and the willTerminate method would not be called.
the same happens if while suspended iOS kills the app to get resources giving to it the status of terminated.
What I would do is to persist the timeStamp of the applicationDidEnterBackground method call, cancel it on applicationWillEnterForeground and in the applicationWillTerminate.
If the next time that your application(_:willFinishLaunchingWithOptions:) gets called you have a value for the timestamp saved in the applicationDidEnterBackground it means that the user did not manually kill the app (maybe) and he did not come back after putting it in background.
If the user killed the app while the app was suspended, maybe in your case it would still be considered a misuse of the app, and the message can be displayed, so that all the use case are covered.

A: You shouldn't do that but if we are speaking about theory then the solution is to show the alert always except the first run.
I would save a boolean in UserDefaults, let's call it shouldShowWarning.
Everything else can go inside:
UIApplicationDelegate.application(_:didFinishLaunchingWithOptions:)

Inside the method you can check whether shouldShowWarning is true. If it's true, show the warning.
Then set the value to true.
Now if the app is terminated and you return back, the alert will be shown.
If there is some scenario when you are terminating the app from code (which is very non-standard), just set shouldShowWarning to false to disable the warning when the app is restarted.


text:
Q: How to query DynamoDB and return the first matching result instead of querying the whole collection? We have some old code that is doing a query of the DynamoDB to find list of matching records.
Sample code below:
    final DynamoDBQueryExpression<MyObject> queryExp = new DynamoDBQueryExpression<MyObject>()
            .withHashKeyValues(myObject)
            .withIndexName(indexName)
            .withScanIndexForward(false)
            .withConsistentRead(true)
            .withLimit(rowsPerPage);
    final PaginatedQueryList<MyObject> ruleInstanceList = dynamoDBMapper.query(MyObject.class, queryExp);

This is a slow operation since this query will return a list of matching MyObject, and I noticed all we used it for is to check if this list is empty or not.
So what I want to do is simply doing the query to find the first element or even a different type of query to simply make sure the count is greater than 0, all I need to verify is that the record exist so that I can reduce the latency.
My question is, how do I do it in order to achieve this?

A: The documentation for getLimit() indicates:

Note that when calling DynamoDBMapper.query, multiple requests are made to DynamoDB if needed to retrieve the entire result set. Setting this will limit the number of items retrieved by each request, NOT the total number of results that will be retrieved. Use DynamoDBMapper.queryPage to retrieve a single page of items from DynamoDB.

To limit the number of results, you can use queryPage() instead of query(). And apply withLimit(1) to your query expression.


text:
Q: SQL Class Issue - Call to a member function on null - phpBB I know this exact problem has been posted, but none give me a working answer. I have a simple PHP file that includes another php file to instantiate a few classes so that I can connect to my database. I get the error "Call a to member function sql_query() on null". The line that is getting the error is $result = $db->sql_query($sql);. I know that the include($phpbb_root_path . 'common.' . $phpEx); works. I have done var_dump($db) and it is not null, and I do not set that variable anywhere in this file, but in common.php which is included.Here is my php file:
PHP

<?php
//error reporting
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);

define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

//handle ajax post data
if(isset($_POST['action']) && !empty($_POST['action'])) {
  $action = $_POST['action'];

  switch($action) {
   case 'get_vehicle_makes' :
    get_vehicle_makes();
    break;
   case 'get_vehicle_models' :
    get_vehicle_models();
    break;
   case 'test' :
    get_vehicle_years();
    break;
  }
 }

//The vehicle years list will always be the same regardless of make or model  - block_var = "vehicle_years"
 function get_vehicle_years()
 {
  $sql = 'SELECT DISTINCT year FROM phpbb_vehicles';
  var_dump($sql);
  $result = $db->sql_query($sql);

  $data = array();

  while($row = $db->sql_fetchrow($result))
  {
   $data = $row['year'];
  }

  $db->sql_freeresult($result);

  $myArray = array(1, 2, 3);
  echo ("good job");
  exit;
 }

?>

As you can see at the top of my PHP, I include debugging code to display my php log errors, but I get nothing other than the error message. This isn't something obvious, is it?

A: You should pass $db to the function(s) as a parameter, else it wont be in the functions scope, though your global functions would suit a vehicle class, which then you only need to pass the $db instance once.
For example:
<?php
//error reporting
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);

define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include($phpbb_root_path . 'common.' . $phpEx);

class vehicle {

    public function __construct($db)
    {
        $this->db = $db;
    }

    //The vehicle years list will always be the same regardless of make or model  - block_var = "vehicle_years"
    public function years()
    {
        $sql = 'SELECT DISTINCT year FROM phpbb_vehicles';
        var_dump($sql);
        $result = $this->db->sql_query($sql);

        $data = array();

        while ($row = $this->db->sql_fetchrow($result)) {
            $data = $row['year'];
        }

        $this->db->sql_freeresult($result);

        $myArray = array(1, 2, 3);
        echo ("good job");
        exit;
    }

    //.. your other functions
}

//handle ajax post data
if (isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];

    $vehicle = new vehicle($db);

    switch($action) {
        case 'get_vehicle_makes' :
            $vehicle->makes();
            break;
        case 'get_vehicle_models' :
            $vehicle->models();
            break;
        case 'test' :
            $vehicle->years();
            break;
    }
}


text:
Q: Como utillizar dos valor de una funcion en otra funcion El problema dice: Calcule la media de la edad de sus compañeros. La edad es generada aleatoriamente
de entre 18 y 23 años dentro de la función, que realiza la suma y devuelve la suma; la
media es calculada en otra función que recibe la suma y devuelve el resultado.
Todo lo he hecho bien, el problema esta en la segunda función en donde tengo que sacar el promedio solo puedo usar el valor retornado de la función primera que es la suma de las edades. El promedio  da si yo le dejo un valor asignado de mi, pero en realidad va el valor dependiendo cuanto sea el valor que ingrese el usuario. Me explico a continuacion...
 #include <stdio.h>
 #include <conio.h>
 #include <stdlib.h>
 #include <time.h>

float generadorEstudiantes (float alum);

float media (float prom );

int main (){

float prom, alum;

printf ( "\nEL PROMEDIO DE LA EDADES ES DE: %.2f", media (prom));

}

float generadorEstudiantes (float alum){
int i, can;
int rango, n, cd;
srand (time (NULL));
rango = 24-18;

printf ("Ingrese la cantidad de alumnos:\t");
scanf ("%d", &can );

for (i=0; i<can; i++){
n = rand () % rango + 18;
alum += n;
cd = cd + 1;
printf ("\nEstudiante %i: %d", i+1, n);
}
printf ("\n\nLA SUMA DE LA EDADES ES: %.2f", alum);
return alum;
}

En esta función yo le asigne el  valor de 5 para poder sacar el promedio de la suma de las edades, solo lo puse para ver si imprimia bien el promedio. Ahora bien, claro está, que ese no sería el promedio correcto ya que el valor que va donde esta 5 es el contador que esta en la función generadorEstudiantes (float alum), la variable cd que cuenta, cuanta edades se van a ejecutar, esa variable es la que va reemplazar 5, entonces ese es el problema, como hago para pasar esa variable si solo en esa función retorna solo un valor que es alum = es la suma de las edades. Ya intente hacer que la función retorne 2 valores que seria la suma y el contador pero como hago para que se divida y poder sacar el promedio en la segunda función.
float media (float prom ){
float alum, n;
n = generadorEstudiantes (alum);
prom = n / 5;

return prom;
}

A: Apuntes iniciales:

*

*tabula el código. Un código sin tabular es tremendamente complicado de leer y los errores se empezarán a reproducir como si fuesen lindos conejitos. Estás avisado.

*Desde hace más 30 años no es necesario declarar todas la variables al inicio de la función. Esta práctica no es para nada aconsejable pues se alarga innecesariamente la vida de las variables y ahí es cuando podemos acabar reutilizando una variable ... este suele ser el origen de numerosos errores al programar. Intenta que la vida de las variables sea la mínima imprescindible.
Vamos con tu código.
Tienes un problema en las dos funciones que has definido, y es que ambas reciben como parámetro una variable cuyo valor no usan en ningún momento:
float media (float prom ){
//                 ~~~~ <<--- recibes prom como parametro
    float alum, n;
    n = generadorEstudiantes (alum);
    prom = n / 5; // <<--- pero sobreescribes su valor

    return prom;

}

Si la función recibe un parámetro es porque necesita un valor que debe ser proporcionado desde fuera para que la función pueda trabajar correctamente. Si la función no necesita dicho valor, entonces no debería recibir ningún parámetro.
Hablando ahora de la función generadorEstudiantes:

*

*No deberías invocar srand en una función que hace más cosas ... el motivo es que cada vez que llamas a srand modificas la semilla del generador de números. Si esta función se invoca dos o más veces en el mismo segundo (es la precisión de time(NULL)) entonces obtendrás varias veces la misma secuencia de números aleatorios

*alum no debería ser un float sino un entero. En esta función no tienes ninguna necesidad de recurrir al uso de decimales. De hecho debería tener un nombre más adecuado, como suma_edades. Un código facil de leer te dara menos problemas.
int generadorEstudiantes ()
{
int rango = 24 - 18;
  int numero_alumnos;
  printf ("Ingrese la cantidad de alumnos:\t");
  scanf ("%d", &numero_alumnos);

  int suma_edades = 0;
  for (int i=0; i<numero_alumnos; i++){
      int edad = (rand () % rango) + 18;
      suma_edades += edad;
      printf ("\nEstudiante %i: %d", i+1, n);
  }
  printf ("\n\nLA SUMA DE LA EDADES ES: %d", suma_edades);
  return suma_edades;

}
Adelantándonos un poco al siguiente problema, esta función no debería pedir el número de alumnos, ya que este dato va a ser necesario para poder calcular la media. Este es un dato que o bien podemos pedir en una función independiente o bien directamente en el main:
int NumeroAlumnos()
{
    int numero_alumnos;
    printf ("Ingrese la cantidad de alumnos:\t");
    scanf ("%d", &numero_alumnos);

    return numero_alumnos;
}

Ahora sí tendría sentido que numeroAlumnos reciba un parámetro. Fíjate que ahora la función tiene un parámetro y, a cambio, pierde el código que inicializaba la variable.
int generadorEstudiantes (int numero_alumnos)
{
    int rango = 24 - 18;

    int suma_edades = 0;
    for (int i=0; i<numero_alumnos; i++){
        int edad = (rand () % rango) + 18;
        suma_edades += edad;
        printf ("\nEstudiante %i: %d", i+1, n);
    }
    return suma_edades;
}

Ahora vamos a por la función media. Esta función no debería llamar a generadorEstudiantes directamente sino que lo suyo sería pasarle la suma y el número de valores para que pueda calcular el promedio:
float media(int numero_alumnos, int suma_edades)
{
    return numero_alumnos / (float)suma_edades;
}

Y ya solo nos quedaría enlazar todas estas funciones en el main:
int main()
{
    srand (time (NULL));

    int numero_alumnos = NumeroAlumnos();

    int suma_edades = generadorEstudiantes (numero_alumnos);
    printf ("\n\nLA SUMA DE LA EDADES ES: %d", suma_edades);

    float promedio = media(numero_alumnos, suma_edades);

    printf ("\n\nLA SUMA DE LA EDADES ES: %.2f", promedio);
}


text:
Q: Domain Name Forwarding not working with github pages I had my blog on github pages with a custom domain name blog.tamizhvendan.in and today I've moved it to a new domain name www.p3programmer.com by updating the CNAME record with www.p3programmer.com.
The new domain name is working fine.
As it is a breaking change, I would like to have a domain redirection which redirects the old one to the new one. I've configured the same in my DNS Server (BigRock) using their Domain Forwarding System. After that, tamizhvendan.in is redirecting correctly to www.p3programmer.com but blog.tamizhvendan.in resulting in 404 in github pages. By BigRock's documentation, for subdomains will be redirect to path www.example.com\{subdomain} i.e in this scenario it should redirect to www.p3programmer.com\blog but it is not redirecting.
I've added a CNAME record in the tamizhvendan.in account with the value pointing to www.p3programmer.com but yet I am getting github page's 404 page error.
Here is my dig output of blog.tamizhvendan.in
; <<>> DiG 9.10.1-P2 <<>> blog.tamizhvendan.in +nostats +nocomments +nocmd
;; global options: +cmd
;blog.tamizhvendan.in.          IN      A
blog.tamizhvendan.in.   2658    IN      CNAME   www.p3programmer.com.
www.p3programmer.com.   1818    IN      CNAME   tamizhvendan.github.io.
tamizhvendan.github.io. 427     IN      CNAME   github.map.fastly.net.
github.map.fastly.net.  30      IN      A       23.235.44.133

Dig output of www.p3programmer.com
;; global options: +cmd
;www.p3programmer.com.          IN      A
www.p3programmer.com.   1740    IN      CNAME   tamizhvendan.github.io.
tamizhvendan.github.io. 349     IN      CNAME   github.map.fastly.net.
github.map.fastly.net.  30      IN      A       23.235.40.133

A: did you follow the following steps?
https://help.github.com/articles/adding-a-cname-file-to-your-repository/

A: Github seems to only support one external domain per repository, at least according to their documentation Adding a CNAME file to your repository:

Note that there can only be one domain in the CNAME file.

So you need a page which answers all request to blog.tamizhvendan.in with a 301:
HTTP/1.1 301 Moved Permanently
Location: http://www.p3programmer.com/


text:
Q: Disable the html page resizing Hi I want to disable the resizing the html web page by the user. How to do that
I want to disable the resize button and manual resizing by dragging. pls help

A: You can't, thank God.
When you open a new popup you can request it be unresizable using the feature resizable:
window.open('something.html', '_blank', 'resizable=no');

however modern browsers may ignore your request as it is considered egregiously user-hostile.
Use liquid layout to make your page respond flexibly to changes in window size, rather than attempting to set it in concrete. The web is inherently a variable-size medium, and mobile browser users get no input in how large their screen is anyway.

A: Pardon? Are you talking about resizing the browser window? If that's the case then you can't do this in HTML, or JavaScript as it would be a security risk allow web pages to control browsers behaviour.
If you want to get rid of scroll bars you can set the body tag to 'overflow: hidden' in CSS?

A: If you mean to stop the page shrinking and expanding in sympathy with browser window size, then use fixed width elements as supposed to relative (%)


text:
Q: Stuck in weird issue with nginx reverse proxy - need help pls I am stuck in this weird issue. I have nginx as my reverse proxy set in front of Apache web server Some how my proxy_pass is not working as expected and getting 404 not found error while retrieving page. Can someone pls help?

Reve Proxy IP - 10.122.0.4
Apache 10.122.0.3

On my Rev Proxy /etc/hosts file
10.122.0.3 ipbl.xxxx.xxx
Here is my nginx stanza
server {
listen 80;
server_name threat.list.xxx.xxx;
# return 301 https://$server_name$request_uri;
add_header X-Frame-Options "SAMEORIGIN";
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
error_page 404 403 /custom_404.html;
location = /custom_404.html {
root /usr/share/nginx/html;
internal;
}
access_log /var/log/nginx/threatlist/access.log;
error_log /var/log/nginx/threatlist/error.log;
location / {
if ($request_method !~ "GET") {
return 403;
break;
}
include /etc/nginx/threatlistacl/ipacls;
deny all;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
proxy_temp_file_write_size 256k;
proxy_connect_timeout 30s;
proxy_pass http://ipbl.xxxx.xxxx;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

Now if I access ipbl.xxx.xxx/ipbl.txt page it gets accessed successfully
Request URL: http://threat.list.xxx.xxx/ipbl.txt
Request Method: GET
Status Code: 404 Not Found
Remote Address: xxx.xx.xx.xx:80
Referrer Policy: strict-origin-when-cross-origin
Connection: keep-alive
Content-Type: text/html; charset=iso-8859-1
Date: Sat, 13 Mar 2021 04:50:53 GMT
Server: nginx
Transfer-Encoding: chunked
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.9
Connection: keep-alive
DNT: 1
Host: threat.list.xxx.xxx
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36

And my access.log
xx.xx.xx.xx - - [13/Mar/2021:10:31:17 +0530] "GET /ipbl.txt HTTP/1.1" 404 183 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"

A: I posted my virtualhost config in apache2.conf and deleted my ipbl.conf file from sites-enabled somehow that worked. Plus I added entries in /etc/hosts [not sure if this is required to match ServerName]


text:
Q: jQuery trigger on variable change I have a setup where i load many modules as required, each module has a specific load needs when a specific variable is changed. I need something like jquery trigger but that runs when a variable change, something like this:
var x = 0; // no triggers

// something happens

x = 1; // will trigger a function
x = 2; // will trigger the same function

Thanks.

A: Perhaps you could create an object that contains a set_x method to change the value of the variable. In addition to changing the variable, this method could call any associated triggers.
Then instead of setting x directly, you would use this new method:
my_obj.set_x( 2 ); // Will trigger a function

A: How about this?
var x = {
    value: 10
}

var set = function(obj, new_value) {
    obj.value = new_value;
    /* call whatever your heart desires here */
}

So you can do:
set(x, 2);
// now x.value = 2


text:
Q: How can I fix this:error CS0234 in Unity? error CS0234: The type or namespace name 'CrossPlatformInput' does not exist in the namespace
'UnityStandardAssets' (are you missing an assembly reference?)
       enter code here:
        using System.Collections;
        using System.Collections.Generic;
        using UnityEngine;
        using UnityStandardAssets.CrossPlatformInput;
        using UnityEngine.UI;

        public class TrumpController : MonoBehaviour
        {

             private Animation anim;

             private Rigidbody rb;

             void Start()
             {
               anim = GetComponent<Animation>();
               rb = GetComponent<Rigidbody>();
             }

             void Update()
             {

                float x = CrossPlatformInputManager.GetAxis("Horizontal");
                float y = CrossPlatformInputManager.GetAxis("Vertical");

                Vector3 movement = new Vector3(x, 0.0f, y);

                rb.velocity = movement * 4f;

                if (x != 0 && y != 0)
                {
                transform.eulerAngles = new Vector3(transform.eulerAngles.x, Mathf.Atan2(x, y) *
                Mathf.Rad2Deg, transform.eulerAngles.z);
                }

                if (x != 0 || y != 0)
                {
                 anim.Play("walk");
                }
                else
                {
                 anim.Play("idle");
                }
             }
        }

So I am creating my first game in unity. I am currently working on the left to right movement and getting error:

A: I think CrossPlatformInput is under 'UnitySampleAssets' and not under 'UnityStandardAssets'" So you need to add an assembly reference:
using UnitySampleAssets;


text:
Q: Reuse ViewModel materializer in multiple EF queries? I'd like to reuse the method that hydrates a view model from an Entity Framework 6 IQueryable<TEntity>. Most intuitively to me, that would look something like this:
ViewModel ToViewModel(Record record) {
    return new ViewModel {
        Title = record.Title
    }
}

// Get a single ViewModel
ViewModel GetRecord(int id) {
    return ToViewModel(Context.Records.Find(id));
}

// Get multiple ViewModels
IEnumerable<ViewModel> GetRecords() {
    return
        from record in Context.Records
        select ToViewModel(record);
}

Unfortunately EF tries to send the ToViewModel() method to the database, so enumerating the query result causes an Exception similar to "this method cannot be translated into a store expression".
Typically I'd prefer not to load the entire Entity<Record> (and all related objects referenced in the initializer) over the wire for performance reasons, otherwise I could do the following:
IEnumerable<ViewModel> GetRecords() {
    return
        from record in Context.Records.ToList()
        select ToViewModel(record);
}

I feel like I'm overlooking something fairly simple with Expression typing. Thoughts?

A: Yes, you think correctly that you should use Expression. Prepare the method, and a new helper, like this:
public static Expression<Func<Record, ViewModel>> GetToViewModelExpression() {
    return r => new ViewModel {
        Title = r.Title
    };
}

public static ViewModel ToViewModel(Record record) {
    return GetToViewModelExpression().Compile()(record);
}

And use it in your dependent methods like this:
// Get a single ViewModel
ViewModel GetRecord(int id) {
    return ToViewModel(Context.Records.Find(id));
}

// Get multiple ViewModels
IEnumerable<ViewModel> GetRecords() {
    return Context
        .Records
        .Select(GetToViewModelExpression());
}