text:
Q: Logging framework being injected into classes Should a logging framework be injected into classes that need them or should every class that needs it just know the framework and use it directly?  I am using Log4Net and currently I am injecting a service that wraps that framework into the classes that need to be able to log, knowing logging is probably not going to change and that most pieces need it, is injecting the answer in this sense?

A: Injection is more flexible in the long run, since you can easily selectively inject into certain places and disable logging selectively, etc.

A: I think there is nothing wrong with injecting it.  They recommend using static variables merely for performance reasons, but I see little difference between this and injecting a logger at start up.

A: If memory performance is not that much of an issue you might consider AOP, e.g. using PostSharp. That way your classes don't need to know the logger at all. You basically inject IL-code right into your assembly as a postbuild step. PostSharp uses attributes for marking methods, classes and even whole assemblies. There's even a plugin for using log4net for the logging concern.
EDIT:
I mentioned memory because with each attribute you create a new object for each join point.

A: Even though you stated that logging isn't going to change, I suggest to abstract away from a specific logging framework. Injecting a logger instance however isn't needed in all cases.
Take CommonLogging (see this Stackoverflow answer for a short description of what Common.Logging is) for instance: Your class talks directly to the factory (LoggerManager) but you are not bound to a specific logger implementation.

A: If you are talking about dependency injection (say in the Spring.NET sense) then it doesn't much matter - though you don't get much value from multiple copies of logger instances. Typically, each logger instance returned by a framework with a specific class/name will be a singleton anyway, so the question is whether you want to clutter each instance with a logger reference, rather than a single static reference per class. If you are concerned about changing logger implementations, then log to an interface (CommonLogging, mentioned in another answer, does this, and supports both log4net and Enterprise Library implementations).
If you are talking about injection using AOP, then I'm not sure that beyond a certain point, AOP injection is more flexible. You are pretty much limited to logging entry, exit and exceptions with method-level granularity.AOP Injection is more of a scatter-shot approach, even if you use AOP to selectively inject into parts of your code. Although logging is touted as a cross-cutting concern of the kind which which is ideal for AOP, I've never found AOP-based logging to be much use in practice (YMMV, of course).

A: CSharpAtl,
I am curious as to exactly how you are injecting Log4net?  See my question/community wiki here.
I also saw your answer to a DI/Log4net question here.
Most logging injection examples that I have seen show a class having a "logger" injected, something like this:
public class Foo
{
  private ILogger logger;

  public Foo(ILogger logger) //Injection via constructor
  {
    //Which "named" logger is this anyway?  Is it Foo's?  If so, how is it Foo's?
    this.logger = logger;
  }

  public DoSomeWork(int xyz)
  {
    logger.Info("xyz = {0}", xyz);
  }
}

With something like Log4net (and NLog, and maybe others), you typically create a logger like this:
public class Foo
{
  private static ILogger logger =
          LogManager.GetLogger(
              System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

  public Foo()
  {
  }

  public DoSomeWork(int xyz)
  {
    logger.Info("xyz = {0}", xyz);
  }
}

So, how does my class, Foo, get the correct logger if I dependency inject?  Also, maybe I am not naming my loggers based strictly on the class.  Rather, I might name them based on functional area (like "DatabaseAccess", "AppStartup", "AppShutdown", etc) that might not be derivable from type.
Are you injecting a "Logger" (that would correspond to a named logger), or a "LogManager" (that would correspond to Log4net's LogManager), or are you doing something else?  Do you use a configuration capability of a DI platform to associate "named instances" of injected dependencies?  I think that Unity supports something like this, although I am not really sure.
Here is how I would imagine injecting a "LogManager" would work:
public class Foo
{
  private static ILogger logger;

  public Foo(ILogManager logManager) //Injection via constructor
  {
    logger = logManager.GetLogger
                    (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    //Since logger is (should it be?) static, maybe should be like this:

    if (logger = null)
    {
      logManager.GetLogger
                 (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    }
  }

  public DoSomeWork(int xyz)
  {
    logger.Info("xyz = {0}", xyz);
  }
}

It seems to me that injecting something like ILogManager (the implementation of which would wrap Log4net's LogManager) would be easier than injectng ILogger, because of the question of how the DI platform would know which ILogger to inject.
I am new to DI and .NET logging platforms (and actually, pretty new to C# and .NET in general).  The vast majority of my experience over the last many years is VB6 + VC++ 6.
Thanks for ANY info ...
Begin edit ...
I have looked around on SO some more and have found that you have also asked about AutoFac, so I am guessing that you are using this for your DI.  If that is true, then I guess that you are also doing something like this or, apparently even better, like this to resolve your logger (by class type).  I guess that answers the question of how, at least in AutoFac, to inject named loggers (such as from Log4Net or NLog).
End edit ...


text:
Q: How to handle a real world multiple inheritance scenario in .Net? I've heard of the pitfalls of multiple inheritance before, and I know the .Net devs are against it's inclusion.
With that said, consider a simple example such as 'Game Companies'. A game company can be:

*

*a software developer, like Platinum Games

*a publisher, like for instance Agetec

*a developer AND publisher at the same time, as in Blizzard Entertainment

*a gaming hardware manufacturer only (don't have examples of a company that is solely a manufacturer in hand)

*all of the above, i.e. Nintendo
If I had to model this in .Net, how would I go about the fact that the "is a" relationship is present and a company can be multiple of those at the same time? Imagine that I have modeled a:

*

*Game class, having List<Developer> and Publisher as properties

*Console class that had a Manufacturer property.

In an ideal scenario, this should be as type safe as possible and easy to filter and navigate to and from each class (like a fully connected Entity Framework mapping of sorts).
I thought about something in the same vein, for which I probably known the 'right' answer.
What if I had FatPerson and TallPerson as base classes and wanted to 'work around' the multiple inheritance limitation? Because it's quite possible to have someone who is both fat and tall at the same time. In this case, it would probably be cleaner if there was a single Person had two properties, Weight and Height, eliminating the base classes altogether. It would be just a matter of rewriting whatever filtering I had before that was based around the type of the objects to consider these new properties.
Is there something inherently equivalent to this for every multiple inheritance case? What about for this particular case I proposed?
Update:
I've read that answer that is marked as a duplicate of mine (before posting this one), but I disagree slightly here. I think this is the same as marking a SQL optimization question as duplicate of every other SQL optimization question. In the end, each case is a different case, and would require a different approach/answer. I think this applies here since I asked about a very fixed case, like the other answer did.

A: This scenario is a good example for Role Based Software Engineering which is a current topic in research. That's because there is no one and only solution to the problem. There are several approaches, but all of them have their drawbacks.
Interfaces are a good way to design the relation of types. If you make e.g. Developer and Publisher interfaces, there can be companies that are both. However, you cannot inherit code from interfaces and you usually end up with lots of duplicate code.
Going one step further, you come up with mixin inheritance. That's basically interface implementation augmented with extension methods. Take a look at this example:
class Company { }

interface Publisher { }
public static class PublisherMixin
{
    public static void Publish(this Publisher p)
    {
        //do something
    }
}

class CompanyThatIsAPublisher : Company, Publisher { }

And then you can do
var c = new CompanyThatIsAPublisher():
c.Publish();

You can do this for several mixins. You can even provide state for the mixins with the help of weak reference dictionaries.
Another way to avoid code duplication is delegation. You still have your interface hierarchy, but create objects for the developer role, the publisher role etc. The company then just forwards method calls to these sub-objects. However, this results in object schizophrenia. The sub-objects do not really belong to the main object which can pose a problem. However you can easily exchange them.
In C# you could also use a DynamicObject. With this you could dynamically register roles and dynamically reroute method calls to the appropriate objects. So a developer company can become a publisher eventually without having to loose its identity. This approach also suffers from the object schizophrenia problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Building angular library at ng serve I am struggling with my angular library development. First of all, I am building an angular 8 library (current cli version 9) and I want to live see my library code changes while I am serving the demo app in which I am using this library.
Current behavior: When I am making changes on library source code, angular demo application reloads but I am non seeing any changes to take affect. This behavior was mainly applied with css changes and not every time on a .ts file.
Expected behavior: To being able to see every change I am making on the library source code.
Current angular.json file
    {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "bDataTableDemo": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/bDataTableDemo",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": false,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "bDataTableDemo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "bDataTableDemo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "bDataTableDemo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "bDataTableDemo:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "bDataTableDemo:serve:production"
            }
          }
        }
      }
    },
    "ng-bootstrap-table": {
      "projectType": "library",
      "root": "projects/ng-bootstrap-table",
      "sourceRoot": "projects/ng-bootstrap-table/src",
      "prefix": "lib",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-ng-packagr:build",
          "options": {
            "tsConfig": "projects/ng-bootstrap-table/tsconfig.lib.json",
            "project": "projects/ng-bootstrap-table/ng-package.json"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "projects/ng-bootstrap-table/src/test.ts",
            "tsConfig": "projects/ng-bootstrap-table/tsconfig.spec.json",
            "karmaConfig": "projects/ng-bootstrap-table/karma.conf.js"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "projects/ng-bootstrap-table/tsconfig.lib.json",
              "projects/ng-bootstrap-table/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "bDataTableDemo"
}

And my tsconfig.json file
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "ng-bootstrap-table": [
        "dist/ng-bootstrap-table"
      ],
      "ng-bootstrap-table/*": [
        "dist/ng-bootstrap-table/*"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

What should I change in order to have the expected behavior?
P.S. I am new to angular libraries, so I can't find a solution yet.
Thank you in advance!!

A: You should edit the paths in tsconfig to point to your library's index.ts instead of dist/ - which is the built artifact generated with ng build my-library:
"my-library" : [ "libs/my-library/index.ts" ]

A: Well, I have been working on this approach and, I have been able to see the library change in my app using npm-link

*

*On your library

*

*Open the terminal and execute npm run build

*Then, navigate on the terminal to the dist/pkg folder and run the command npm link

*Copy the library name exposed in the result from the npm link

*On your app

*

*On the angular.json file search the path projects.project-name.architect.build.options and, add the following property: "preserveSymlinks": true

*Open the terminal and run the command npm link <name-of-your-library>


text:
Q: Какая функция для того чтобы записать текст в буфер обмена Собственно все в заголовке
"Какая функция для того чтобы записать текст в буфер обмена"  В C++

A: Пример записи и чтения текста в буфер обмена для ОС Windows. (Подробнее)
CString source; //в эту переменную нужно записать текст, который в дальнейшем поместится в буфер обмена
//запись текста в буфер обмена
if(OpenClipboard())//открываем буфер обмена
{
   HGLOBAL hgBuffer;
   char* chBuffer;
   EmptyClipboard(); //очищаем буфер
   hgBuffer= GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);//выделяем память
   chBuffer= (char*)GlobalLock(hgBuffer); //блокируем память
   strcpy(chBuffer, LPCSTR(source));
   GlobalUnlock(hgBuffer);//разблокируем память
   SetClipboardData(CF_TEXT, hgBuffer);//помещаем текст в буфер обмена
   CloseClipboard(); //закрываем буфер обмена
}

//чтение текста из буфера обмена
CString fromClipboard;//в эту переменную сохраним текст из буфера обмена
if ( OpenClipboard() )//открываем буфер обмена
{
   HANDLE hData = GetClipboardData(CF_TEXT);//извлекаем текст из буфера обмена
   char* chBuffer= (char*)GlobalLock(hData);//блокируем память
   fromClipboard = chBuffer;
   GlobalUnlock(hData);//разблокируем память
   CloseClipboard();//закрываем буфер обмена
}


text:
Q: Does anyone have a Windows "at /every:" example to explain how to setup a batch file to run the first sunday of every month? This is the one I have to run first day of the month, but I need to run it the first sunday of every month.
at 13:00 /every:1 D:\DBMaintenance\MySc.bat
Thanks

A: You can't do this with the at command.  It only allows for either EVERY Sunday or NEXT Sunday.
You'll need to use Scheduled Tasks instead.  Either with the gui or via cli.
I'll steal this one from Hyppy as an example:
SCHTASKS /Create /SC MONTHLY /MO first /D SUN /TN GameTime /TR c:\windows\system32\frecell


text:
Q: Convert the L.H.S to the form of the R.H.S by completing the square. Given that $x^2-3x+5=(x-p)^2+q$ for all values of $x$, calculate the value of $p$ and of $q$.
A book example tells me to firstly convert the L.H.S to the form of the R.H.S by completing the square.
How to convert it? Can anyone explain me how to do it? Can you show me the steps? HELP!

A: $x^2−3x+5=(x-1.5)^2-2.25+5=(x-1.5)^2+2.75$
Motivation: So look at the expansion of $(x+a)^2$, this is $x^2+2ax+a^2$, can you see the reason why we half the coefficient of the x and why I subtracted by $2.25$?

A: You always have to take half of the linear coefficient, put that in the bracket and subtract the square of half the coefficient to make up for it:
$$\begin{align}
x^2\color{red}{-3}x+5 &=\left(x+\frac{\color{red}{-3}}{2}\right)^2-\left(\frac{\color{red}{-3}}{2}\right)^2+5\\
&=\left(x-\frac{3}{2}\right)^2 - \frac{9}{4} + \frac{20}{4}\\
&=\left(x-\frac{3}{2}\right)^2+\frac{11}{4}
\end{align}
$$
The reason for this is the binomial formula:
$$(x+\color{red}{a})^2=x^2+2\color{red}{a}x+\color{red}{a}^2$$

A: $x^2-3x+5$
$=x^2-3x+\frac94-\frac94+5$
$=(x-\frac32)^2+\frac{11}4$

A: You must first make sure the LHS is in standard form and is a monomial (the coefficient of the leading term must be 1) then you would complete the square by taking the "b" term and dividing it by 2 and squaring it and adding it to the equation but also subtracting it (basically you're adding 0). You should have something of the form $(ax^2+bx+(b/2)^2)-(b/2)^2$. From this you can see the values for p and q once you realize you can factor the polynomial in parenthesis.


text:
Q: What do I need to install on a Windows Server 2012 64-bit box to deploy an ASP.NET MVC project under IIS using DNX SDK version 1.0.0-beta8 I have published a website in VS2015 built using ASP.NET 5 and MVC 6 and configured it in IIS on a different server but I am getting an HTTP404 error when I try to Browse the application. The deployment from VS2015 uses DNX SDK version 1.0.0-beta8. Do I need to install anything else on the IIS server in order to get this to work does anybody know?

A: By following this guide I was able to do the installation: Really helpful guide: [http://docs.asp.net/en/latest/publishing/iis.html][1]


text:
Q: How to use Data Connection created in Visual Studio in code? Is it possible to access the Data Connection added to the project in the code?
I know that it is possible to access DataSets created using visual designer but I would like to access the connection only.
Edit:
It is possible to add Data Connection to the project in VS2008 via Tools > Connect to Database.
I would like to access this connection as an object in my code so that I would not have to specify connection string by myself.

A: I don't think you can directly use the connection created by the IDE as if it were one of your project's settings.  However, the IDE provides similar functionality through the project properties.
How you get to the properties varies slightly on which language/default configuration you are using.  But in general you should be able to try these steps and see if they provide the functionality you wanted:

*

*Open your project.

*Find your project in the Solution Explorer and select the project.

*On the Project menu, choose the 'ProjectName' Properties menu item.

*The project properties tab should open.  Select the "Settings" blade.

*If you have no settings you will be given the option to create a settings file.  Do so if necessary.

*In the grid that is displayed, choose the first blank row and type "ConnectionString" into the name field.

*In the type drop-down, choose (Connection String)

*Click in the value field.  When you activate this field, a little expansion button labeled "..." should appear.  Click it.

*This will bring up a Connection settings dialog box.

*Choose your sever from the available drop-down.

*Configure your log on credentials to your liking.

*Select your database from the available drop-down.

*Test connection.  If it is OK, then Click OK twice to return to the settings page.

*Save your settings.

Now you should be able to access this connection string from your project code.
VB.Net:
Dim cs = My.Settings.ConnectionString

C#:
var cs = Properties.Settings.Default.ConnectionString;


text:
Q: compiler warning: left shift of negative value I think GCC is wrongfully producing a [-Wshift-negative-value] warning.
I have a function that should produce a suffix mask of a certain length provided by its single input argument:
#include <stdint.h>

uint16_t get_suffix_mask_sht(uint8_t shift) {
    return (~(~((uint16_t) 0) << shift));
}

I have tried to compile this function with the following compiler options on different versions of gcc
-Werror -Wextra

This warning also occurs if I change the output from uint16_t to uint8_t. Bigger output types, i.e. uint32_t don't produce this warning.
I am using an older version of GCC: 7.4. But I have tried this out on godbolt using the latest GCC 9.x versions and they all produce the same warning. Clang versions however do not produce this error.

A: When variables smaller than int (like e.g. uint16_t) are used with the bitwise complement operator ~ they are promoted to int.
The type int is signed, and will not work well with shifting. Especially considering that ~0 will be -1 with two's complement notation (which is the most common notation for representing negative numbers on binary systems).
A possible solution is to use larger unsigned types (like unsigned int) and then use masking to get the relevant bits for the smaller type when done.

A: Warning is correct.
~((uint16_t) 0) results in negative value, because result of (uint16_t) 0 is promoted to int before bitwise complement is performed.
In general you should prefer unsigned integers (wide enough to avoid type promotion) when using bit shifting. My suggestion would be to use unsigned int zero instead:
return (~(~0U << shift));


text:
Q: R: anova(lm) anova(lm, lm2) interaction term result different? I am trying to test the interaction term of level1 * question. I have two ways, using anova(lm) and anova(lm, lm2). Why their results are so different?
Code
pacman::p_load(nlme)
data_long = read.csv("https://raw.githubusercontent.com/slfan2013/Jen-Falbe---menu-labeling---Dec-2020/main/STATA/data_long.csv?token=ADGNCRVI2JVHC72URESWLFS765ALK")[,-1]
lm = lme(pme ~ level1 * question, random = ~1 | subject, data = data_long)
lm2 = lme(pme ~ level1 + question, random = ~1 | subject, data = data_long)

Results
> anova(lm)
                numDF denDF   F-value p-value
(Intercept)         1  2648 21598.329  <.0001
level1              2  1324     8.981  0.0001
question            2  2648    17.354  <.0001
level1:question     4  2648     0.857  0.4888

> anova(lm, lm2)
    Model df      AIC      BIC    logLik   Test  L.Ratio p-value
lm      1 11 11853.99 11923.15 -5915.995
lm2     2  7 11838.61 11882.62 -5912.303 1 vs 2 7.383951  0.1169

I don't understand why the interaction p-value from the first method is 0.4888 and the second is 0.1169, which is too different.

A: The default optimization criterion of lme is restricted maximum likelihood (REML). REML is not compatible with likelihood ratio tests. You need to refit your models with maximum likelihood, method = "ML", to compare them on the basis of a likelihood ratio test. Doing so, we see more agreement with the F test.
lm <- lme(pme ~ level1 * question, random = ~1 | subject, data = data_long, method = "ML")
lm2 <- lme(pme ~ level1 + question, random = ~1 | subject, data = data_long, method = "ML")

anova(lm, lm2)

The output is
    Model df      AIC      BIC    logLik   Test  L.Ratio p-value
lm      1 11 11822.01 11891.20 -5900.007
lm2     2  7 11817.45 11861.47 -5901.725 1 vs 2 3.435362  0.4878

If you do not use maximum likelihood to fit your mixed effects models, anova(lm, lm2) will complain with a warning that the comparisons are not meaningful!


text:
Q: Array List printing wrong numbers I am new to C++ and I am trying to write a program to take in a set of results of an exam and print them out in a histogram.  I am writing the code in stages and at this moment I am trying to get it to take in the exam marks and then print them out in a list just to make sure it is working before moving on to the histogram.
My problem is that when I input my numbers into my array and then print them I get a weird number coming up, say for example I enter the numbers 1,2,3,4
Expected console output:
1
2
3
4
Actual output:
-858993460
1
2
3
4
so I know this must be a problem with my code however I am not sure what can anyone help please?
Code:
void readExamMarks(int examMarks[], int sizeOfArray){

   cout << "Please enter a set of exam marks to see a histogram for:" << endl;
   for( int x = 0; x < sizeOfArray; x++){
      cin >> x;
      examMarks[x] = x;
   }
}

void printExamMarks(int examMarks[], int sizeOfArray){

    system("cls");
    for(int x = 0; x < sizeOfArray; x++){

        cout << examMarks[x] << endl;
    }
}

int main()
{
    int examMarks[5];

    readExamMarks(examMarks, 5);
    printExamMarks(examMarks,5);

    system("PAUSE");
}

A: You are reusing x for both your array index and the data:
for( int x = 0; x < sizeOfArray; x++){
    cin >> x;
    examMarks[x] = x;
}

You need to use a separate variable for the array index:
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
    cin >> x;
    examMarks[idx] = x;
}

A: Problem is here:
for( int x = 0; x < sizeOfArray; x++){
   cin >> x;
   examMarks[x] = x;
}

You are using the x as array index, and always accepts x as input value.

A: for( int x = 0; x < sizeOfArray; x++){
    cin >> x;

You are reading into the loop iterator. It should be
int temp
for( int x = 0; x < sizeOfArray; x++){
    cin >> temp;
    examMarks[x] = temp;


text:
Q: Is rename refactoring working for somebody in strongly typed razor views? I have a model that looks like this:
public class Person
{
     public string PostalCode {get;set;}
}

Then I have a razor view
@model MvcApp1.Person

Your location is: @Model.PostalCode

When I am using Visual Studio's 2010 rename refactoring (Ctrl+R,R) the property gets renamed on the model class, but stays the same in the view.
My understanding is that since the view is strongly typed, renaming should have also happened in the view.
What am I doing wrong?

A: VS's refactoring engine doesn't support Razor.


text:
Q: ValueError when combining Tensorflow with Sklearn's Sparse Matrices Hello and let me start with by saying my experience with StackOverflow is extremely limited likewise with my experience programming. Needless to say, if I make any unintentional mistakes in the format of StackOverflow or the format of my code, I apologize and am welcome to edit my post.
I've done extensive research so to not create a duplicate and found posts like this one but no matter how hard I try, I either cant derive meaning from the post, or have too little knowledge in how to implement it
So here's my problem:
I'm making similar to a sentiment analysis machine learning algorithm, and I use Sklearns CountVectorizer and Tfidf on about 6,000 tweets, which turned into the following
<6612x9703 sparse matrix of type '<class 'numpy.float64'>
with 47719 stored elements in Compressed Sparse Row format>
From there I try to train on it using the following function:

X = tf.placeholder("float", [None, X_train_spmx.shape[0]])
y = tf.placeholder("float")

def train_neural_net(x):
prediction = neural_net_model(x)

cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction, labels=y) )
optimizer = tf.train.AdamOptimizer().minimize(cost)

hm_epochs = 10
with tf.Session() as sess:

    sess.run(tf.global_variables_initializer())

    for epoch in range(hm_epochs):
        epoch_loss = 0

        i = 0
        while i < len(y_train):
            start = i
            end = i+batch_size

            batch_x = np.array(X_train_spmx[start:end])
            print(batch_x)
            batch_y = np.array(y_train[start:end])
            print(batch_y)

            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
            epoch_loss += c

        print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)

    correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
    print('Accuracy:',accuracy.eval({x:X_test, y:y_test}))

train_neural_net(X)

However when I run I get the error:
    ValueError                                Traceback (most recent call
    last)
    <ipython-input-16-8130c429fbca> in <module>()
         32         print('Accuracy:',accuracy.eval({x:X_test, y:y_test}))
         33
    ---> 34 train_neural_net(X)

    <ipython-input-16-8130c429fbca> in train_neural_net(x)
         23                 print(batch_y)
         24
    ---> 25                 _, c = sess.run([optimizer, cost], feed_dict= .
  {x: batch_x, y: batch_y})
         26                 epoch_loss += c
         27

    /anaconda3/lib/python3.6/site-
   packages/tensorflow/python/client/session.py in run(self, fetches,
    feed_dict, options, run_metadata)
        903     try:
        904       result = self._run(None, fetches, feed_dict, options_ptr,
    --> 905                          run_metadata_ptr)
        906       if run_metadata:
        907         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

    /anaconda3/lib/python3.6/site-
   packages/tensorflow/python/client/session.py in _run(self, handle,
    fetches, feed_dict, options, run_metadata)
       1104             feed_handles[subfeed_t] = subfeed_val
       1105           else:
    -> 1106             np_val = np.asarray(subfeed_val,
    dtype=subfeed_dtype)
       1107
       1108           if (not is_tensor_handle_feed and

    /anaconda3/lib/python3.6/site-packages/numpy/core/numeric.py in
    asarray(a, dtype, order)
        490
        491     """
    --> 492     return array(a, dtype, copy=False, order=order)
        493
        494

    ValueError: setting an array element with a sequence.

Edit:
After a recommendation that I turn the Spare Matrix into an array using .toarray() , I receive the error ValueError: Cannot feed value of shape (128, 9703) for Tensor 'Placeholder_2:0', which has shape '(?, 6612)'
 I researched and believe it is not the same as here as I have different values in the PlaceHolder, meanwhile the link had different Dimensions. Still unsure on where to go, thanks!
Any Ideas? Thanks in advance


text:
Q: Linux machine can't find its tape drive I have an older HP NetServer LPr with what is apparently a Symbios SCSI card connecting to a Quantum SuperLoader 3 that is DLT based.  From time to time, we seem to lose the connection to the autoloader.  It's usually due to flaky power, but not totally sure why; sometimes when this happens the Autoloader's LED's are orange and it needs to be power cycled. The annoying workaround currently is to reboot the machine.  As it is our production VPN and DNS server in addition to being our backup server, this is less than optimal.
In Debian (Sarge) is there not some command one can type to get the card to notice that it has the autoloader connected again?
dcr1:/proc# grep -i symbios /proc/pci
    SCSI storage controller: LSI Logic / Symbios Logic 53c895 (rev 1).
dcr1:/proc# uname -a
Linux dcr1 2.4.27-3-686 #1 Tue Dec 5 21:03:54 UTC 2006 i686 GNU/Linux
dcr1:/proc# mt status
mt: /dev/tape: No such device
dcr1:/proc# ls -l /dev/tape
lrwxrwxrwx 1 root root 8 2007-02-07 16:01 /dev/tape -> /dev/st0
dcr1:/proc#

That mt status command will show the actual st0 status when things are working correctly. The No such device message is usually the second clue that we need to reboot - the first clue is usually that the backups didn't run.

A: On Linux 2.4 you can force a scsi bus rescan by sending 'echo 1' to one of the /proc entries.  I always looked it up in the SCSI_HOWTO document.  I can look it up if needed.
It sounds like the drive is going offline.  Have you tried the scsitur (test unit ready)
or the scsinq command ?

A: Have you tried removing and re-adding the 'st' (scsi tape) module? Might prevent the need for a reboot at least...

lsmod | grep st
sudo rmmod st
sudo modprobe st

A: Maybe you need to delete the scsi device and then force a rescan.  This IBM article has some ways of doing this.

A: When your drive is detected correctly, run the command :
# cat /proc/scsi/scsi

and note down the result.
it should look like :
Host: scsi9 Channel: 00 Id: 01 Lun: 00
  Vendor: IBM      Model: ULT3580-TD4      Rev: 5500
  Type:   Sequential-Access                ANSI  SCSI revision: 05

on 2.4 kernels :
# echo "scsi add-single-device H C I L" > /proc/scsi/scsi

where H C I L are the SCSI address whenever the drive is detected correctly

on 2.6 kernels :
# echo "- - -" >  /sys/class/scsi_host/hostH/scan

where H is the number of the SCSI controler.


text:
Q: Branching shared projects in TFS We have a SQL database that is accessed by several different software products (all with their own Visual Studio solutions).
I'm wanting to create a database project so we can have version control of the database objects.
What I want to know (if it's possible at all) is how do I share the database project across all of the solutions and allow branching per solution?
I've made a couple of test solutions/projects, and I'm able to link the shared database project to another solution by going File->Add->Existing Project, however, when I create a branch of that solution, it doesn't seem to create a branch of the database project and the new branched solution has an invalid reference to the database project.
Is there a way to do this? (if so, how?)

A: In this circumstance I would put all three into the same solution. That would allow me to version and build together.
Branching in this curcomstance is a bad idea as you will just end up with multiple products to support. This is especially common for shared SQL projects.
If you have time to refactor then you could put a service interface in top of the database to allow you to version. If you build a single solution with Restfull API's and your Database you could much more easily both use that api while maintaining data integrity. Its real hard to move the database forward for one application without affecting the other without a service interface that you can version.


text:
Q: How to proof if an object is an imageview? I want to remove all imageviews on a relative layout in Android Studio, save them and replace them later.
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
ArrayList al = rl.getTouchables();
rl.removeAllViews();
//do something
for(int i=0; i<al.size(); i++)
{
 if(al.get(i).equals(new ImageView(this)))
 rl.addView((ImageView) al.get(i));
}

The programm is not working :(

A: Find all the image views in the viewgroup using instanceof. Once you have them all, remove the images from the viewgroup. Then you can do whatever work you need to do on these images:
final ViewGroup vg = (ViewGroup) findViewById(R.id.relativeLayout);
final List<ImageView> images = new ArrayList<>();
for(int i = 0; i < vg.getChildCount(); i++) {
    final View v = vg.getChildAt(i);
    if (v instanceof ImageView) {
        images.add((ImageView) v);
    }
}
for (final ImageView v : images) {
    vg.removeView(v);
}

When java 8 rolls around I imagine we'd be able to do something like this:
final ViewGroup vg = (ViewGroup) findViewById(R.id.relativeLayout);
final List<ImageView> images = IntStream()
    .range(0, vg.getChildCount())
    .mapToObj(vg::getChildAt)
    .filter(ImageView.class::isInstance)
    .map(ImageView.class::cast)
    .collect(Collectors.toList());
images.stream().forEach(vg::removeView);


text:
Q: ShowSearch function rebuilds the whole widget tree on Flutter I have a problem when i navigate to multiple pages and then show search.
More specifically, i have a product page with some details. At the bottom there is a list of similar products.
The flow is:

*

*open many similar products (so I navigate to the same screen using Navigator pushNamed).

*then, navigate from the las product page to the search page

*tap on search bar, open search delegate using the showSearch function

My issue is that when i tap on the search bar, then the whole widget tree is rebuilded and my app is very heavy because rebuilds the previous product pages and everything else.

A: This happens due to the general rebuild on keyboard changes(i.e: showing and hiding Keyboard).
I recommend to have a heavy operation like loading data from backend should be held on initState in State with StatefullWidget.

A: Try to debug and understand why do you rebuild the tree. It seems to me, that you need to simplify a navigation flow.


text:
Q: Does a cellphone ping cell towers even in "aeroplane" mode? In the movies and TV shows they show that the only way for a cellphone to not be traced is to take the battery out (and optionally break it in two :-).
But if this is true, then that means that even in aeroplane mode one's cellphone is pinging the cell towers -- how else could a cellphone be traceable?
Corollary: is a cellphone traceable by just the SIM or the SIM and the IMEI number of the phone?

A: In flight mode -- at least in every mobile phone I've come across that has that feature -- all the radios are disabled[1], so the device is inhibited from transmitting any signal.  If you power up an iOS device while already in flight mode, it doesn't even initialise the SIM card until you switch off the mode (if your SIM card has a PIN code set, it won't prompt for the code if powered on in flight mode).  So while in flight mode, a mobile phone cannot communicate with any other device, and that includes base stations.
To answer the second part of your question: the phone is traceable by its IMEI, which (in theory at least[2]) is unique.  Of course that doesn't mean you know who owns the phone.  The SIM card number is also unique, and is a better target for tracing a user as it will be tied to an account with the provider[3].
[1]  On some devices, you can enable flight mode and then selectively switch on some radios.  On iOS, for example, one can use Wi-Fi and Bluetooth in flight mode if these are manually selected 'on'.
[2]  In practice they are almost unique.  I have seen devices leave a factory with duplicate IMEI numbers by mistake.  It's also possible with some hardware to re-program the IMEI number.
[3]  In some jurisdictions (e.g. the UK), it is possible to buy a SIM card from a shop and use it without the provider knowing your identity.

A: Spy movies and TV shoes make a great deal up.
They are in no way a credible way of telling what is really possible.
As "Airplane Mode" is a way to follow the FCC's ban on "inflight use of cell phones because of potential interference with ground networks"1, someone would have to tinker with a phone's software to disable correct "Airplane Mode".
But seriously, before you consider movies legitimate sources spook info, consider how many movies have x-ray satilites, and can somehow rotate the view a satellite to on a horizontal plain.


text:
Q: How to Align a trailing string to the bottom right corner of a TextView In the picture bellow i want the Footnote string to always appear floating to the right edge of the Textview:

I tried the following but it doesn't work:
SpannableStringBuilder builder = new SpannableStringBuilder();
SpannableString item = new SpannableString ("Main text");
builder.append (item);
builder.append ("  ");
String footnote = "Footnote";
int len = footnote.length();
SpannableString subitem = new SpannableString (footnote);
subitem.setSpan (new ForegroundColorSpan (color), 0, len, 0);
subitem.setSpan (new AbsoluteSizeSpan (12, true), 0, len, 0);
subitem.setSpan (new AlignmentSpan.Standard (Layout.Alignment.ALIGN_OPPOSITE), 0, len, 0);
builder.append (subitem);

myTextView.setText (builder, TextView.BufferType.SPANNABLE);

A: It can be achieved by using 2 textviews in frame layout and set the value of layout_gravity as right and bottom of 2nd second textview.

android:layout_gravity="bottom|right"

Example:
<FrameLayout
        android:id="@+id/flString"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text "
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@android:color/black" />

        <TextView
            android:id="@+id/tvHighlighted"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:text="Footnote"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#0000ff" />
</FrameLayout>

In case of single line, second highlighted word overlaps the text. It can be handled programatically:
/**
 * Used to create 2 text view text in single line like :
 *
 * Text Text Text Text Text Text Text Text Text Text    |Footnote|
 *
 * @param frameLayout         FrameLayout
 * @param tvTitle             TextView
 * @param tvHighlighted       TextView
 *       Directly "View" can be used as param type, but for this case only I
 *         have used dedicated Views and ViewGroup.
 */
public static void manageTextViews(final FrameLayout frameLayout, final TextView tvTitle, final TextView tvHighlighted) {
    tvTitle.post(new Runnable() {
        @Override
        public void run() {
            try {
                int lineCount = tvTitle.getLineCount();
                Rect bounds = new Rect();
                tvTitle.getLineBounds(lineCount > 0 ? lineCount - 1 : 0, bounds);
                FrameLayout.LayoutParams fllp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                fllp.gravity = (Gravity.BOTTOM | Gravity.RIGHT);
                if (frameLayout.getWidth() <= (bounds.width() + tvBuyable.getWidth() + 10)) {
                    fllp.setMargins(0, tvTitle.getLineHeight() + 5, 0, 0);
                } else {
                    fllp.setMargins(0, 0, 0, 0);
                }
                tvHighlighted.setLayoutParams(fllp);
            } catch (Exception e) {
               Log.e(ClassName + ".manageTextViews()", "mTxtTitle.post", e);
            }
        }
    });
}


text:
Q: Energy propagation through stationary points of a standing wave I take two identical lasers, point them at each other from a large distance in space, and fire a pulse from each. The pulse is $N$ wavelengths long. The pulses intersect at the mid point and, for a while, a standing wave is formed by their superposition, and in that standing wave are a series of stationary points at which the E and H fields are 0. There will be $N$ such points, some longer lived than others.
However, both pulses are carrying energy, in the E and H fields, and that energy arrives at the final destination, so energy is being transferred, in the form of E and H fields, through points that never have an E or H field.
I can do maths, but I'm looking for some sort of physical explanation of what is actually happening to allow this. Can anyone point me in the right direction?
I've found a related question which doesn't have answers I can accept (or, for that matter, an accepted answer)
How do traveling waves pass through a standing wave node, if the node doesn't move?
and this one which has the right title but isn't the question I'm asking
How does the energy in a standing wave travel beyond a node?
This last one doesn't answer the question - the accepted answer instead explains how an additional wave can travel through a pre existing standing wave - I want to know how the two waves forming the standing wave are propagating energy through the nodes.

A:
The pulses intersect at the mid point and, for a while, a standing wave is formed by their superposition, and in that standing wave are a series of stationary points at which the E and H fields are 0.

Unfortunately, your assumption about how this works is incorrect. It is best to work through the math on problems like this. For clarity I will use natural units ($c=\mu_0=\epsilon_0=1$) and a frequency such that $\omega=k=1$. Let $$\vec E_1 = (0,A,0) \cos(x-t)$$ $$\vec B_1=(0,0,A) \cos(x-t)$$ and let $$\vec E_2=(0,A,0) \cos(-x-t)$$ $$\vec B_2 = (0,0,-A) \cos(-x-t)$$ and let $$\vec E_3 = \vec E_1 + \vec E_2$$ $$\vec B_3 = \vec B_1 + \vec B_2$$
So the first fields represent a plane wave traveling in the $+x$ direction, the second fields represent a plane wave traveling in the $-x$ direction, and the third fields represent the standing wave formed by their sum. I leave it as an exercise to show that all three pairs of fields satisfy Maxwell's equations.
Note that by simplifying we obtain $$\vec E_3 = (0,2A,0) \cos(t) \cos(x)$$ $$\vec B_3 = (0,0,2A)\sin(t) \sin(x)$$ So although it is correct that $\vec E_3$ has a series of stationary points at which it is always 0 (nodes) and it is also correct that $\vec B_3$ has a series of nodes, the nodes for $\vec E_3$ are different from the nodes for $\vec B_3$. There are no points that are always zero for both fields and there are also no times when both fields are zero everywhere.
To understand the flow of energy in this field configuration we can calculate the energy density and the Poynting vector. $$\vec S_3 = \vec E_3 \times \vec B_3 = (A^2,0,0) \sin(2t) \sin(2x)$$ $$u_3=\frac{1}{2}(E_3^2+B_3^2)=A^2\left(\cos^2(t-x)+\cos^2(t+x)\right)$$

However, both pulses are carrying energy, in the E and H fields, and that energy arrives at the final destination, so energy is being transferred, in the form of E and H fields, through points that never have an E or H field.

This is partly correct and partly incorrect. There are points that are nodes for the E field and different points that are nodes of the B field. There are no points are nodes for both the E and B field.
However, there are indeed nodes for the Poynting vector $\vec S_3$. The nodes of $\vec S_3$ include all of the nodes of $\vec E_3$ and of $\vec B_3$. Any point where $\vec S = \vec 0$ means that electromagnetic energy is not flowing through that point. So electromagnetic energy never flows through the nodes of $\vec S_3$ at any time. Instead, by looking at $u_3$ and $\vec S_3$ we see that EM energy merely oscillates back and forth between the nodes. There is no transfer of energy through the nodes of $\vec S_3$.
Just because energy arrives at the final destination does not imply that energy goes through any of the nodes of $\vec S_3$. Energy doesn't get some cosmic ID tag, so there is no sense in which you can say that the energy leaving one laser must be the same energy as the energy arriving at the other laser and therefore no justification for the assumption that energy must flow through the nodes. Energy is conserved, and energy conservation does not require it to flow through the nodes.


text:
Q: Sum of squared symmetric matrices is the identity matrix Let $A_1, A_2,\ldots,A_n$ be $m\times m$ real symmetric matrices such that
\begin{equation}
A_1^2 + A_2^2 + \dots + A_n^2 = \alpha I_m.
\end{equation}
Can we prove that $A_i^2 = \alpha_i B_i$, where $B_i$ is a diagonal matrix with only zeros and ones on the diagonal?
This conclusion is based on a lot of examples I found while studying homogeneous polynomial maps between spheres.


text:
Q: spring mvc rest protocol buffers http 406 not acceptable error I am using Spring MVC 4.1.5 with its REST support trying to get a web service working with google protocol buffers message format. I have seen a lot of posts that are mentioning this issue with JSON format but none with google protocol buffers format.
Also I don't see Spring framework docs have a MediaType for protobufs (more on that below)   My code is posted here on github
Here's my controller code (using or not using produces="application-xprotobuf" makes no difference - same 406 not acceptable error)
@RestController
@RequestMapping("/ws")
@EnableWebMvc
public class CustomerRestController {
    @Autowired
    private CustomerRepository customerRepository;
    //@RequestMapping(value="/customers/{id}", method = RequestMethod.GET, produces="application/x-protobuf")
    @RequestMapping(value="/customers/{id}", method = RequestMethod.GET)
    public CustomerProtos.Customer customer(@PathVariable Integer id) {
        return this.customerRepository.findById(id);
    }

    @Bean
    ProtobufHttpMessageConverter protobufHttpMessageConverter() {
        return new ProtobufHttpMessageConverter();
    }

    private CustomerProtos.Customer customer(int id, String f, String l, Collection<String> emails) {
        String emailAddressString = "defaultEmail@address.com";
        for (String email : emails) {
            emailAddressString = email;
            break;
        }

        EmailAddress emailAddress = CustomerProtos.Customer.EmailAddress.newBuilder()
                .setType(CustomerProtos.Customer.EmailType.PROFESSIONAL).setEmail(emailAddressString).build();

        return CustomerProtos.Customer.newBuilder().setFirstName(f).setLastName(l).setId(id).addEmail(emailAddress)
                // .addAllEmail(emailAddresses)
                .build();
    }

    @Bean
    CustomerRepository customerRepository() {
        return new CustomerRepositoryImpl();
    }
}

here's my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>demo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

<servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/rest-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

Here's my pom.xml, please note that i do have google protobuf libaries added here and they do end up in WEB-INF/lib folder of the deployed .war file.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.test</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <start-class>demo.DemoApplication</start-class>
        <java.version>1.8</java.version>
        <jackson.version>2.5.3</jackson.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.protobuf-java-format</groupId>
            <artifactId>protobuf-java-format</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-legacy</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Here's my test client
package demo;

import java.util.Arrays;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class DemoApplicationTests {

    @Configuration
    public static class RestClientConfiguration {

        @Bean
        RestTemplate restTemplate(ProtobufHttpMessageConverter hmc) {
            return new RestTemplate(Arrays.asList(hmc));
        }

        @Bean
        ProtobufHttpMessageConverter protobufHttpMessageConverter() {
            return new ProtobufHttpMessageConverter();
        }
    }

    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void contextLoaded() {

        ResponseEntity<CustomerProtos.Customer> customer = restTemplate.getForEntity(
                "http://localhost:7001/demo-0.0.1-SNAPSHOT/ws/customers/2", CustomerProtos.Customer.class);

        System.out.println("customer retrieved: " + customer.toString());

    }

}

When I run the client from command line using mvn test
I get the following error
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.697 sec <<< FAILURE! - in demo.DemoApplicationTests
contextLoaded(demo.DemoApplicationTests)  Time elapsed: 0.037 sec  <<< ERROR!
org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable
        at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
        at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
        at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
        at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
        at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:289)
        at demo.DemoApplicationTests.contextLoaded(DemoApplicationTests.java:42)

I saw people suggesting using a contentNegotiationManager
In my rest-servlet.xml I have mvc:annotation-driven tag
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <context:component-scan base-package="demo" />
    <mvc:annotation-driven />
  </beans>

Also I have dropped in a webConfig.java in demo package
package demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

  /**
    *  Total customization - see below for explanation.
    */
  @Override
  public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    configurer.favorPathExtension(false).
            favorParameter(true).
            parameterName("mediaType").
            ignoreAcceptHeader(true).
            useJaf(false).
            defaultContentType(MediaType.TEXT_PLAIN).
            mediaType("xml", MediaType.APPLICATION_XML).
            mediaType("json", MediaType.APPLICATION_JSON).
            mediaType("x-protobuf", MediaType.ALL)
            ;
  }
}

I get the 406 not acceptable error with and without the webconfig.java (which is doing the work of contentNegotationManager).
I haven't been able to find a MediaType.APPLICATION_XPROTOBUF in Spring 4.1.3 or even 4.2.3 jars .
So I have left that value to MediaType.ALL ( I think that should work ?)
When I run the test client I get this message before actually running the test..
09:27:26.198 [main] DEBUG o.s.web.client.RestTemplate - Created GET request for "http://localhost:7001/demo-0.0.1-SNAPSHOT/ws/customers/2"
09:27:26.199 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [application/x-protobuf, text/plain, application/xml, application/json]
09:27:26.245 [main] DEBUG o.s.web.client.RestTemplate - GET request for "http://localhost:7001/demo-0.0.1-SNAPSHOT/ws/customers/2" resulted in 406 (Not Acceptable); invoking error
handler

It clearly shows its setting the accept headers to include "application-xprotobuf" value as well.
Not sure what I am missing in this case.

A: I had the same issue with the controller failing with 406: Not Acceptable. After a lot of tracing I figured out the statement in the example:

Spring Boot automatically registers HttpMessageConverter beans so we need only define the ProtobufHttpMessageConverter bean and it gets configured appropriately.

is to be understood literally, since without Spring Boot no converter registration happens. The bean is instantiated, but it's never registered in the list of HttpMessageConverters.
I've solved it by explicitly registering a ProtobufHttpMessageConverter instance:
@Configuration
@EnableWebMvc
@ComponentScan
public class AppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new ProtobufHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}

You don't need to declare a separate bean for it (unless you plan to call it explicitly).
Also note that overriding configureMessageConverters() disables all standard converters; if you mean to extend the list of stock converters rather than replace it, override extendMessageConverters() instead.


text:
Q: Where's the at::empty() source code of PyTorch? > Tensor empty(
>     IntArrayRef size,
>     c10::optional<DimnameList> names,
>     c10::optional<ScalarType> dtype,
>     c10::optional<Layout> layout,
>     c10::optional<Device> device,
>     c10::optional<bool> pin_memory,
>     optional<MemoryFormat> optional_memory_format) {   // See [Note: hacky wrapper removal for TensorOptions]   TensorOptions options =
> TensorOptions().dtype(dtype).layout(layout).device(device).pinned_memory(pin_memory);
>
>   if (!names.has_value()) {
>     return at::empty(size, options, optional_memory_format);   }   TORCH_CHECK(options.layout() == Layout::Strided,
>       "NYI: named tensors only support strided layout");   TORCH_CHECK(options.device().is_cpu() || options.device().is_cuda(),
>       "NYI: named tensors only support CPU and CUDA tensors");   auto result = at::empty(size, options, optional_memory_format);
> internal_set_names_inplace(result, names);   return result; }

I just found this in PyTorch source code but there is nothing about at::empty(size, options, optional_memory_format).
So where is the source code of at::empty(size, options, optional_memory_format)?


text:
Q: Bootstrap text align top center Is it possible to align text top and center (for example) using bootstrap.
I have tried using:

It does not seem to work.

A: I believe you probably wanted to have this instead:

(adding quotes around the CSS class names)
This would assume, however, that you have defined both, text-align-top and text-align-center classes in CSS, as no such classes exist in Twitter-Bootstrap.
If you want to do this the Twitter-Bootstrap-way, you can simply use the Alignment classes, which will take care of horizontal alignments. In your case you'd use text-center.
There are no vertical alignment classes in twitter-bootstrap, so you're going to have to set it up yourself using vertical-align: middle; on your targeted element, or create your custom CSS class having that, ie...
CSS:
.vertical-align-top {
    vertical-align: top
}

HTML (with twitter-bootstrap):

A: add this style="vertical-align: top; text-align: center;"
to your tag attribiutes


text:
Q: Align to center child DIVs inside parent DIV I'm trying to align a DIV in the middle of the page when the size is less than 768px
I have one parent DIV that contains three different DIVs. So I used media queries and within one display size I added this "clear:both" to the display_type and buttons classes. So in that way each div will be in its own row.

        Sorter efter:

Then I tried several ways to align them in the center but they didn't work. Here what the CSS looks like:
.container {
    width: 1180px;
    margin: 0 auto;
    padding: 0;
}
.category_header {
    margin-top: 30px;
    margin-bottom: 30px;
    padding: 0 0 0 25px;
}
.products {
    float: left;
    width: 350px;
    margin: 3.5px 0 0;
}
.products label {
    margin: 0 30px 0 0;
    line-height: 40px;
    height: 40px;
    display: block;
}
.display_type {
    float: left;
    width: 350px;
    color: #A1ABB6;
    margin: 12px 0 0;
}
.category_header .buttons {
    float: right;
    width: 427px;
}

I tried to add the following to the parent div "category_header" with no luck. I also tried the same to the child divs. I found a lot of solutions on google but noone seems to work. (display: inline-block; text-align: center etc etc)
@media screen and (max-width: Number px) and (min-width: Number px)
{
    .category_header {
        margin: 0 auto;
        width: 50%;
    }
}

Can anyone help me with this? Thanks

A: try this:
@media screen and (max-width: 768px)
{
    .display_type, .buttons, .products
    {
        float:none;
        margin:auto;
    }
}


text:
Q: Tic Tac Toe with PHP i'm getting so stuck with my homework. .
how to make tic-tac-toe with php_self?
So, i have 9 button with the number range from 1 to 9. then, when first button is clicked the value will be changed with 'O'. after the player with 'O' symbol had pushed the button, then turn to 'X' symbol appeared if user click the button. the process will be continued until the same symbols appear on horizontal, vertical, or diagonal series.
I hope somebody could help me :(
Thanks

A: Am not sure if you need to re-event the wheel .. what you need to do is to change the interface ...
There are so many solutions online that can help you with this
PHP & HTML & Javascript
http://code.activestate.com/recipes/276962-php-tic-tac-toe/
http://t-dev.iglu.cz/
http://scripts.franciscocharrua.com/javascript/tic-tac-toe/
http://www.mystcommunity.com/board/index.php?/topic/11367-tic-tac-toe-in-php/
PHP & HTML
http://refactormycode.com/codes/1524-simple-tic-tac-toe-php-pure-html
http://jadendreamer.wordpress.com/2012/01/31/php-tutorial-2-player-tic-tac-toe-game-no-database-required/
Conclusion
If you select any of the script that you are interested in then you can comeback if you are having any difficulty in making it work

A: Well in the process of answering this question I pretty much did your homework for you. But you should pretend that I have not and I am going to forget about that as well and just focus on what you have asked.
Also, PHP_SELF by itself means nothing. $_SERVER['PHP_SELF'] which is what you are most likely referring to pretty much points to the page itself that you are writing code in. You make it seem as if there is something that is going to help you to make tic-tac-toe but I do not think so. Maybe you can correct me if I am wrong.
You seem to mention that you already have an interface that you are working with. I do not have the code for this interface so I am going to assume that it looks something like this:
http://jsfiddle.net/vyyXP/1/
the form html tag usually contains another attribute called action. You usually use this if you want the data from the form to go to some other page. Since we don't want to create another page we can either omit this altogether or use something like:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"></form>

This is the only place your PHP_SELF comes in. Again, if you know something else about it, let me know.
So.. now lets actually start solving this problem of yours now.
Step 1: Figure out how to get and use the button clicks.
Every time you click a button. The form submits and the page reloaded. If you have knowledge about headers, it'll add an extra pressed=1 or pressed=2, etc every time you click a button and submit the form. This 'pressed' keyword comes from the fact that our buttons have name="pressed" as an attribute. (Notice that all buttons have the same name!).
We will need to use this data and figure out what the person actually clicked.
Since I'm using <form method="post"> you can get this data by using <?php $pressed = $_POST['pressed'] ?> alternatively if you used method="get" you would have had to use $_GET['pressed'] instead.
As an exercise just display an 'X' on whichever button the user clicks on. You should dynamically generate the html code for the buttons inside the form to make your life easier.
<?php
    for ($i=0; $i<9; $i++) {
    echo '<button name="pressed" value="'.$i.'">';
        if ($_POST['pressed']==$i)
            echo 'X';
        echo '</button>';
    if ($i!=0 && ($i+1)%3==0)
        echo "</br>\n";
    }
?>

Step 2: Figure out how to remember data.
Since you're using php. I'd recommend that you use php sessions. You basically just need to put session_start() in the beginning of the file and then you can store values into the $_SESSION variable and php will remember then next time you visited the page.  You can use this to count how many times a button has been pressed so that you can alternate between O's and X's.
Figure out how to destroy sessions. (Make that reset button work). This is pretty important.
You can also use cookies or write to a file if you want but sessions are probably easiest thing to use.
Here is an example of a simple counter.
<?php
  session_start();
  $count = 0;
  if (isset($_SESSION['count']))
    $count = $_SESSION['count'];
  echo $count;
  $_SESSION['count'] = $count+1;
?>

And.. you're done!
This is probably everything important that you need to do. The rest is just implementing how the game tic-tac-toe works. Let me know if you need any clarifications on anything I have written or if you need more information. Hope this helps!


text:
Q: MVC 3 Authentication / Authorization: Roles missing We use MVC 3. The default user management is not usable for us as our account info is stored in our own data-store and access goes via our own repository classes.
I'm trying to assign a principal add roles to the HttpContext.User and give out an authorization cookie.
Based on a code snipped I found I tried something like this:
if (UserIsOk(name, password))
{
    HttpContext.User =
        new GenericPrincipal(
            new GenericIdentity(name, "Forms"),
            new string[] { "Admin" }
        );
    FormsAuthentication.SetAuthCookie(name, false);

    return Redirect(returnUrl);
}

When the next request is done, the user is authenticated, but he is not in the "Admin" role.
What am I missing?

A: I think you should implement FormsAuthenticationTicket.
More info here : http://msdn.microsoft.com/en-us/library/aa289844(v=vs.71).aspx
In Mvc it is quite similar.
I have a class called UserSession that is injected into LoginController and that I use in LogOn action :
    [HttpPost, ValidateAntiForgeryToken]
public ActionResult Index(LoginInput loginInput, string returnUrl)
{
    if (ModelState.IsValid)
    {
        return (ActionResult)_userSession.LogIn(userToLog, loginInput.RememberMe, CheckForLocalUrl(returnUrl), "~/Home");
    }
}

Here's my UserSession LogIn implementation (notice I put the "Admin" role hard coded for the example, but you could pass it as argument) :
public object LogIn(User user, bool isPersistent, string returnUrl, string redirectDefault)
    {
        var authTicket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddYears(1), isPersistent, "Admin", FormsAuthentication.FormsCookiePath);
        string hash = FormsAuthentication.Encrypt(authTicket);

        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

        if (authTicket.IsPersistent) authCookie.Expires = authTicket.Expiration;

        HttpContext.Current.Response.Cookies.Add(authCookie);

        if (!String.IsNullOrEmpty(returnUrl))
            return new RedirectResult(HttpContext.Current.Server.UrlDecode(returnUrl));

        return new RedirectResult(redirectDefault);
    }

Then in the base controller I've overriden OnAuthorization method to get the cookie :
if (filterContext.HttpContext.Current.User != null)
{
   if (filterContext.HttpContext.Current.User.Identity.IsAuthenticated)
   {
      if( filterContext.HttpContext.Current.User.Identity is FormsIdentity )
      {
         FormsIdentity id = filterContext.HttpContext.Current.User.Identity as FormsIdentity;
         FormsAuthenticationTicket ticket = id.Ticket;
         string roles = ticket.UserData;

         filterContext.HttpContext.Current.User = new GenericPrincipal(id, roles);
      }
   }
}

I hope this helps. Let me know.

A: You sure, that roles are enabled, and there is such role?
If not, do following:
In Visual Studio:
Project -> ASP.NET Configuration
Then choose Security, enable roles. Create role "Admin".
Then try your approach


text:
Q: Diferenças entre readonly Func<> e método normal Esquecendo um pouco questões como legibilidade, qual seria as diferenças entre as seguintes chamadas?
Usando readonly Func<T1, T2, TResult> = (T1, T2) => { return default(TResult); }
private readonly Func<int, int, int> Soma = new Func<Func<int, int, int>>(() => {
    var total = default(int);
    return (numA, numB) => {
        total += numA + numB;
        return total;
    };
})();

Usando Method(T1, T2) { return default(TResult); }
private int total = 0;
private int Soma()
{
    total += numA + numB;
    return total;
}

A: Basicamente o primeiro é um método anônimo definido por um delegado (guia de uso). No caso o delegado é pré definido com a assinatura usada. Então o seu "conteúdo" pode ser "armazenado" em uma variável, como foi feito.
O readonly foi usado para não permitir que o seu conteúdo possa ser trocado. Uma das grandes vantagens do uso de delegados (no caso usando uma sintaxe de lambda) é poder trocar o conteúdo (o que deve ser executado) e dar flexibilidade para a aplicação. Neste caso específico onde isto não é possível, não vejo tanta vantagem, claro que depende do contexto onde for usado, tem situações que pode ser interessante, inclusive evitar alguns padrões de projeto como o Strategy, por exemplo.
O return é desnecessário ali no cabeçalho, poderia ter escrito assim:
(numA, numB) => total += numA + numB;

Coloquei no GitHub para referência futura.
O segundo é um método normal tratado pela linguagem. Tem um suporte melhor pelo compilador podendo ser usado em mais situações.
O primeiro tem algumas limitações de uso de genéricos que o segundo não tem. O segundo, de forma geral, será chamado pelo Soma() e terá que estar disponível no contexto. O primeiro será chamado pelo nome da variável que estiver segurando uma referência para este corpo de código. E isto pode ser passado para outros contextos. Até é possível jogar o método normal em uma variável que espere um método com a mesma assinatura, mas é menos comum.
Em termos de resultado não muda nada. A performance do primeiro é ligeiramente inferior porque há uma indireção e tem uma infra de closure. Também consome um pouco mais de memória.
Um delegado é uma tipo que possui um ponteiro para o código a ser executado e para as variáveis que ela enclausura (no caso a total, mas no outro exemplo tem esse custo também). É um dado, é um objeto, e todo objeto ocupa memória. A chamada do método tem que consultar este endereço armazenado antes, causando a indireção e um custo de processamento extra. Além disso, por ser uma indireção é mais complicado, se não impossível fazer certas otimizações. O método direto é todo resolvido pelo compilador e não tem overhead. Veja um teste.
As variáveis locais de um método normal são colocadas na stack. No método delegado elas ficam no heap (dentro desse objeto criado para suportar o delegado/closure) já que precisam estar disponíveis em outros contextos.
O primeiro tem dificuldade maior para escolha de overload no caso de ter métodos com assinaturas diferentes/default arguments. A decisão é melhor em métodos normais.
Posso estar enganado, mas vejo pouca necessidade da sintaxe ser complexa assim. Acho que o código poderia ser simplificado. Me parece que o primeiro está tentando simular uma classe também. Também não precisa do return no segundo caso.


text:
Q: Nested facets in ggplot2 spanning groups I encountered a situation in which I want to create a plot that was facetted by three grouping variables. To do so, I would simply use facet_grid(f1 ~ f2 + f3), but the issue here is that the labels for f2 would be redundant, and it would be much better to have them span the facets for f3 nested within f2.
MWE:
library('tibble')
library('ggplot2')
df <- tribble(
  ~x, ~y, ~f1, ~f2, ~f3,
  0.5, 0.5, "a", "a", "a",
  0.5, 0.5, "b", "a", "a",
  0.5, 0.5, "a", "b", "a",
  0.5, 0.5, "b", "b", "a",
  0.5, 0.5, "a", "a", "b",
  0.5, 0.5, "b", "a", "b",
  0.5, 0.5, "a", "b", "b",
  0.5, 0.5, "b", "b", "b"
)

p <- ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  facet_grid(f1 ~ f2 + f3)

Again, I'm looking to combine the labels for f2 so that they are not so redundant.
Edit: This is different from other questions in that it asks how to use the existing groupings to modify a facet as opposed to adding a new one.

A: I'm sorry necroing this thread and unintended self-promotion, but I had a go at generalizing this to a facet_nested() function and it can be found in the ggh4x package.
The function isn't tested extensively but I thought it might be of some convenience to people. Maybe some good  feedback will come from this.
There are two other modifications that I made in this function beyond the scope of grouping strips. One is that it doesn't automatically expand missing variables. This is because I was of the opinion that nested facets should be able to co-exist with non-nested facets without any entries to the 2nd or further arguments in vars() when plotting with two data.frames. The second is that it orders the strips from outer to inner, so that inner is nearer to the panels than outer, even when switch is set.
Reproducing the plot in this question would then be as follows, assuming df is the df in the question above:
# library(ggh4x)
p <- ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  facet_nested(f1 ~ f2 + f3)

There was also a related question with a more real-world example plot, which would work like the following, assuming df is the df from that question:
p <- ggplot(df, aes("", density)) +
  geom_boxplot(width=0.7, position=position_dodge(0.7)) +
  theme_bw() +
  facet_nested(. ~ species + location +  position) +
  theme(panel.spacing=unit(0,"lines"),
        strip.background=element_rect(color="grey30", fill="grey90"),
        panel.border=element_rect(color="grey90"),
        axis.ticks.x=element_blank()) +
  labs(x="")

A: The answer to this lies within the grid and gtable packages. Everything in the plot is laid out in a particular order and you can find where everything is if you dig a little.
library('gtable')
library('grid')
library('magrittr') # for the %>% that I love so well

# First get the grob
z <- ggplotGrob(p)

The ultimate goal of this operation is to overlay the top facet label, but the trick is that both of these facets exist on the same row in the grid space. They are a table within a table (look at the rows with the name "strip", also take note of the zeroGrob; these will be useful later):
z
## TableGrob (13 x 14) "layout": 34 grobs
##     z         cells       name                                   grob
## 1   0 ( 1-13, 1-14) background        rect[plot.background..rect.522]
## 2   1 ( 7- 7, 4- 4)  panel-1-1               gTree[panel-1.gTree.292]

                                    ...

## 20  3 ( 7- 7,12-12)   axis-r-1                         zeroGrob[NULL]
## 21  3 ( 9- 9,12-12)   axis-r-2                         zeroGrob[NULL]
## 22  2 ( 6- 6, 4- 4)  strip-t-1                          gtable[strip]
## 23  2 ( 6- 6, 6- 6)  strip-t-2                          gtable[strip]
## 24  2 ( 6- 6, 8- 8)  strip-t-3                          gtable[strip]
## 25  2 ( 6- 6,10-10)  strip-t-4                          gtable[strip]
## 26  2 ( 7- 7,11-11)  strip-r-1                          gtable[strip]
## 27  2 ( 9- 9,11-11)  strip-r-2                          gtable[strip]

                                    ...

## 32  8 ( 3- 3, 4-10)   subtitle  zeroGrob[plot.subtitle..zeroGrob.519]
## 33  9 ( 2- 2, 4-10)      title     zeroGrob[plot.title..zeroGrob.518]
## 34 10 (12-12, 4-10)    caption   zeroGrob[plot.caption..zeroGrob.520]

If you zoom in to the first strip, you can see the nested structure:
z$grob[[22]]
## TableGrob (2 x 1) "strip": 2 grobs
##   z     cells  name                                 grob
## 1 1 (1-1,1-1) strip absoluteGrob[strip.absoluteGrob.451]
## 2 2 (2-2,1-1) strip absoluteGrob[strip.absoluteGrob.475]

For each grob, we have an object that lists the order in which it's plotted (z), the position in the grid (cells), a label (name), and a geometry (grob).
Since we can create gtables within gtables, we are going to use this to plot over our original plot. First, we need to find the positions in the plot that need replacing.
# Find the location of the strips in the main plot
locations <- grep("strip-t", z$layout$name)

# Filter out the strips (trim = FALSE is important here for positions relative to the main plot)
strip <- gtable_filter(z, "strip-t", trim = FALSE)

# Gathering our positions for the main plot
top <- strip$layout$t[1]
l   <- strip$layout$l[c(1, 3)]
r   <- strip$layout$r[c(2, 4)]

Once we have the positions, we need to create a replacement table. We can do this with a matrix of lists (yes, it's weird. Just roll with it). This matrix needs to have three columns and two rows in our case because of the two facets and the gap between them. Since we are just going to replace data in the matrix later, we're going to create one with zeroGrobs:
mat   <- matrix(vector("list", length = 6), nrow = 2)
mat[] <- list(zeroGrob())

# The separator for the facets has zero width
res <- gtable_matrix("toprow", mat, unit(c(1, 0, 1), "null"), unit(c(1, 1), "null"))

The mask is created in two steps, covering the first facet group and then the second. In the first part, we are using the location we recorded earlier to grab the appropriate grob from the original plot and add it on top of our replacement matrix res, spanning the entire length. We then add that matrix on top of our plot.
# Adding the first layer
zz <- res %>%
  gtable_add_grob(z$grobs[[locations[1]]]$grobs[[1]], 1, 1, 1, 3) %>%
  gtable_add_grob(z, ., t = top,  l = l[1],  b = top,  r = r[1], name = c("add-strip"))

# Adding the second layer (note the indices)
pp <- gtable_add_grob(res, z$grobs[[locations[3]]]$grobs[[1]], 1, 1, 1, 3) %>%
  gtable_add_grob(zz, ., t = top,  l = l[2],  b = top,  r = r[2], name = c("add-strip"))

# Plotting
grid.newpage()
print(grid.draw(pp))


text:
Q: Have cmake related files in a subdir under the project dir I would like to have all cmake related files, i.e. CMakeKists.txt, CMakeCache.txt, CMakeFiles/, and Makefile; under a subdirectory of the project root directory, for example, build_files/.
How can this be done?

A: To directly answer your question: simply put CMakeLists.txt there, and run CMake from that directory. You will have to refer to all source files etc. using absolute paths or relative paths that start with .., of course, but it will work.
However, note that it is strongly discouraged (and with good reason) to run in-source builds with CMake; that is, generating buildsystems somewhere within the source tree. If not for backwards compatibility, even allowing them would be long deprecated or even forbidden in CMake itself.
It's much better to generate the buildsystem into a directory separate from your entire source tree. Even so, you can keep the CMakeLists.txt in the build_files, if you wish. Assuming your source is located under /path/source, you would then do it like this:
cd /path
mkdir build
cd build
cmake ../source/build_files


text:
Q: Erro em leitura de arquivo em C++ Alguém sabe me dizer porque a saída desse programa está sendo apenas "end"? O arquivo naocompre.txt está no mesmo diretório do programa.
Segue o código:
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main ()
{
string info;
ifstream input("naocompre.txt");
if(input.is_open()) {
    while(!input.eof()) {
           string info;
           getline(input,info);
           cout<<info<<endl;
    }
}
    cout<<"end"<<"\n";
    return 0;

}

Conteúdo de naocompre.txt:
NaoCompre Costeira
5
7
4
Maria_Benta 1 800
Juliana_Digito 1 800
Zeca_Mole 3 180
Joao_DeMora 3 180

A: O programa está correto. O problema é no seu ambiente. Como comentado por @stderr, ou o arquivo não existe, ou está em outro diretório, ou tem outro nome, ou alguma coisa do tipo.
PS. "Na minha máquina funcionou."


text:
Q: Twitter API Error using variables within php DEFINE I'm trying to pass a username and password variable to the twitter credentials but it keeps returning that I'm not authenticated. However, when I use the actual username and password, instead of the variables, it successfully authorizes.
$username = $_POST["username"];
$password = $_POST["password"];

$url = "http://search.twitter.com/search.atom?q=golf&show_user=true&rpp=100";
$search = file_get_contents($url);

$regex_name = '/\<name\>(.+?) \(/';
preg_match_all($regex_name,$search,$user);
for($i=0;$user[1][$i];$i++)
{
$follow = $user[1][$i];
    define('TWITTER_CREDENTIALS', '$username:$password');
    $url = "http://twitter.com/friendships/create/".$follow.".xml";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERPWD, TWITTER_CREDENTIALS);
    $result= curl_exec ($ch);
    curl_close ($ch);

I'm thinking it has something to do with the colon in between the username and password, or perhaps trying to use variables within define function.
Any clues?

A: $username = $_POST["username"];
$password = $_POST["password"];
// INCORRECT. Will literary assign TWITTER_CREDENTIALS as $username:$password
// define('TWITTER_CREDENTIALS', '$username:$password');

// CORRECT, will parse the variables and assign the result to TWITTER_CREDENTIALS
define('TWITTER_CREDENTIALS', "$username:$password");

Remember strings with double quotes (") parse variables in the string, strings with single quotes (') do not.
Read more about strings in PHP:

*

*PHP strings

*Variable parsing in PHP strings

*PHP string functions

A: it has something to do with using single quotes instead of double quotes.

A: You are using define inside a loop, that´s not gonna work because you can only define e constant once.


text:
Q: Overriding methods in Java Let
public class A{
    public MyType myMethod(){...}
}

and
public class B extends A{
    @Override
    public MyType myMethod(){...}
}

be an arbitrary classes. Why MyType must be a parent type of MyAdvancedType necessarily? What happened if we permitted that MyAdvancedType can be an arbitrary type?

A: I suppose you meant MyAdvancedType in the second example
There is a simple explanation You have the following LOC:
A a = new B();

Now, when you try to call myMethod on the object a, in fact, you will call the overriden in the B class method.
Now, the overriden method returns an object of MyAnvancedType, but you called the method on the class A, which means all you know is you can get an object of MyType. So, the JVM casts MyAnvancedType to MyType, and you are gonna work with MyType object, even not suspecting that you are working with MyAdvancedType
And answering your second question. Even if the compiler permit you use an arbitrary type, you would get ClassCastException, as the compiler would try to cast MySomeOtherType to MyType

A: If I understand you:
Why MyType must be a parent type of MyAdvancedType necessarily?
Because you itself write MyAdvancedType as child of MyType (class  B is child of class A from your sample) and java ideology allow only one parent.
What happened if we permitted that MyAdvancedType can be an arbitrary type
Java recognize your MyAdvancedType as next types: Object, MyType and MyAdvancedType.
For example In this case:
class A{
    void someMethod(){
        System.out.println("Class A method");
    }
}
class B extends A{}
...
A var = new B();
var.someMethod();

executed method of class A. But in this case:
class B extends A{
    @Overide //This string is optionally but good practice.
    void someMethod(){
        System.out.println("Class B method");
    }
}
...
A var = new B();
var.someMethod();

executed overridden method of class B. This behavior be called polymorphism.


text:
Q: Datagridview specific rows change background color i try to highlight the selected row become red where column is 'E' in datagridview but if the first row's status is 'E',the following row also become red too although status is 'I'.

SelectionChanged event
int sel = datagridview.SelectedCells[0].RowIndex;
    DataGridViewRow Row = dataGridView.Rows[sel];
    if(!File.Exists(path))
    {
       Row.Cells[4].Value = "E"
       for(int i=0;i<5;i++)
       {
          Row.Cells[i].Style.BackColor = Color.Red;
       }
    }

A: Just use the dataGridView_CurrentCellChanged event can solve this problem.


text:
Q: object ID vs hash vs class object id I got confused between these three types of IDs, why python have 3 different id types? and what is the use of them?
class Person:
def init(self, name):
self.name=name

p1=Person("Allen")
print(p1)
print(id(p1))
print(hash(p1))
output:
<main.Person object at 0x000001AE10CC7FD0>
1847117774800
115444860925


text:
Q: Capturing text elements as variables I am trying to capture the first instance of particular elements from an object. I have an object $doc and would like to get the values of the following.
id, url, alias, description and label i.e. specifically:

*

*variable1 - Q95,

*variable2 - //www.wikidata.org/wiki/Q95,

*variable3 - Google.Inc,

*varialbe4 - American multinational Internet and technology corporation,

*variable5 - Google

I've made some progress getting the $jsonArr string however I'm not sure this is the best way to go, and if so I'm not sure how to progress anyway.
Please advise as to the best way to get these. Please see my code below:
<HTML>
<body>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>

<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$errors = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://www.wikidata.org/w/api.php?
action=wbsearchentities&search=$search&format=json&language=en");
libxml_clear_errors();
libxml_use_internal_errors($errors);

var_dump($doc);
echo "<p>";
$jsonArr = $doc->documentElement->nodeValue;

$jsonArr = (string)$jsonArr;
echo $jsonArr;

}
?>
</body>
</HTML>

A: Since the response to your API request is JSON, not HTML or XML, it's most appropriate to use cURL or Stream library to perform the HTTP request. You can even use something primitive like file_get_contents.
For example, using cURL:
// Make the request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.wikidata.org/w/api.php?action=wbsearchentities&search=google&format=json&language=en");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

// Decode the string into an appropriate PHP type
$contents = json_decode($output);

// Navigate the object
$contents->search[0]->id; // "Q95"
$contents->search[0]->url; // "//www.wikidata.org/wiki/Q95"
$contents->search[0]->aliases[0]; // "Google Inc."

You can use var_dump to inspect the $contents and traverse it like you would any PHP object.


text:
Q: Extracting named colors out of ColorFactory.java class by the lobo project? What type of process would I need in a new class to 'read' all of the colors that are in this class below?  I use the class to set colors on components and love it. But the time has come to allow my application to right-click on a panel and change the background color for example.
What would get me started in the correct direction code-wise in continuing to use these colors: ColorFactory.java
I was just starting to think about adding a new method to the class something like:
public Map<String, Color> getColorMapValues(){

    return colorMap;
    //
}

A: You can access the color map by reflexion.
I don't guarantee the following code since I don't have my IDE at hand, but this should do the trick :
private static Map<String, Color> getColorMap() throws Exception {
    Field colorMapField = ColorFactory.class.getDeclaredField("colorMap");
    colorMapField.setAccessible(true);
    return (Map<String, Color>) colorMapField.get(ColorFactory.getInstance());
}

Then you can just query the returned color map to get the Color by name :
Map<String, Color> colorMap = getColorMap();
Color yellow = colorMap.get("yellow");

If you want to modify the color map, just retrieve it with the method above, put() "any color you like" (yeah, Pink Floyd reference!), then call this method :
public void setColorMap(Map<String, Color> colorMap) throws Exception {
    Field colorMapField = ColorFactory.class.getDeclaredField("colorMap");
    colorMapField.setAccessible(true);
    colorMapField.set(ColorFactory.getInstance(), colorMap);
}

Be warned that this is quite dangerous with respect to the class' synchronization policy, but it should work provided you don't spam it with multiple threads.

A: Since you have control over the source code in this case, it would be better to refactor the class to meet your needs than using reflection (which is not only expensive, but is prohibited depending on your security policy).
The technique commonly used is the Holder pattern. See Joshua Bloch's Effective Java (2nd Edition) Item 71 for more information. We can also avoid synchronization on reads by using a thread-safe, non blocking structure, namely java.util.concurrent.ConcurrentHashMap.
public class ColorFactory {
    private static class ColorFactoryHolder {
        // creates on instantiation of ColorFactoryHolder
        // synchronization is baked into the JVM, but won't be created until
        // the class is used, see JLS 12.4.1
        static final ColorFactory instance = new ColorMap();
    }
    public static ColorFactory getInstance() { return ColorFactoryHolder.instance; }
    // concurrent hash map - all operations are thread safe
    Map<String,Color> colormap = new ConcurrentHashMap<String,Color>();
    private final Object lock = new Object();
    private ColorFactory() {
        colormap.add("blue",new Color(0,0,255));
        // rest of colors here
    }
    public Color getColor(String spec) {
        if(colormap.containsKey(spec)) return colormap.get(spec);
        // don't synchronize externally - Bloch et al, item 70
        synchronized(lock) {
            // double check idiom - not broken, as map is thread safe
            if(colormap.containsKey(spec)) return colormap.get(spec);
            Color color = parse(spec); // parse method can be extracted from old code
            colormap.put(spec,color);
            return color;
        }
    }
    private static Color parse(String spec) {
        // parse the color spec here
    }
}

In fact, because the parse operation is likely to be very, very fast (in comparison to the synchronization), we can do away with the synchronization altogether. So we might end up parsing the value multiple times - not really a big problem, since the result will be the same every time. See Bloch et al. Item 69 for more information.
public class ColorFactory {
    private static class ColorFactoryHolder {
        // same as above, snipped for brevity
    }
    public static ColorFactory getInstance() { return ColorFactoryHolder.instance; }
    // requires ConcurrentMap reference to get putIfAbsent(K,V) method
    ConcurrentMap<String,Color> colormap = new ConcurrentHashMap<String,Color>();
    // private final Object lock = new Object(); - removed
    private ColorFactory() {
        colormap.add("blue",new Color(0,0,255));
        // rest of colors here
    }
    public Color getColor(String spec) {
        Color result = colormap.get(spec);
        if(result == null) {
            result = parse(spec); // may parse multiple times, but still
                                  // cheaper than synchronization
            colormap.putIfAbsent(spec,result);
        }
        return result
    }
    private static Color parse(String spec) {
        // parse the color spec here
    }
}