Cannot change UIView frame size

Question: I have a custom uiview that i am trying to update the frame size. I do it like this in a method once it is clicked.  The method is called, and the frame value changes, however on the screen nothing happens!
if (!touched) {

        GameBox *box = (GameBox *)[self.view viewWithTag:40];

        [box setFrame:CGRectMake(20, 20, 100, 73)];
        NSLog(@"%f", box.frame.origin.x);
        markButton.enabled = NO;
        guessButton.enabled = NO;
        [self.view reloadInputViews];

        NSLog(@"The action bar should now be hidden");
    }
    else if (touched) {
        guessButton.enabled = YES;
        markButton.enabled = YES;
        [self.view reloadInputViews];
        NSLog(@"The action bar should now be visible");
    }

Comment: Please ask what you want to do..so I can understand..
Comment: I want to:  a)  resize the cgrect frame of the uisubview box, and b)  disable/reenable the guess button and mark button
Answer: I guess you have hooked self.view to UIView in Interface Builder.
In order to change UIView frame, in Interface Builder go to File Inspector, and uncheck Use Autolayout, then in the code change the frame.
Hope this helps.
Comment: I can't believe I spent 3 hours debugging...Thank you!
Comment: This works but it affects the ability to use autolayout for the whole document...
Comment: You can simply set translatesAutoresizingMaskIntoConstraints = YES; on the uiView element and still keep your autolayout. This will redraw the element to new frame.
Answer: You need to set adjust the frame in the viewDidAppear (not viewDidLoad).
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];

CGRect frame = self.tableView.frame;
frame.origin.y += 100.0;
frame.size.height -= 100.0;
self.tableView.frame = frame;
}

Apparently this has something to do with table views within navigation controllers.
Answer: It is because of Auto Layout, however you could do it after Auto Layout done its work or change constraints of it. If you want to do it after auto layout add following.
- (void)viewDidAppear:(BOOL)animated {
    dispatch_async(dispatch_get_main_queue(), ^{
        box.frame = CGRectMake(20, 20, 100, 73)];
});

Comment: It helped me, Thanks, but can you tell me reason why you put it inside dispatch block @Deniz
Comment: It seems that I had wanted frame size to be changed after current repaint cycle, some time after viewDidAppear method finished executing. But I am not sure now.
Answer: [self.view reloadInputViews] is generally used for FirstResponders. I Don't have much of an idea about your customview, but I think for just settings the frame you can use:
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelay:1.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

viewFrame.frame=frame;//Frame Defined by you
[UIView commitAnimations];

can give better solution if i get a look at your custom view.

Cannot change UIView frame size


CakePHP WAMP - Database Mysql connection missing

Question: I have scoured the web for an answer but as of now have been unsuccessful. I am attempting to connect CakePHP to a database. But I keep getting the same response:
CakePHP is NOT able to connect to the database.
Database connection "Mysql" is missing, or could not be created.

Here is part of my database.php file
public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => '',
    'database' => 'cake',
    'prefix' => '',
    //'encoding' => 'utf8',
);

^I've also tried different host/login combinations based from the access privileges list in phpmyadmin.
I think one problem might be that Wampserver is finding the wrong php.ini file. It seems that it is loading the file at: "C:\Program Files (x86)\PHP\php.ini" instead of something under "C:\wamp...". How would I set it to point at the right file??
However, I had added the line "extension=php_pdo_mysql.dll" to both files and still no luck.  Any help would be appreciated.
Comment: Is mysql running at localhost?
Comment: Check out this link http://stackoverflow.com/questions/19280245/cakephp-database-connection-mysql-is-missing-or-could-not-be-created. It seems the same issue.
Answer: I had the exact same issue. There was no problem in the mysql database as it was accessible through phpMyadmin and other applications running on the server. The issue was caused due to the mysql port not mentioned alongwith the host. Append the port with the host like... 'host' => 'localhost:3307'.
public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost:3307',
    'login' => 'root',
    'password' => 'mypass',
    'database' => 'cake_todos',
    'prefix' => '',
    //'encoding' => 'utf8',
);

Now, how to know the mysql port? For that you need to go to the server configuration file.. e.g. the in my case it was the properties.ini file in the home directory of the wamp folder. Open the file and you will most probably find an entry like this:
mysql_port=3307
mysql_host=127.0.0.1
So, here it is, the mysql_port. Hope it helps.
Answer: First check there is database called cake in your localhost/phpmyadmin, and if that mysql use the username root and no password and also make sure you set php_mysql on the right php.ini file (extension=php_mysql.dll).
Second, if you think the problem is because of php.ini file location, you can set it:

go to your wamp folder (C:\wamp) and
under that folder you'll find wampmanager.ini file and
Find php.ini word in that file you'll get this kind of line
(Type: item; Caption: "php.ini"; Glyph: 6; Action: run; FileName: "notepad.exe"; parameters: "...path here...")and locate the path and set "C:/wamp/bin/apache/apache2.2.21/bin/php.ini"

please tell me (vote) if it works. I hope it helps.
Thanks


c++ error: request for member 'view' in

Question: I'm working on a bit of code for my C++ class, and I'm stuck.
I'm actually using Polymorphism dynamic binding, I have successfully store the objects into my vector and now I would like to display all the objects that are being stored in the vector ShapeTwoD.
Here's the bit of the assignment I'm working on:
Shape2DLin.cpp
void Shape2DLink::Display()
{
    vector<ShapeTwoD*>::iterator vectorIt = shapeobject.begin();
    while(vectorIt != shapeobject.end())
    {
        *vectorIt->view();
        vectorIt++;
    }
}

SquareImp.cpp
void Square::view() const
{
    cout << "Area is: " << area << endl;
}

ShapeTwoDImp.cpp
void Square::view() const
{
    cout << "Area is: " << area << endl;
}

whenever i compile the application I would get the following error. just wonder why is it so?
D:\School\CSCI204-C++\Assignment\Assign 2\Assign2>g++ -o test Shape2Dmain.cpp Sh
ape2DLink.cpp ShapeTwoDImp.cpp SquareImp.cpp RectangleImp.cpp CrossImp.cpp
Shape2DLink.cpp: In member function 'void Shape2DLink::Display()':
Shape2DLink.cpp:94:14: error: request for member 'view' in '* vectorIt.__gnu_cxx
::__normal_iterator<_Iterator, _Container>::operator-> [with _Iterator = ShapeTw
oD**, _Container = std::vector<ShapeTwoD*>, __gnu_cxx::__normal_iterator<_Iterat
or, _Container>::pointer = ShapeTwoD**]()', which is of non-class type 'ShapeTwo
D*'

Comment: I assume you didn't try `(*vectorIt)->view()`
Answer: Instead of *vectorIt->view() use (*vectorIt)->view().
Because the operator -> has higher precedence than the dereference/indirection operator *.
Comment: thanks alot!! it compiles and work.. but may I know the reason why do i have to bracket the *vectorIt?

c++ error: request for member 'view' in


Software to repliacte data in a Cluster Shared Volume in real time from DAS attached to Server 2k8 R2 HyperV cluster to an identical setup?

Question: Are there any software solutions that will be able to handle replicating the data from one SAS based DAS (a Dell MD3200) attached to two R410 servers running clustered Server 2008 R2 Hyper V instances in a co location data center to another MD3200 attached to another two R410 servers running clustered Server 2008 R2 Hyper V instances that are in our office so that in the event that the data center goes down it is simply a matter of turning on the VMs in our office and the VMs are able to start up as if they were a server that had been turned off without being shutdown?
I have recently seen someone doing something similar with HP's left hand SAN offering and VMWare where they were able to have iSCSI endpoints clustered together and replicating across a WAN link so that if for some reason the data center became unavailable they could simply start up the VMs on ESX servers running in their local office and the only negative affect is that to the VMs it was like being turned off instead of properly shut down which most applications like SQL will handle without too much trouble.
I would like to do something similar but use DAS based storage instead of HP's Left Hand SAN and Hyper V R2 instead of ESX.
This blog entry indicates that Clustered Shared Volumes cannot be replicated but I was curious if there was third party software out there that can handle this.
Edit1:
I am exploring the functionality of Double Take's Availability replication product but based on what I have currently seen it doesn't provide any indication that it can replicate clustered Hyper V instances, just normal ones.
Edit2:
I have spoken with representatives from Double Take and their product does not support replication of Cluster Shared Volumes but I have discovered that Microsoft's Data Protection Manager 2010 does support backing up Cluster Shared Volumes.
Answer: At this point in time there does not appear to be any way to replicate cluster shared volumes used by Hyper V to store clustered VMs. If someone can find one then I will mark theirs as the answer.
EDIT: Bumped into this post and decided it was worth making an edit to the answer. It's 2018 and not 2010 now and there's a bunch of options these days. WS2016+ has built-in feature called Storage Spaces Direct (S2D) which comes with Datacenter edition and it allows replicating CSVs (actually virtual disks being CSVs' back end storage).
https://docs.microsoft.com/en-us/windows-server/storage/storage-spaces/storage-spaces-direct-overview
There's also Storage Replica which is more of a disaster recovery (DR) solution but it can also be put into use when there's a need to deploy CSV replication. This feature required Datacenter edition also (there are rumors stripped down version of SR will be released as part of Standard with WS2019, but nothing is in stone yet).
https://docs.microsoft.com/en-us/windows-server/storage/storage-replica/storage-replica-overview
There are third-party tools like StarWind Virtual SAN (Free) that could be used to replicate CSVs as well. It works with Standard edition of Windows Server and even free Hyper-V Server.
https://www.starwindsoftware.com/starwind-virtual-san-free
There are hardware ways to solve the issue as well. Hope this helps.


Convergence of sequence and sum.

Question: Do the sequence $$\frac{n}{{n!}^{\frac{1}{n}}}$$ and the sum
$$\sum_{n=1}^\infty \frac{n}{{n!}^{\frac{1}{n}}}$$
converge?
And if they do converge then to what real number.
It seems to me that the sequence converges but I have no clue about the sum.
Comment: The first sequence converges to $e \neq 0$, so that the series is divergent.
Comment: Hint: Note that $n! \leq n^n$.
Comment: Use the Stirling formula for the factorial.
Comment: As part of your question, you should include what argument you use to convince yourself that the sequence converges.
Comment: @marmouset : Overhard in this problem.
Comment: actually Stirling is a very bad idea, I was even planning to put an exposant 1/n on it
Comment: @marmouset I tried using Stirling's formula but no use.
Comment: @marmouset: can you elaborate ?
Comment: Proving the convergence of the expression I got by Stirling's formula seemed harder than the original problem.
Answer: We can use the fact that if $a_n>0$ for all $n\ge1$ and the sequence $\frac{a_{n+1}}{a_n}$ converges in $[0,\infty]$, then
$$
\lim_{n\to\infty}a_n^{1/n}=\lim_{n\to\infty}\frac{a_{n+1}}{a_n}
$$
(see this question).
We have that
$$
\lim_{n\to\infty}\biggl(\frac{n^n}{n!}\biggr)^{1/n}=\lim_{n\to\infty}\frac{(n+1)^{n+1}n!}{(n+1)!n^n}=\lim_{n\to\infty}\biggl(1+\frac1{n}\biggr)^n=e.
$$
Hence, the sequence converges but the series diverges.
Answer: Regarding just the sum, since you say you have a handle on the term by itself.
For $n>1$, we have $1 < n, 2 < n, \dots, n-1 < n$ and $n = n$, so $n! < n^n$.  Then $n!^{1/n} < (n^n)^{1/n} = n$.  So, for $n>1$,

 $$  \frac{n}{n!^{1/n}} > \frac{n}{n} = 1  $$

and the sum cannot converge because the terms do not go to zero.
Did you think the limiting value of the term was zero?
Comment: No ,I knew that the terms converged to some real numbers greater than 0, because I calculated the terms for n=1000.
Answer: Taking the logarithm,
$$\log s_n=-\frac1n\sum_{k=1}^n\log\frac kn.$$
In the limit,
$$\log s_\infty=-\int_0^1\log x\,dx=1.$$

Convergence of sequence and sum.


XCode6 storyboard, TableViewController can't see navigation Items

Question: I was migrating some code over form XCode5 to XCode6 and I realized I couldn't figure out how to see my Navigation Items as part of my TableViewController on the storyboard.  As you can see in the following image i have an AddPilot button

My Storyboard however looks like this and there is no visual representation of the Add Pilot of which I can drag off to create segues etc.

Do i have to do something on the display to get it to show?
Answer: In my case complete reinstall of xcode didn't help, so I clicked on "Show the assistant editor" and than preview my storyboard.

It helped in some magical way.


Evaluating an integral with unspecified functions $f,g$, given other integrals with these functions

Question:
Suppose that
  $$\int_6^8(3f(x)-x)\,\mathrm dx=6$$
  and
  $$\int_8^6(2x+4g(x))\,\mathrm dx=-8$$
  Evaluate
  $$\int_8^6 (f(x)-5g(x))\,\mathrm dx$$

I have a problem. So, this one question asks me to find the integral of a function, however, I have no idea where to start.
Comment: Use the linearity property of integrals, assign variable names to the integrals of the unknown functions $f$ and $g$, and turn this into a linear algebra problem.
Comment: As a first step, you could find out what $\int_8^6 f(x)$ and $\int_8^6 g(x)$ are by splitting up your two given integrals.
Answer: To solve this you need to perform some basic transformations of integrals, here's how to solve the value of $\newcommand{\dx}{\,\mathrm dx}\int_8^6 f(x)\dx$ below, the same teqnique can be used to solve the second integral.
For finding the final integral we have to transform it into some expression involving $\int_8^6 f(x)\dx$ and $\int_8^6 g(x)\dx$, and since we know the value of these, we can substitute those values in.

$$\int_6^8(3f(x)-x)\dx=6$$
The integral of a sum is the sum of the integrals
$$\int_6^83f(x)\,\mathrm dx-\int_6^8x\dx=6$$
The second integral equals $14$
$$\int_6^83f(x)\dx-14=6$$
Since $\int af(x)\dx=a\int f(x)\dx$ for any constant $a$
$$3\int_6^8f(x)\dx=20$$
$$\int_6^8f(x)\dx=\frac{20}3$$
Switching the indexes of a integral, negates the result.
$$\int_8^6f(x)\dx=-\frac{20}3$$
Comment: I got -95/3 as my solution. Is this correct?
Comment: @user1763899 Yes


CFHTTP Response - Set XML values in variables

Question: I'm making a CFHTTP request which is returning the following XML in the fileContent:
<login>
    <success>1</success>
    <player>
        <id>123456</id>
        <nucleusId>28736389714</nucleusId>
        <email>email@example.com</email>
        <preferredPersona>
            <id>19842082</id>
            <gamertag>MyGamerTag1</gamertag>
            <platform>360</platform>
        </preferredPersona>
    </player>
</login>

What I'm looking to do is declare ColdFusion variables for:

player -> id
player -> nucleusID
player -> email
player -> preferredPersona -> id
player -> preferredPersona -> gamertag
player -> preferredPersona -> platform

I've had a read around all morning but am still none the wiser on how I'd achieve this?
Answer: So all you need to do is convert some XML to a coldfusion structure?

http://www.anujgakhar.com/2007/11/05/coldfusion-xml-to-struct/
http://www.bennadel.com/blog/1039-Ask-Ben-Iterating-Over-A-ColdFusion-XML-Document.htm
http://www.cflib.org/udf/flattenXmlToStruct
ColdFusion - how to loop through XML output and adding to struct or array?

I'd probably just do it like
<cfsavecontent variable="myXML">
<login>
    <success>1</success>
    <player>
        <id>123456</id>
        <nucleusId>28736389714</nucleusId>
        <email>email@example.com</email>
        <preferredPersona>
            <id>19842082</id>
            <gamertag>MyGamerTag1</gamertag>
            <platform>360</platform>
        </preferredPersona>
    </player>
</login>
</cfsavecontent>

<cfset myXML = XMLParse(myXML)>
<cfset stuPlayer = {}>
<cfset stuPlayer.ID = myXML.login.player.ID.XmlText>
<cfset stuPlayer.nucleusID = myXML.login.player.nucleusID.XmlText>
... etc
<cfdump var="#stuPlayer#">

Answer: Over and above Duncan's answer, it seems you could probably step back, and get yourself up to speed understanding/using XML in ColdFusion before you look at any implementation stuff.

The XML document object
Using an XML object
Functions for XML object management
XML document object management reference
Using XML and ColdFusion queries - demonstrates transformation techniques.

It's always best to read and understand the docs before trying to use some part of CFML's functionality.


Backbone Fetch not by ID

Question: is it possible to fetch on backbone, by a different attribute?
Now I can only fetch by ID which will return /url/IDVALUE
is is possible to do
<code>      model.fetch({name:'VALUE'});
</code>
and then it will generate the /url/NAMEVALUE ?
Thanks.
Answer: this is a workaround and I think you should use this just to do the fetch but I think it can work
change the IdAttributte and use the name,
then when you fetch your model the url will use the name attribute
http://backbonejs.org/#Model-idAttribute
<code>var Model = Backbone.Model.extend({
  idAttribute: "name"
});
</code>

Backbone Fetch not by ID


Drupal 7 Form API, Checkboxes with key -> value from database

Question: I'm working on a custom module and I'm adding a form that uses checkboxes.  All is fine with using code like:
$form['tags'] = array(
   '#type' => 'checkboxes',
    '#options' => array(
      88 => 'option1',
      100 => 'option 2',
      79 => 'etc'
    ),
   '#title' => t('Tag this project as...'),
  );
The problem comes from the fact that I'd like to pull the key and value from the database (a specific taxonomy).  I do not want to use an autocomplete, I want to use checkboxes.
Specifically, how do I get the results from the database and format into a proper array for the options array?  Also, on the edit version of the form I'm creating, how do I show items that have been "checked" based on their value?
All of the examples I've seen are extremely basic and never show how to do this from a database call.  Thanks for reading/answering
Answer: To populate your options array with data from table my_table, with value keys from column value and text from column atext, you can use:
$options = array();
$result = db_select('my_table', 'mt')
            ->fields('mt', array('value', 'atext'))
            ->execute();
foreach ($result as $row) {
  $options[$row->value] = $row->atext;
}

To get taxonomy terms, you could use the code above to query tid and name from the taxonomy_term_data table (plus add a condition() for the vocabulary id), but for this specific usage you'd better to use the right API:
$options = array();
// Get term tree for vocabulary which id is in $vid.
$terms = taxonomy_get_tree($vid);
foreach ($terms as $term) {
  $options[$term->tid] = $term->name;
}

Just do not forget that vocabularies are tree structures. See the documentation for the taxonomy_get_tree() API to know how to limit the terms you want to get from a vocabulary wrt starting term and tree depth.
Comment: Thanks much for the great explanation!  Very helpful.  Sometimes it's very hard to know where to look in the documentation and for which api.


How to call a generator type function with a nonetype function within a loop?

Question: I have a generator function getElements in a class Reader() that yields all the elements out of an xml file. I also want to have a function getFeatures that only yields the elements with a feature tag.
How I tried it is to have a flag featuresOnly that is set to True when getFeatures is called, and in getFeatures call self.getElements, like this:
def getFeatures(self):
    self.getFeaturesOnly = True
    self.getElements()

This way in getElements() I only have to do
def getElements(self):
    inFile = open(self.path)
    for element in cElementTree.iterparse(inFile):
        if self.getFeaturesOnly == True:
            if element.tag == 'feature':
                yield element
        else:
            yield element
     inFile.close()

However, when I do this and run it
 features = parseFeatureXML.Reader(filePath)
 for element in features.getFeatures():#
       print element

I get: TypeError: 'NoneType' object is not iterable
This is because getFeatures doesn't contain a yield. Now, the way that I know how to solve this is to copy the code of getElements into getFeatures and only use the
if elementFunctions.getElmentTag(element) == 'feature':

in the getFeatures() function, but  I rather not duplicate any code. So how would I be able to keep on generator function, and have a different function where I only specefy which tag I would like to get?
Answer: First things first: You have that error because you don't return the generator
Meaning that you have to change:
def getFeatures(self):
    self.getFeaturesOnly = True
    self.getElements()

with:
def getFeatures(self):
    self.getFeaturesOnly = True
    return self.getElements()    # returning the generator

Cleared this, TBH I wouldn't design my Reader() class like this.
I'd let the getElement yield all the elements:
def getElements(self):
    inFile = open(self.path)
    for element in cElementTree.iterparse(inFile):
        yield element
    inFile.close()

And then getFeatures() do the filtering:
def getFeatures(self):
    for element in self.getElements():
        if element.tag == 'feature':
            yield element

Answer: The reason you get the TypeError is not that getFeatures doesn't contain a yield, it's because getFeatures doesn't return anything. If you want getFeatures to return the iterator returned by getElements, you have to use return:
def getFeatures(self):
    self.getFeaturesOnly = True
    return self.getElements()

While you're at it, you really shouldn't do if expr == True; just do if expr, which works even if expr is true (the concept) but not True (the object.) That said, instead of hoisting the features-only support into getElements, a more common approach is to do it in getFeatures itself, like so:
def getFeatures(self):
    for element in self.getElements():
        if element.tag == 'feature':
            yield element

def getElements(self):
    inFile = open(self.path)
    for element in cElementTree.iterparse(inFile):
        yield element
    inFile.close()


Usando C# 6.0 no VS2010

Question: Tenho o Visual Studio 2010 instalado. Gostaria de saber se é possível usar os recursos da versão 6.0 do C# na minha IDE
Answer: Infelizmente você não poderá utilizar os recursos do C# 6 no VS 2010. Se fosse ao menos o VS 2012.
Acompanhe a evolução da linguagem
Versões atuais

C# 7.1 -> VS2017 versão 15.3 || .NET Core 2.0
async main, inferência de nome de membro de tupla, expressão padrão, correspondência de padrões com generics.
C# 7 -> VS2017 || .NET Core 1.0 e posteriores
Principais: tuplas, ref locals e ref return, correspondência de padrões (incluindo instruções de comutação baseadas em padrões), declarações de parâmetros out, funções locais, literais binários, separadores de dígitos e retornos arbitrários assíncronos.
C# 6 -> VS2015 .NET 4.6 || .NET Core 1.0
Implementado pelo Roslyn. Inicializadores para propriedades implementadas automaticamente, usando diretrizes para importar membros estáticos, filtros de exceção, membros indexados e inicializadores de elementos, await em catch e finally, método de extensão Add em inicializadores de coleções.

Versões anteriores
A seguir estão listados as principais funcionalidades que foram introduzidas em versões anteriores da linguagem C# e Visual Studio .NET.

C# 5 -> VS2013

Esta versão do Visual Studio incluiu correções de bug, aprimoramentos de desempenho e visualizações de tecnologia da Plataforma do Compilador .NET ("Roslyn");

C# 5 -> VS2012 .NET 4.5 (4.7)

Async/await, atributos de informações do chamador;

Para direcionar para o .NET Framework 4.7 no Visual Studio 2012 ou posterior, instale o Pacote do Desenvolvedor do Microsoft .NET Framework 4.7.
C# 4 -> VS2010 .NET 4

Dynamic, argumentos nomeados, parâmetros opcionais e covariância e contravariância genéricas;

C# 3 -> VS2008 .NET 3.5

Inicializadores de objeto e coleção, expressões lambda, métodos de extensão, tipos anônimos, propriedades automáticas, inferência de tipos var local e LINQ (Consulta Integrada à Linguagem);

C# 2 -> VS2005 .NET 2.0

Métodos anônimos, genéricos, tipos anuláveis, iteradores/suspensão, classes static, covariância e contravariância para delegados;

C# 1.1 -> VS2003

Comentários da documentação XML e pragma #line;

C# 1 -> VS2002 .NET 1.0

A primeira versão do C#.

Usando C# 6.0 no VS2010


LDAP Getting Full user Name C++

Question: I'm writing a little Application at my Office.
In this Application i have to get the full UserName.
It's written in Qt / C++
I like to get this Information over LDAP.
Now i can connect to our Active Directory Server and can connect to the Search function.
This information is from an example written by Microsoft.
But at this Point the Example confuses me.
I Don't get it how i can give this Server an Username and receive the Full Name.
Link to the Microsoft example: http://msdn.microsoft.com/en-us/library/windows/desktop/aa367016(v=vs.85).aspx
Can someone give me an Advice how i can get this Information?
Thanks and With best regards
Chris ;)
P.S. Sorry for the bad English.
P.S.S and if i missed Something or you need more Information just say it.
LDAP_query.cpp:
#include <settings.h>
#include <ui_settings.h>
#include <mainwindow.h>
#include <ui_mainwindow.h>
#include <QtGui>
#include <QString>
//Header Files for LDAP Query
#include <windows.h>
#include <winldap.h>
#include <winber.h>
#include <rpc.h>
#include <rpcdce.h>
#include <stdio.h>

void MainWindow::LDAP_query(QString name)
{

//Name contains the username

PWCHAR hostName = NULL;
PWCHAR Domain = NULL;
PWCHAR pMyDN = NULL;
PWCHAR pUserName;
PWCHAR pPassword;
LDAP* pLdapConnection = NULL;
ULONG version = LDAP_VERSION3;
ULONG getOptSuccess = 0;
ULONG connectSuccess = 0;
INT returnCode = 0;

//  Convert String hostname to a wchar_t*
char *hostName_2 = "Server.office.com";
QString Test = QString::fromAscii(hostName_2);
hostName = (WCHAR*)(Test.utf16());

//Connverting Char to WCHAR to connect to Directory
char *pMyDN_2 = "Ou=directory,Dc=Name,DC=office";
QString test2 = QString::fromAscii(pMyDN_2);
pMyDN = (WCHAR*)(test2.utf16());

//Open Connection
pLdapConnection = ldap_init(hostName, LDAP_PORT);
//Setting Connection Parm's

  ldap_set_option(pLdapConnection, LDAP_OPT_PROTOCOL_VERSION, (void*)&version);
ldap_connect(pLdapConnection, NULL);
returnCode = ldap_bind_s(pLdapConnection, pMyDN, NULL, LDAP_AUTH_NEGOTIATE);

if(returnCode == LDAP_SUCCESS)
{
    ui->InputA->setText("Connection sucessfull");
}
else
{
    ui->InputA->setText("Connection unsucessfull");
}

//Variables for Search Results
LDAPMessage* pSearchResult;
PWCHAR pMyFilter = NULL;
char *pMyFilter_2 = "(&(objectCategory=person)(objectClass=user))";
QString Test7 = QString::fromAscii(pMyFilter_2);
pMyFilter = (WCHAR*)(Test7.utf16());

PWCHAR pMyAttributes[6];
ULONG errorCode = LDAP_SUCCESS;

pMyAttributes[0] = (WCHAR*)QString("cn").utf16();
pMyAttributes[1] = (WCHAR*)QString("company").utf16();
pMyAttributes[2] = (WCHAR*)QString("department").utf16();
pMyAttributes[3] = (WCHAR*)QString("telephoneNumber").utf16();
pMyAttributes[4] = (WCHAR*)QString("memberOf").utf16();
pMyAttributes[5] = NULL;

errorCode = ldap_search_s(
                    pLdapConnection,    // Session handle
                    pMyDN,              // DN to start search
                    LDAP_SCOPE_SUBTREE, // Scope
                    pMyFilter,          // Filter
                    pMyAttributes,      // Retrieve list of attributes
                    0,                  // Get both attributes and values
                    &pSearchResult);    // [out] Search results

if (errorCode != LDAP_SUCCESS)
   {
       ui->InputB->setText("ldap_search_s failed with");
       ldap_unbind_s(pLdapConnection);
       if(pSearchResult != NULL)
           ldap_msgfree(pSearchResult);
     }
   else
        ui->InputB->setText("ldap_search succeeded \n");

//here i like to receive the user's full name

//Closing Connection
ldap_unbind(pLdapConnection);

ui->Test_Ausgabe -> setText(name);
}

Answer: It appears that you are requesting the cn or commonName, sometimes the value of that attribute is the full name. If it is not, try adding givenName and sn to the list of requested attributes. givenName is the first name sn is the surname or last name.
Comment: now i after getting some Errors.
i got the full name of the useres. Just use "cn" then qDebug showed me the full names of the users.
Now i just only need to filter after username under Windows (and getting this from AD).
Then a big step i done
Thank you @Terry Gardner
Answer: Just a little other Question.
Below you see the Lines which get the things i Need.
It sounds a little Stupid but when i run the code the Attributes which are in pMyAttributes[0], will never be Displayed.
I don't care because i don't need this Information but it don's seems like it is Right.
I'm a little Scared that i will get later wrong Information and my Programm will get Error's.
Settings Filters With "PWCHAR pMyAttributes[4];" will Display nothing
But Setting Filter "PWCHAR pMyAttributes[5];" like that and i get Everything i wanted.
Can someone Explain this ?
PWCHAR pMyAttributes[4];
ULONG errorCode = LDAP_SUCCESS;

pMyAttributes[0] = (WCHAR*)QString("sn").utf16();
pMyAttributes[1] = (WCHAR*)QString("mailNickname").utf16();
pMyAttributes[2] = (WCHAR*)QString("cn").utf16();
pMyAttributes[3] = NULL;

Code for Displaying the user's:
// Get the number of entries returned.
  ULONG numberOfEntries;

numberOfEntries = ldap_count_entries(
                    pLdapConnection,    // Session handle
                    pSearchResult);     // Search result

/*if(numberOfEntries == NULL)
{
    qDebug("ldap_count_entries failed with 0x%0lx \n",errorCode);
    ldap_unbind_s(pLdapConnection);
    if(pSearchResult != NULL)
        ldap_msgfree(pSearchResult);
}
else
    qDebug("ldap_count_entries succeeded \n");
*/
qDebug("The number of entries is: %d \n", numberOfEntries);

//----------------------------------------------------------
// Loop through the search entries, get, and output the
// requested list of attributes and values.
//----------------------------------------------------------
LDAPMessage* pEntry = NULL;
PWCHAR pEntryDN = NULL;
ULONG iCnt = 0;
char* sMsg;
BerElement* pBer = NULL;
PWCHAR pAttribute = NULL;
PWCHAR* ppValue = NULL;
ULONG iValue = 0;

for( iCnt=0; iCnt < numberOfEntries; iCnt++ )
{
    // Get the first/next entry.
    if( !iCnt )
        pEntry = ldap_first_entry(pLdapConnection, pSearchResult);
    else
        pEntry = ldap_next_entry(pLdapConnection, pEntry);

    // Output the entry number.
    qDebug("ENTRY NUMBER %i \n", iCnt);

    // Get the first attribute name.
    pAttribute = ldap_first_attribute(
                  pLdapConnection,   // Session handle
                  pEntry,            // Current entry
                  &pBer);            // [out] Current BerElement

    // Output the attribute names for the current object
    // and output values.
    while(pAttribute != NULL)
    {
        // Output the attribute name.
        QString abc = QString::fromWCharArray(pAttribute);
        qDebug() << "abc" << abc;

        // Get the string values.

        ppValue = ldap_get_values(
                      pLdapConnection,  // Session Handle
                      pEntry,           // Current entry
                      pAttribute);      // Current attribute

        // Print status if no values are returned (NULL ptr)
        if(ppValue == NULL)
        {
            qDebug(": [NO ATTRIBUTE VALUE RETURNED]");
        }

        // Output the attribute values
        else
        {
            iValue = ldap_count_values(ppValue);
            if(!iValue)
            {
                qDebug(": [BAD VALUE LIST]");
            }
            else
            {
                // Output the first attribute value
                QString abc2 = QString::fromWCharArray(*ppValue);
                qDebug()<< "abc2" << abc2;
                qDebug()<< "iValue" << iValue;

                // Output more values if available
                ULONG z;
                for(z=1; z<iValue; z++)
                {
                    QString abc3 = QString::fromWCharArray(ppValue[z]);
                    qDebug() << "abc3" << abc3;
                }
            }
        }

        // Free memory.
        if(ppValue != NULL)
            ldap_value_free(ppValue);
        ppValue = NULL;
        ldap_memfree(pAttribute);

        // Get next attribute name.
        pAttribute = ldap_next_attribute(
                        pLdapConnection,   // Session Handle
                        pEntry,            // Current entry
                        pBer);             // Current BerElement
        qDebug("\n");
    }

    if( pBer != NULL )
        ber_free(pBer,0);
    pBer = NULL;
}

//Closing Connection
ldap_unbind(pLdapConnection);

ui->Test_Ausgabe -> setText(name);
}

LDAP Getting Full user Name C++


Apache 2 sites-enabled problem

Question: I have a virtual machine running Apache 2 and am having the worst time attempting to set up multiple name based virtual hosts. Basically as soon as I upload and enable a new virtual host file in the sites-enabled folder the entire web server stops responding. It won't start, I can't connect to it from a web browser, and it won't start back up again until I remove the file. Here are the steps I am following:

Creating a new VirtaualHost file and uploading it to etc/apache2/sites-enabled, VirtualHost file looks like the code below and is named www.glutenfreaks.com:

        ServerAdmin firstname.lastname@example.com
        ServerName  www.glutenfreaks.com
        ServerAlias glutenfreaks.com
    # Indexes + Directory Root.
    DirectoryIndex index.php
    DocumentRoot /var/www/glutenfreaks/

    # CGI Directory
    ScriptAlias /cgi-bin/ /var/www/glutenfreaks/cgi-bin
    <Location /cgi-bin>
            Options +ExecCGI
    </Location>

    # Logfiles
    ErrorLog  /var/www/glutenfreaks/logs/error.log
    CustomLog /var/www/glutenfreaks/logs/access.log combined

From the command line I'm then executing "a2ensite www.glutenfreaks.com"
Then I reload the server: "/etc/init.d/apache2 reload"

And then everything goes boom and nothing works anymore.
Help??
Thanks,
Evan
Answer: what happens when you do apache2ctl configtest ? and what do you see in /var/log/apache2/error.log
Comment: I'm assuming you took out the necessary stuff with   from your paste..
Answer: Your apache not responding because he can`t load his config-file.
The first thing you must do - remember if you do something else mentioned here.
The next one - #tail /var/log/apache2/error.log, if you enabled apache error log. If you don`t, enable it and start apache.
BTW, the Syntax of VirtualHost directive is <VirtualHost addr[:port] [addr[:port]] ...>...</VirtualHost> - ie <VirtualHost 10.1.2.3>...</VirtualHost>. Maybe you need write the right host?

Apache 2 sites-enabled problem


SQL Server : creating a top 3 view - having difficulties

Question: This is my first time asking a SQL related question. I am having a difficult time getting this query to work.
Basically, I have a database that has 3 tables Course, Faculty and Adjunct. This query is supposed to create a view named Top3Enrollment that returns FirstName, LastName, TotalStudents, and MaxEnrollment of the 3 faculty members with the largest total enrollment for their courses, along with the highest enrollment among the classes they teach.
When attempting to write the query I get an error with selecting the column FirstName
My query:
CREATE VIEW Top3Enrollment
AS
    SELECT TOP 3 PERCENT
        FirstName, LastName, SUM(Enrollment), MAX(Enrollment)
    FROM
        Faculty
    JOIN
        Course ON Faculty.Faculty_ID = Course.Faculty_ID
    ORDER BY
        MAX(Enrollment);

The error I get is:

Msg 8120, Level 16, State 1, Procedure Top3Enrollment, Line 3 [Batch Start Line 0]
  Column 'Faculty.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

My database structures:
CREATE TABLE Faculty
(
    Faculty_ID VARCHAR(2),
    LastName VARCHAR(20),
    FirstName VARCHAR(20),
    Department VARCHAR(10),
    Campus VARCHAR(10)
);

INSERT INTO Faculty
VALUES ('1', 'Brown', 'Joe', 'Business', 'Kent'),
       ('2', 'Smith', 'John', 'Economics', 'Kent'),
       ('3', 'Jones', 'Sally', 'English', 'South'),
       ('4', 'Black', 'Bill', 'Economics', 'Deerwood'),
       ('5', 'Green', 'Gene', 'Business', 'South');

CREATE TABLE Course
(
    Course_ID CHAR(2),
    Ref_Number CHAR(5),
    Faculty_ID VARCHAR(2),
    Term Char(1),
    BegDate SMALLDATETIME,
    Enrollment INTEGER,
    TotRev FLOAT
);

INSERT INTO Course
VALUES ('1', '12345', 'a', 'A', '2016-01-08 00:00:00', 24, 12345.32 ),
       ('2', '54321', '3', 'B', '2016-02-04 00:00:00', 18, 21435.51 ),
       ('3', '13524', '1', 'B', '2016-02-04 00:00:00', 7,  1256.67 ),
       ('4', '24653', '1', 'C', '2016-03-04 00:00:00', 29, 54421.11 ),
       ('5', '98765', '5', 'A', '2016-01-08 00:00:00', 35, 246753.23),
       ('6', '14862', '2', 'B', '2016-02-04 00:00:00', 14, 9876.87),
       ('7', '96032', '1', 'C', '2016-03-04 00:00:00', 8,  863159.31),
       ('8', '81256', '5', 'A', '2016-01-08 00:00:00', 5,  98762.14),
       ('9', '64321', '2', 'C', '2016-03-04 00:00:00', 23, 2965.98),
       ('10','90908', 'a', 'A', '2016-01-08 00:00:00', 45, 91724.02),
       ('11','90908', '3', 'A', '2016-01-08 00:00:00', 23, 73725.77),
       ('12','90908', '3', 'A', '2016-01-08 00:00:00', 16, 84224.29),
       ('13','90908', 'b', 'A', '2016-01-08 00:00:00', 13, 42719.82);

CREATE TABLE Adjuncts
(
    Faculty_ID Char(2),
    LastName VARCHAR(20),
    FirstName VARCHAR(20),
    Department VARCHAR(10),
    Campus VARCHAR(10)
);

INSERT INTO Adjuncts
VALUES ('a', 'Rogers', 'Aaron', 'Business', 'Kent'),
       ('b', 'Manning', 'Peyton', 'Economics', 'North'),
       ('c', 'Drew', 'Maurice', 'English', 'Cecil'),
       ('d', 'Griffin', 'Robert', 'Music', 'Deerwood'),
       ('e', 'Goodell', 'Roger', 'Economics', 'South'),
       ('f', 'Vilma', 'Jonathan', 'Business', 'Kent');

Note:
I Understand I cannot have Order By but I wouldn't know what else to use
Added the database code
Comment: This question is impossible to answer, because there simply isn't enough information about what you have or what you want. You know what you want, but we have no idea, so you're going to have to put in a lot more detail
Comment: Ill add the database code if that helps. This is my first time posting a SQL question and didn't know how much to include.
Comment: Realistically for SQL questions: create table/insert statements for your existing real data, the full query you've written so far, and your desired output. Even better if you can create an SQL Fiddle, db<>fiddle, dbfiddle or similar and just post the link. these are websites that let you "create" a db and run a query against it. Then the pros can get straight into solving your problem rather than taking their time to write code to reproduce your db before they start writing the solution to your woes. See also https://stackoverflow.com/help/mcve
Answer: When you use aggregate functions like sum and max together with other columns you need to group your aggregations by those other columns.
Add GROUP BY like this
SELECT TOP 3 PERCENT FirstName, LastName, SUM(Enrollment), MAX(Enrollment)
FROM Faculty
JOIN Course ON Faculty.Faculty_ID = Course.Faculty_ID
GROUP BY FirstName, LastName
ORDER BY MAX(Enrollment);

Comment: Ohhh I never knew you could have a group by their! Thank you! Works now! :D


Ordered Arrangements: number of ways of arranging $1-9$ in a circle so that sum of 3 adjacent is divisible by 3

Question:
Find the number of ways of arranging the numbers $1, 2, 3, ... 9$ in a circle, so that the sum of any three adjacent numbers is divisible by $3$. (Two arrangements are considered the same if one arrangement can be rotated to obtain the other.)

I worked out that if I have the numbers in ascending/descending order, it will be divisible by $3$ (because $x-1 + x + x+1$ would be equal to $3x$).
I'm not sure how to use that information to work out the total number though (or if there are other ways to place them).
Please provide an answer to my question and help me with how to proceed with my approach.
Comment: Hint: fix the location of $1$ (possible thanks to the rotation equivalence), and convince yourself that its two neighbors must be congruent to $0$ and $2$ modulo $3$. Then generalize....
Answer: Hint: $a_1 \equiv a_4 \equiv a_7 \pmod 3$.
Likewise for the other indices.
This gives us a constraint, dividing up into 3 sets of 3. Under this constraint, all permutations work.
Hence $ \dfrac{3!\times (3!)^3}{9} = 144$ ways.
Comment: can you explain how the equation works (like the purpose of each step and why)? Thank you for the help
Comment: $a_1+a_2+a_3\equiv a_2+a_3+a_4\pmod{3}$. Work out the rest, if you get stuck, state what you've done and where you're stuck.
Comment: This is a nice approach, but I think you're missing a factor of $3!$. You can permute the values of $a_1,a_2,a_3$ mod $3$, then permute within each set of the same value mod $3$, giving $3!^4/9$.
Comment: Yes, that's true. 24 felt too low.
Comment: @EspeciallyLime permuting within each set might give us extra cases such as an arrangement of the form: $a_1(mod 3)--\>a_2(mod 3)--\>a_3(mod 3)--\>a_3(mod 3)--\>a_1(mod 3)...$ which is undesirable?
Comment: @CalvinLin I think 24 should be the correct answer?
Comment: Your formula is correct, but it evaluates to 144, not 216.
Comment: @RobPratt Thanks, fixed.
Answer: Hint: You have $3$ numbers of the form $3k$, $3$ of the form $3k+1$ and $3$ of the form $3k−1$.
Start with fixing a $3k$ at the start.
If you put another $3k$ after it, will the resulting combination $3k,3k,...$ be possible?

 No, because that would demand another $3k$ after it ($\because$ sum of $3$ consecutive numbers must be divisible by $3$)
 and so on, and the whole arrangement would need to be of the form $3k,3k,3k,3k,3k,...$ which is impossible.

Conclude you only have $2$ possibilities of arrangement

$3k,3k+1,3k−1,3k,3k+1,...$
$3k,3k−1,3k+1,..$

(the second is the mirror of the other).

 Suppose we start with $3k,3k+1$.
 Then, we would need a number of the form $3k-1$ after that for the sum $(3k)+(3k+1)+?$ to be divisible by $3$.
 Now, we have $3k,3k+1,3k-1,..$.
 For the sum $(3k+1)+(3k-1)+?$ to be divisible by $3$ we need to have a $3k$ after $3k-1$ giving us $3k,3k+1,3k-1,3k,..$.

Calculate the number of possibilities in any one. Double that is the answer.
Answer: First, when we look at this problem we must think what does every set of 3 numbers contain. Since, $1 + 2 + 3 \equiv  0 \mod 3$ and $2 + 3 + 4 ≡  0 \mod 3$ then $1 + 2 + 3 \equiv 2 + 3 + 4 \mod 3$. So $1 ≡ 4 \mod 3$.
Then we use the same tactic to find that $4 ≡ 7 \mod 3$. So $1 ≡ 4 ≡ 7 \mod 3$. Then we also find that $2 ≡ 5 ≡ 8 \mod 3$ and $3 ≡ 6 ≡ 9 \mod 3$. And since $1 + 2 +3 ≡  0 \mod 3$, we realize that a set of 3 must have one number from each set.
We should start by putting $1$ on top to account for rotational symmetry. Then we have $2$ choices for which set to be to the right of the one. Then we have $3$ choices for which number from the set shall go there. Then there are $3$ choices for the number to the right of that one because there are $3$ numbers from the set that we did not use so far. Then there are $2$ choices for the number that goes to the right of that because we already used $1$ from that set. Then another $2$ for the next. and $2$ for the next. then there is only one option for how to arrange the rest of the numbers because there is only one number left from each set.
So there are $2 * 3 * 3 * 2 * 2 * 2 * 1 = 144$ total ways to arrange the numbers $1-9$ in a circle if the sum of every $3$ adjacent numbers must be divisible by $3$.
Comment: I confirmed via constraint programming that 144 is the correct count.


How to remove an item from a list of tuples in c++?

Question: I'm iterating over my list of tuples :   list<tuple<int,int>> edges, and want to remove some elements in it. This is necessary for me to reduce the total overhead as I am working with huge data.
std::list<tuple<int, int>>::iterator it;
for (it = edges.begin(); it != edges.end(); ++it)
{
  if (get<0>(*it) == 0 || get<1>(*it) == 0){
      edges.remove(*it);
  }

}

As I know, remove(element) works, but here edges.remove(*it) does not. How can I do this correctly?
Comment: Unless you have a _really_ darn good reason to use `std::list`, `std::vector` is likely just better.
Comment: Offtopic: IMHO tuple with fixed types are useless and make code harder to read and maintain.
Answer: You can use erase() to specify an element to remove by an iterator.
It returns an iterator for the next element, so don't forget to catch that.
std::list<tuple<int, int>>::iterator it;
for (it = edges.begin(); it != edges.end(); ) // don't increment it here
{
  if (get<0>(*it) == 0 || get<1>(*it) == 0){
      it = edges.erase(it);
  } else {
      ++it;
  }
}

Answer: In C++20, you can simply use a specialization of std::erase_if for std::list to do this.
#include <list>
#include <tuple>

int main() {
  std::list<std::tuple<int, int>> l;
  std::erase_if(l, [](const auto& elem) {
    auto& [first, second] = elem;
    return first == 0 || second == 0; });
}

Demo
However, since std::list itself has a remove_if member function, it is more appropriate to use it directly, since it applies to any C++ standard.
Answer: In my opionion remove_if which is a dedicated and optimized function for a std::list should be used. This will avoid unnecessary indirections.
Please read here about it.
The result will be an efficient one liner.
Please see one of many potential solutions:
#include <iostream>
#include <list>
#include <tuple>

using MyTuple = std::tuple<int,int>;
using MyList = std::list<MyTuple>;

int main() {
    // Define some demo data
    MyList myList{{0,1},{2,3},{4,5},{6,0},{7,8},{9,10},{0,0}};

    // Predicate function. Define whatever you want
    auto unwanted = [](const MyTuple& t) {return std::get<0>(t)==0 or std::get<1>(t)==0;};

    // Remove all unwanted stuff
    myList.remove_if(unwanted);

    // Some debug output
    for (const auto&[l,r] : myList)
        std::cout << l << ' ' << r << '\n';
}


Change in twitter login

Question: As we know, there have been changes in access to the twitter API referring to callbacks URLs.
So far, I have been using the identification callback with firebase, as I indicated here:

This has been working perfectly so far.
I read in the documentation that now you have to indicate the callback, according to android or iOS in the following way:

twitterkit- : // if using Twitter Kit for iOS or
  twittersdk: // if using Twitter Kit for Android.

My application is only developed for android.
I have tried all the possible variants, but I always get the following error:
The client application failed validation: Not a valid callback URL format.
The tested options have been:
twittersdk://pfa89MGYola62VIln ........ (MY_CONSUMER_KEY)

twittersdk://MY_APP-android.firebaseapp.com/__/auth/handler

twittersdk://https://MY_APP-android.firebaseapp.com/__/auth/handler

I have activated and deactivated the check "enable callback locking" ...
I've tried everything, I'm a little desperate
For another test, I tried to register the URL callback as if it were the iOS platform
twitterkit-MY_CONSUMER_KEY://

and it was accepted on the first attempt.
I do not mind losing the relationship with firebase, the truth is that I was not using it, but I have a serious problem if I can not connect with twitter again.
I appreciate any help.
Answer: I found the solution, I put it here in case it can be of help to someone.
The truth is that it is not well specified in the documentation, you have to take two steps.
First: activate the "enable callback locking" checkbox
Second: indicate the android sdk for twitter, WITHOUT CONSUMER KEY, unlike iOS users.
It would be like this:

I hope it helps
Comment: can you specify where one can find "enable callback locking". I keep reading that but in the dev console i do not see that.
Comment: For me, it was enough to just add "twittersdk://" into the callback URLs.

Change in twitter login


Setfacl: Operation not supported

Question:
Possible Duplicate:
setfacl: x.txt: Operation not supported

I am trying to do:
setfacl -m d:u:apache:rw /etc/asterisk/additional/

but getting:
setfacl: /etc/asterisk/additional/: Operation not supported

my /etc/fstab looks like this:
LABEL=/     /           ext4    defaults,noatime  1   1
tmpfs       /dev/shm    tmpfs   defaults        0   0
devpts      /dev/pts    devpts  gid=5,mode=620  0   0
sysfs       /sys        sysfs   defaults        0   0
proc        /proc   proc    defaults        0   0
/dev/sda3   none    swap    sw,comment=cloudconfig  0   0

Can someone help me please? I tried what others  tried and ended up screwing my server and had reinstall. Now I'm back at this step and don't wanna do the same mistake. Any help is appreciated!
Answer: Try adding ',acl' after noatime. Then reboot or just invoke mount -o remount /.
Comment: No need to reboot, just `mount -o remount /`.

Setfacl: Operation not supported


systemd service runs but then exits

Question: Strange for me:
I have a bash script (cams_record.sh) which will take care of recordings of my ipcams.
This script should be started by systemd (cams_record.service). That service file should take care of the bash script (which should always be running).
So I created a service file, but when I start the systemd service: it starts/runs which is showed by the systemd status check. However when I check the status again then systemd service has been stopped. What might be wrong (f.i. in the service file)?
Below the output of starting cams_record.service and then twice the output of the status:
systemctl start cams_record

systemctl status cams_record
. cams_record.service - record ipcams
   Loaded: loaded (/lib/systemd/system/cams_record.service; enabled; vendor preset: enabled)
   Active: active (running) since wo 2017-11-01 11:03:53 +03; 39ms ago
 Main PID: 22904 (bash)
   CGroup: /system.slice/cams_record.service
           ??22904 /bin/bash /media/USB2/movie/cams/cams_record.sh
           ??22912 /bin/bash /media/USB2/movie/cams/cams_record.sh
           ??22913 ps -ax
           ??22914 grep [f]fmpeg
           ??22915 grep rtsp://192.168.2.21:554/live/ch00_0
           ??22916 grep \-t 3600

nov 01 11:03:53 Shuttle systemd[1]: Started record ipcams.

systemctl status cams_record
. cams_record.service - record ipcams
   Loaded: loaded (/lib/systemd/system/cams_record.service; enabled; vendor preset: enabled)
   Active: inactive (dead) (Result: exit-code) since wo 2017-11-01 11:03:55 +03; 5s ago
  Process: 22988 ExecStart=/bin/bash /media/USB2/movie/cams/cams_record.sh (code=exited, status=1/FAILURE)
 Main PID: 22988 (code=exited, status=1/FAILURE)

nov 01 11:03:55 Shuttle systemd[1]: cams_record.service: Unit entered failed state.
nov 01 11:03:55 Shuttle systemd[1]: cams_record.service: Failed with result 'exit-code'.
nov 01 11:03:55 Shuttle systemd[1]: cams_record.service: Service hold-off time over, scheduling restart.
nov 01 11:03:55 Shuttle systemd[1]: Stopped record ipcams.
nov 01 11:03:55 Shuttle systemd[1]: cams_record.service: Start request repeated too quickly.
nov 01 11:03:55 Shuttle systemd[1]: Failed to start record ipcams.

The content of the used service file is:
[Unit]
Description=record ipcams
After=network.target
Requires=network.target
RequiresMountsFor=/media/USB2

[Service]
Type=forking
WorkingDirectory=/media/USB2/movie/cams
ExecStart=/media/USB2/movie/cams/cams_record.sh
RemainAfterExit=yes
SyslogIdentifier=cams_record

[Install]
WantedBy=multi-user.target

Answer: The reason why your script fails has as much to with the script as it does with systemd.
What conditions cause your script to exit with status code 1?
Add logging to the script to see how far it gets before it dies.
Confirm your script runs fine outside of systemd, then review Why do things behave differently under systemd?.
Also, consider referencing the network-online service rather than network service, if you want to be certain the network is up when your script runs.
Comment: Thx I will try what you wrote, but for me it is strange cause the script runs outside systemd, so directly from the CLI. Will report when I tried ur suggestions.
Answer: @Mark Stosberg: I did what you wrote/suggested.
Well, as written, the bash script runs in CLI (outside systemd) and I think in systemd the script does not exit before the end.
I changed in service file: network -> network-online. Tried different things in the service file like a "&" (at (end of) ExecStart): same result unfortunately. Then I added "PIDFile=" and always get a MAINPID error (also when I remove the "&" again).
So, I went back to the service file (see 1st post) and only changed forking into simple. It seems everything is running. What I can not explain is that in the status view of the running service I see: "active exited" and "Main process exited, code=exited, status=1/FAILURE". For me weird, coz "systemctl is-active cams_record.service" gives me: active:
systemctl status cams_record.service
. cams_record.service - record ipcams
   Loaded: loaded (/lib/systemd/system/cams_record.service; enabled; vendor preset: enabled)
   Active: active (exited) (Result: exit-code) since vr 2017-11-03 09:10:10 +03; 44s ago
  Process: 31355 ExecStart=/media/USB2/movie/cams/cams_record.sh (code=exited, status=1/FAILURE)
 Main PID: 31355 (code=exited, status=1/FAILURE)
   CGroup: /system.slice/cams_record.service
           ??31379 ffmpeg -i rtsp://192.168.2.21:554/live/ch00_0 -r 30 -vcodec copy -an -t 1200 -nostats -nostdin /media/USB2/movie/cams/cam1/cam20171103_0910.mp4

systemd[1]: Started record ipcams.
systemd[1]: cams_record.service: Main process exited, code=exited, status=1/FAILURE

So some questions left:

Is it normal that the service is running (Type simple), the script has been executed well (it does start ffmpeg; checked with ps -ax) and still an error in the status view
I always thought when starting a script, type forking is better, but unfortunately I can not get it working.

Later:
In the bash script was a line like:
  if ! ps -ax | grep [f]fmpeg |grep ; then start ffmpeg in background
I put that part (where running processes of all cams are checked/restarted) in a "while true-loop" and it seems to be working now only with type=simple. Strange, but working (as it seems to be)

systemd service runs but then exits


make - Only create intermediate files if needed

Question: I'm writing a Makefile to build a Latex document depending on plots whose data is generated from some other data by some python script.
It looks like this
% pdf plot needed by final document
build/tikz-standalone/%.pdf: build/tikz-standalone/%.tex xy_data
    cd $$(dirname $@) && ../../latexrun $$(basename $<)

xy_data: $(PLOT_DATA) tools/plots/crunch.py | build
    % crunch.py will create data for plots needed by build/tikz-standalone/%.tex
    PYTHONPATH=. tools/plots/crunch.py

build:
    mkdir -p build build/other_stuff ...

crunch.py generates several data files in build/data which are needed by build/tikz-standalone/%.tex. To create these files it uses other files stored in the variable PLOT_DATA. I could put a list of the intermediate data files in build/data into the Makefile at the position of xy_data. I don't like this as this would require me to update the list whenever a new file is added. What I want is that all data files are recreated whenever crunch.py or $(PLOT_DATA) has changed.
Is there a way to express this in Make?
Answer: If you do not want to provide and maintain the list of the generated files you can turn your (implicitly) phony xy_data target into an empty file used as a marker. Simply touch it at the end of the recipe:
BUILDDIRS := build build/other_stuff ...

build/tikz-standalone/%.pdf: build/tikz-standalone/%.tex xy_data
    cd $(dir $@) && ../../latexrun $(notdir $<)

xy_data: $(PLOT_DATA) tools/plots/crunch.py | $(BUILDDIRS)
    PYTHONPATH=. tools/plots/crunch.py
    touch $@

$(BUILDDIRS):
    mkdir -p $@

Note: I also improved a bit some other aspects:

Use of make functions dir and notdir instead of the shell equivalents.
Variable declaration for the build directories to avoid writing the same list several times, which is tedious and error prone.
Explicit list of all build directories as order-only prerequisites instead of just one, which could lead to unexpected results if this single one exists but not some others.
Generic rule for all build directories thanks to the $@ automatic variable.


Ruby - alternative style for determining if object is contained within a list?

Question: Let's say you have a conditions with multiple ORs, e.g.
if action == 'new' || action == 'edit' || action == 'update'

Another way to write this is:
if ['new', 'edit', 'action'].include?(action)

but that feels like a 'backwards' way to write the logic.
Is there any built-in way to do something like:
if action.equals_any_of?('new', 'edit', 'action')

?
Update - I'm quite keen on this little snippet:
class Object
  def is_included_in?(a)
    a.include?(self)
  end
end

Update 2 - improvements based on the comments below:
class Object
  def in?(*obj)
    obj.flatten.include?(self)
  end
end

Comment: yeah, that's handy, I usually write a shorter `Object#in?`: http://stackoverflow.com/a/4421030/188031
Comment: I'm not much of a Ruby dev, but I like the second one (it's what I'd do in JavaScript).
Comment: Perhaps `is_included_in?(*a)` would be more error-proof.
Answer: Use a regex?
action =~ /new|edit|action/

Or:
action.match /new|edit|action/

Or just write a simple utility method that's semantically-meaningful in the context of your app.
Comment: I like this. If I was dealing with strings I'd use this, wish there was something as concise for other objects.
Comment: @AndyWaite If you're dealing with an app-specific object (not really clear from the question) then the "simply utility method" meaningful to your app is likely the best option.
Answer: Yet another way would be
case action
when 'new', 'edit', 'action'
  #whatever
end

You can also use a regular expression for a case like this
if action =~ /new|edit|action/

Comment: It's a bit more verbose but I think would be good in some situations.
Answer: You can use the %w notation for arrays of strings:
%w(new edit action).include? action

Comment: Yeah, but that still seems backwards, i.e. the opposite how how you would describe the purpose of that line.


Divisibility Tests in Various Bases

Question: Background
One thing that has been on my mind lately is why a number of simple rules work for determining if some large number is a multiple of some other number. In base 10, I was taught the following divisibility rules:

2: Ends with an even digit
3: Sum all the digits. If that number is a multiple of 3, so is the whole number
4: The last two digits are a multiple of 4
5: Last digit is a 5 or 0
6: Number is an even multiple of 3
8: The last 3 digits are a multiple of 8
9: Sum all the digits. If that number is a multiple of 9, so is the whole number
10: Last digit is 0

Multiples of 1 are trivial. I also don't know any rule for 7 in base 10, but I noticed some interesting patterns that might apply to some other bases. In base 6, you get these rules:

2: Ends with even digit
3: Ends with 0 or 3
4: Last two digits are a multiple of 4
5: Sum all the digits. If that number is a multiple of 5, so is the whole number.
6: Last digit is 0

So there are some general rules given some radix R:

Multiples of R end in 0
Factors of R can use the last digit only for multiples
R-1 and its factors can use the "sum the digits" trick
You can compose rules from a existing multiples:

If A and B have no common multiples, then the rule for AB is the rule for A anded with the rule for B

For instance, in base 10, 6 uses both rules for 2 and 3 in conjunction because 2 and 3 are its prime factors

If A is a rule that uses the last digit, then An can use the last n digits.
If A has a divisibility rule, then RnA can exclude the last n digits and use the rule for A.

Given these rules, 12 rules should work for base 10 as a combination of the 3 rule and the 4 rule.
The Question

Is my reasoning here sound? Are there any formal proofs already done on the subject?
Are there other reasonable rules that could be used for, say, multiples of 7 in base 10?
Comment: Interesting subject but I don't think it's accurate to call these "mnemonics" (aids to remembering sonerhing). Really they're convenient shortcuts to *calculating* something. "Divisibility tests" might be better. (I did open the question expecting mathematical memory aids.)
Comment: Good call. Renamed and retagged.
Answer: Your observations are all correct.
Formal proofs for all of them are known, and not too hard. They start with the expansion
$$
n = a_k R^k  + a_{k-1} R^{k-1}+ \cdots + a_1 R + a_0
$$
and use the remainder of $R$ and its powers when you divide by the $d$ you are interested in.
One more trick: to test for divisibility by $11$ (in base $10$) look at the alternating sum of the digits. That generalizes.
There is no good test for divisibility by $7$ in base $10$.
Since $7 \times 11 \times 13 = 1001$ you can test for divisibility by any of these primes by testing the alternating sum of the blocks of three digits instead.
Check out https://en.wikipedia.org/wiki/Divisibility_rule and other links in a search for "divisibility tests".
Answer: Maybe these are too obvious to need pointing out, but I will anyway. But note that they're shortcuts with the limitations I mention.
Trick 1

If $n$ can be broken into two or more parts all divisible by $a$, then $n$ is automatically divisible by $a$.

Example: $6526$ is divisible by $13$, since $65$ and $26$  both are.
(But if $n$ can't be split in this way, the test doesn't rule out diviibility by $a$. )
Trick 2
In base $10$:

Split $n$ into two parts $A$ and $B$. Any number which isn't divisible by $2$ or $5$, and is a factor of only $A$ or only $B$, can't be a factor of $n$.

Example: $16956$ isn't divisible by $13$, because $169$ is but $56$ isn't.
Neither is it divisible by $7$, since $169$ isn't but $56$ is.
If you really insisted, you could also split it up into $16$ and $956$, and find that it's not divisible by $239$.
(Obviously there are other numbers which don't divide $n$: this trick only checks the ones which happen to be factors of $A$ or $B$.)
It's straightforward to extend Trick 2 by splitting $n$ into more sections and looking for numbers which divide all but one of the sections: for example splitting $142857$ as $14, 28, 57$ shows that it's not divisible by $7$.
Comment: This test may tell you when something is divisible but not reliably when it's not. For example, it doesn't help when you want to test $666$ for divisibility by $7$.
Comment: Agreed. I'll clarify that in the answer.
Comment: @EthanBolker I hope my answer spells out the limitations now!

Divisibility Tests in Various Bases


October CMS /backend not found 404 with Nginx

Question: I installed October CMS on my Nginx server, installed fine. Front end works with index.php and the style is correct. However backend does not. It just gives me a 404 page error. I've followed everything on the docs correctly, tried different sites-avaliable config files and they don't seem to work but give a 502, which I've checked the logs too and nothing in there.
This is my one3.com config file:
<code>server {
    listen  80;

    root /storage/www/one3community.com;
    index index.php index.html index.htm;
    listen  443;
    ssl     on;
    ssl_certificate         /ssl_keys/one3community.com/public.pem;
    ssl_certificate_key     /ssl_keys/one3community.com/private.pem;
    # Make site accessible from http://localhost/
    server_name www.one3community.com;

    location / {
        try_files $uri $uri.html $uri/ @extensionless-php;
        index index.php;
    }

    location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php5.5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
</code>
Answer: Converted default apache .htaccess file to Nginx. Loaded into sites-available .conf file restarted nginx. Now up and running.
** Had to replace every break with last in nginx file otherwise causes file download **
Comment: Could you please add the converted nginx file?


Finding a repetitive pattern in Python strings

Question: Let's suppose I have this string
s = '123123123'
I can notice the '123' sub-string is being repeated.
here = '1234'
The sub-string would be '1234' with no repetitions.
s = '11111'
The sub-string would be '1'
How can I get this with Python? Any hints?
Answer: <code>strings = ['123123123', '1234', '11111']
import re
pattern, result = re.compile(r'(.+?)\1+'), []
for item in strings:
    result.extend(pattern.findall(item) or [item])
print result
# ['123', '1234', '1']
</code>

Debuggex Demo
You can see the explanation for the RegEx here
Comment: but he wants 1234 to be detected for the middle string.
Comment: Can't you fix it in the regex?
Comment: @AaronHall That might break if the string is `111112111`?


Show that $\lim_{n \rightarrow \infty}\frac{a_n}{b_n}=1 \implies \lim_{n \rightarrow \infty}{(a_n-b_n)}=0$

Question: I have a question concerning a special limit
$$\lim_{n \rightarrow \infty}\frac{a_n}{b_n}=1$$
Can I always conclude from this that
$$\lim_{n \rightarrow \infty}{(a_n-b_n)}=0$$
Even if $a_n$ and $b_n$ are divergent? I tried to find some counter examples but I couldn't.
Comment: Add condition $b_n$ bounded.  No need for it to converge.
Answer: False. Take $a_n = 1+n$ and $b_n = n$. Then $\frac{a_n}{b_n} \to 1$ and $a_n -b_n \to 1 \neq 0$.
Comment: It seems to me that we must have $b_n \to b \in \Bbb R$. So we can do: $$a_n - b_n = b_n\left(\frac{a_n}{b_n}-1\right) \to b \cdot 0 = 0.$$If $b_n$ diverges then we'll have some $\infty \cdot 0$, and we can't conclude anything.
Comment: Are there conditions in which this might still be true? Even in the case of divergence?
Comment: If $b_n$ is convergent also $a_n$ must be convergent to have a limit of 1 for the ratio. I think something like order of divergence of $b_n$ less than the order of Convergence of $\frac{a_n}{b_n}-1$ could used.


Rushing yards vs passing yards vs receiving yards?

Question: I'm trying to understand football and some of its basic stats, and I'm not clear on the difference between these three.
Rushing yards:

A statistic in football that records the total number of yards gained by a single player as the result of a rushing play (or plays), in which the player carries the football (as opposed to receiving a pass).

Passing yards:

A statistic that measures the amount of yards gained by an offensive team on completed passes. Passing yards are measured for a given completion as the number of yards from the original line of scrimmage and the point that the player was tackled, forced out of bounds, or entered the end zone for a touchdown.

Receiving yards:

This is a statistic used in football defined as the number of yards gained by a receiver on a passing play. Included in the calculation of this statistic is the distance the ball was passed and any additional yardage the player gained after the reception.

What is a rushing play? How does a player get a ball other than by having it passed to them, excluding interceptions? If the ball always starts in a QB's hands, how can it possibly end up in anyone else's other than by a pass?
Honestly all three of these sound like "yards gained in a play by passing the ball to someone and having them run with it."
My understanding is that despite the phrasing in these definitions, these stats can apply to single players or to teams as a whole, but even so I don't see the distinction between them. They all seem to measure yards gained by a player who received the ball and ran with it.
Comment: Yeah, that's just a rubbish definition. Passing yards certainly is counted for individual players - see e.g. [here](http://www.espn.co.uk/nfl/boxscore?gameId=400874608) where passing yards are counted for both Joe Flacco and Ryan Mallett, rather than just "Ravens" as a whole.
Comment: What source are you using for your definitions? My instant answer is "get better definitions", but that will depend a bit on whether they're any sort of official definitions or not.
Comment: Sportingcharts.com, and I'm about to edit the question to include receiving yards. [Here](https://www.sportingcharts.com/dictionary/nfl/passing-yards.aspx) and [here](https://www.sportingcharts.com/dictionary/nfl/rushing-yards.aspx) are the definitions for the current two. To my astonishment I couldn't really find (from cursory searching) plentiful sources for explanation. I thought, given how popular this is, there would be many results, but there are not.
Answer: That is just a bad definition of "passing yards" - as can be seen from (for example) this boxscore, passing yards are most definitely counted for individual players (Flacco and Mallett for the Ravens in this case), rather than just for the team as a whole.
As you've noted, finding a formal definition of this is a bit tricky. The best I can do at the moment is the "Passing & Sacks (Offensive)" section of the NFL Guide for Statisticians; this has multiple references to "the passer" being credited for pass attempts, rather than "the team" or any other language.
The other half of your question is somewhat easier to answer:

How does a player get a ball other than by having it passed to them, excluding interceptions?

In this context, a pass refers solely to a forward pass (with all the restrictions that go with that - most notably, it must be from behind the line of scrimmage). Handoffs, backward passes (including laterals) and the snap from the center are not counted as a pass. One very important difference here is what happens if the ball is not caught cleanly by the recipient - on a forward pass, it is an incomplete pass and the play is dead, but on a handoff, backward pass or snap, the ball is live and can be recovered by either side.
Answer: Passing/Receving = throwing the ball forward in any way behind the line of scrimmage.   This means underhand side arm or whatever and can be as little as an inch forward.   An example is that some jet sweeps are taken where the receiver gets the ball from a QB in shotgun/pistol and just pops the ball forward a couple inches.   This is a pass.   It is also passing yards if a receiver catches a pass and hands it to another player.   So if the jet sweep WR gets the ball popped to them and runs 9 yards that is 9 receiving yards and then if they lateral it backwards to another runner for 10 yards that is an additional 10 receiving yards.
Rushing = throwing the ball sideways (without an initial forward pass), backwards or directly handing the ball to someone.


Inclusion is cofibration iff $(A\times I) \cup (X\times \{0\})$ is a retract of $X\times I$

Question: Let $A\subset X$ be a subspace. Then the inclusion $i:A\to X$ is a cofibration iff $(A\times I) \cup (X\times \{0\})$ is a retract of $X\times I$.
I've proved the "$\implies$" direction.
"$\impliedby$": Suppose that $H: X\times I \to Y =  (A\times I) \cup (X\times \{0\}$ is a retraction.
We want to show that $i:A\to X$ is a cofibration. It suffices to show that $i$ has the HEP w.r.t. the mapping cylinder $S(i) = \left( A\times I \sqcup X \right)/(a,0)\sim i(a)$. But $S(i)$ is precisely the space $Y$. So we want to verify that $i$ has the HEP w.r.t. $Y$.
Let $f:X\to Y$ be some map and $h:A\times I \to Y$ some homotopy such that $h_0 = f \circ i$. Our retraction $H$ might be a good candidate to fulfil the required conditions, namely that $H(x,0) = f(x)$ and $H(a,t) = h(a,t)$. Since $H$ restricts to the identity on $Y$, we require that $f(x) = (x,0)$ and $h(a,t) = (a,t)$. I don't see why this requirement would be fulfilled.
What else can we do?
Answer: Actually it suffices when the canonical maps $j_X:X\times\{0\}\hookrightarrow M_i$ and $\bar i:A\times I\to M_i$ extend to a map $r:X\times I\to M_i$ with $r(i(a),t)=(a,t)$ and $r(x,0)=x$. Because such $r$ would be  retraction (left-inverse) to the map $s:M_i\to X\times I$ sending $x$ to $(x,0)$ and $(a,t)$ to $(i(a),t)$. (Conversely, a retraction $r$ for $s$ would be an extension for the maps $j_X$ and $\bar i$). Then, if $f:X\times\{0\}\to Z$ and $G:A\times I\to Z$ are maps to any space $Z$ satisfying $G(a,0)=f(a,0)$, this induces a unique map $\tilde G:M_i\to Z$ such that $\tilde Gj_X=f$ and $\tilde G\bar i=G$. If we compose this to $H=\tilde Gr:X\times I\to Z$, we have $H(x,0)=f$ and $H(a,t)=G(a,t)$.
The problem is rather in the ambiguity regarding the topology on $M_i$. Since $r$ restricts to a continuous map $X\times\{0\}\cup A\times I\to M_i$ which is $j_X$ on $X\times\{0\}$ and $\bar i$ on $A\times I$, that means that the union of $j_X$ and $\bar i$ is continuous. This is not always the case, for example when $i$ is the inclusion $(0,1]\hookrightarrow[0,1]$, as the topology on the mapping cylinder of $i$ is in that case strictly finer than the subspace topology on $I\times\{0\}\cup(0,1]\times I$. However, if this subspace is a retract of $X\times I$, then one can show that both maps always combine to a continuous map. This is done in the appendix of Hatcher's Algebraic Topology (the proof first appeared 1968 as Lemma 3 in Strøm's Note on Cofibrations II).
Comment: Ok, that makes more sense (and is easier). Thanks


Views Geolocation field proximity: How to alter views field setting

Question: I'm using a Geolocation field in views to order results by distance. The module provides a special views proximity plugin/field, which can be used in the "sort" section of the view. This plugin/field has a "proximity setting" (lat/long) to define the center point for distance calculation. I got this far in views UI and this all works.
I now need to programmatically change that center point based on a custom logic derived from the current user, but I don't know which views hook to use to alter this field setting.
Tried, didn't work:
function MYMODULE_views_pre_view($view, $display_id, &$args) {
  //my field's machine name is "field_geo"
  $geoField = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofield) is empty

  //suffix "_proximity" seems to be added by geolocation module, but does not work either
  $geoFieldProximity = $view->display_handler->getHandler('field', 'field_geo_proximity');
  //print_r($geofieldProximity) is empty
}

I've got two questions:

Is pre_view the correct hook to alter the field setting? (If not, which hook should I use instead?)
How to I get/set those field settings?
I thought I need to use $view->display_handler->getHandler() but didn't get any results.
Answer: Digging through the exported views.yml config helped me to get on the right track:
function MYMODULE_views_pre_view($view, $display_id, &$args) {

  if ($view->id() == 'WHATEVER' and $display_id == 'MY_DISPLAY') {
    $allFields = $view->display_handler->getOption('fields');

    $user = _MY_BUSINESS_LOGIC();
    if (!$user->get('field_geo')->isEmpty()) {
      $allFields ['field_geo_proximity']['proximity_lat'] = $user->get('field_geo')->lat;
      $allFields ['field_geo_proximity']['proximity_lng'] = $user->get('field_geo')->lng;
      $view->display_handler->overrideOption('fields', $allFields);
    }
  }
}


LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void) for C program

Question: Main Error:
Error   LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
I have read so many different ones and tried it all with no luck. Could someone help please? I am not a dev, so any help would be really appreciated.
I have tried the linker resolution and several others.
<code>#include <stdio.h>
#include <string.h>

void main()
{
    printf("======================================================================");
    printf("\n====================================================================");

    char input[20];
    int i,j;

    puts("\n\nEnter the sentence to be reversed::\n");
    gets(input);
    printf("Input   addr: %p\n", input);
    printf("\nThe reversed sentence is:: \n\n");
    strrev(input);

    for(i=0; input[i]!='\0'; i++)
    {
       if(input[i+1]==' ' || input[i+1]==NULL)
       {
           for(j=i; j>=0 && input[j]!=' '; j--)
            printf("%c",input[j]);
       }
       else
       continue;
       printf(" ");
    }
    getch();
}
</code>
Comment: Did you try this: https://stackoverflow.com/a/46085227/3003365?
Comment: are you compiling it as C or C++? From the error it looks like it might be C++, although the code is plain C. Usually `main` is expected to return `int`, not `void`. You may try to change that and see if that makes a difference. Add `return 0;` if you change the return type.
Comment: Rather, `int main(void)` or `int main(int, char**)` (that is allowed in both C and C++, with the same meaning). Remember that empty parentheses in C don't mean what one may expect.
Comment: Does this answer your question? [Error LNK2019 unresolved external symbol \_main referenced in function "int \_\_cdecl invoke\_main(void)" (?invoke\_main@@YAHXZ)](https://stackoverflow.com/questions/33400777/error-lnk2019-unresolved-external-symbol-main-referenced-in-function-int-cde)
Answer: Thank you for the replies. So the first problem was in my source file i had a .cpp file rather than a .c file. Then I found that I wasn't exactly pointing to the entry point of my program properly.
So this is now fixed. Thank you to all that replied.


Onde usar acumuladores em um algoritmo de avaliação de pares e ímpares?

Question: Onde devo encaixar os acumuladores desse código que eu escrevi por enquanto?
 #include <stdio.h>

         int main()
         {

         int N;
         int somapar;
         int somaimpar;

         do{
         printf("\n Digite um número qualquer: ");
         scanf("%d", &N);

         if (N % 2 == 0){
         printf("\n Número escolhido é par!");
         }

         else {
         printf("\n Número escolhido é ímpar");
         }
         }while (N >= 0);

         printf("\n");

         return 0;
         }

O enunciado do algoritmo é esse:

Escreva um algoritmo para mostrar na tela se cada número N, digitado pelo usuário é par ou ímpar. O algoritmo também deverá mostrar na tela a soma de todos os números pares, a soma de todos os números ímpares, a porcentagem de números pares e a porcentagem de números ímpares digitados. O algoritmo deverá encerrar sua execução caso o usuário digite um número menor que zero.
Comment: Se você tem outra dúvida, faça uma nova pergunta, não altere o que já foi respondido.
Answer: Cada um deles deve ser colocado dentro do if afinal é nele que se decide se é par ou ímpar. Não esqueça de zerar a variável na inicialização para não pegar sujeira da memória.
#include <stdio.h>

int main() {
    int N;
    int somapar = 0;
    int somaimpar = 0;
    do {
        printf("\n Digite um número qualquer: ");
        scanf("%d", &N);
        if (N % 2 == 0) {
            printf("\n Número escolhido é par!");
            somapar += N;
        } else {
            printf("\n Número escolhido é ímpar");
            somaimpar += N;
        }
    } while (N >= 0);
    printf("\nTotal de ímpares é %d e total de pares é %d\n", somaimpar, somapar);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
A porcentagem e outras coisas ficam por sua conta.
Comment: amigo ainda estou com dificuldade.
Answer: COLOQUEI UM EXEMPLO PARA TE AJUDAR COM A MEDIA E SOMA,A PORCENTAGEM É COM VOCÊ.
#include <stdio.h>

int main() {
    // INICIALIZANDO VARIAVEIS COM 0.
    int N;
    int par = 0;
    int impar = 0;
    int somapar=0;
    int mediapar=0;
    int somaimpar=0;
    int mediaimpar = 0;

    do {
        printf("\n Digite um número qualquer: ");
        scanf("%d", &N);

        // SE O NUMERO FOR PAR ELE ENTRA AQUI
        if (N % 2 == 0) {
            printf("Número escolhido é par!\n");
            par = par + 1;
            somapar = somapar + N;
            mediapar = somapar / par;
        }

        // SE NÃO ENTRA AQUI
        else{
            printf("\Número escolhido é ímpar!\n");
            impar = impar + 1;
            somaimpar = somaimpar + N;
            mediaimpar = somaimpar / impar;
        }
    } while (N > 0);

    // EXIBINDO RESULTADO NA TELA
    printf("------------------RESULTADO-------------------");
    printf("\nO Total de ímpares é %d e o total de pares é %d.", impar, par);
    printf("\nA soma dos numeros pares é: %d.", somapar);
    printf("\nA média dos numeros pares é: %d.", mediapar);
    printf("\nA soma dos numeros impares é: %d.", somaimpar);
    printf("\nA média dos numeros impares é: %d.", mediaimpar);
}

PARA CURIOSIDADE: Por que geralmente se declara uma variável com
valor padrão?


What is the maximum entropy probability density function for a positive continuous variable of given mean and standard deviation?

Question: What is the maximum entropy distribution for a positive continuous variable, given its first and second moments?
For example, a Gaussian distribution is the maximum entropy distribution for an unbounded variable, given its mean and standard deviation, and a Gamma distribution is the maximum entropy distribution for a positive variable, given its mean value and the mean value of its logarithm.
Answer: One may simply use the theorem of Boltzmann's that is in the very Wikipedia article you point to.
Note that specifying the mean and variance is equivalent to specifying the first two raw moments - each determines the other (it's not actually necessary to invoke this, since we may apply the theorem directly to the mean and variance, it's just a little simpler this way).
The theorem then establishes that the density must be of the form:
$$f(x)=c \exp\left(\lambda_1 x + \lambda_2 x^2 \right)\quad \mbox{ for all } x \geq 0$$
Integrability over the positive real line will restrict $\lambda_2$ to be $\leq 0$, and I think places some restrictions on the relationships between the $\lambda$s (which will presumably be satisfied automatically when starting from the specified mean and variance rather than the raw moments).
To my surprise (since I wouldn't have expected it when I started this answer), this appears to leave us with a truncated normal distribution.
As it happens, I don't think I've used this theorem before, so criticisms or helpful suggestions on anything I haven't considered or have left out would be welcome.
Comment: For some reason the uniform base measure and resulting truncated normal distribution do not fully convince me: As Fred Schoen stresses, to find the maximum-(relative-)entropy in the continuous case we need a base measure or reference probability distribution. Since the continuous variable $x$ in question is positive, it could be a scale variable, and a base measure proportional to $1/x$ then recommends itself for various reasons (e.g. group invariance; see Jaynes's book or Jeffreys's).
Comment: With this base measure the resulting distribution is proportional to
$$
\frac{1}{x}\exp(-\alpha x- \beta x^2)
$$
but unfortunately it's non-normalizable (it could still be used as an improper prior, though).

Given the positiveness of the variable in question it may be worth considering whether the moments of its logarithm may make more sense as information carriers and maximum-entropy constraints. They would lead to gamma-like maximum-entropy distributions.
Comment: +1 Thanks. Seems alright. When I read the Wikipedia article, I seem to have missed the fact that Boltzmann theorem applies for all closed intervals. I had assumed it applied only to variables going from $-\infty$ to $\infty$.
Answer: I want to make @Glen_b's answer more explicit, here is an extra answer just because it wouldn't fit as a comment.
The formalism etc. is well explained in Chapter 11 and 12 of Jaynes' book.
Taking the uniform distribution as the base measure, the general solution, as @Glen_b already said, is a Gaussian
$$
f(x) \propto \mathcal{N}(x | -1/2 \lambda_1/\lambda_2, -1/(2\lambda_2))
$$
For the unbounded variable, you can explicitly solve for the Lagrange multipliers $\lambda_1$ and $\lambda_2$ in terms of the constraint values ($a_1, a_2$ in the Wikipedia article). With $a_1=\mu, a_2=\mu^2 + \sigma^2$, you then get $\lambda_1=\mu/\sigma^2, \lambda_2=-0.5 \sigma^2$, so the standard Gaussian $\mathcal{N}(x|\mu, \sigma^2)$.
For the bounded variable $x>x_{min}$, I (and mathematica) cannot solve for $\lambda_{1,2}$ explicitly anymore because of the error function term that appears when computing the partition function ($1/c$ in wikipedia). This means that that the $\mu$ and $\sigma^2$ parameters of the truncated Gaussian are not the mean and variance of the continuous variable you started with. It can even happen that for $x_{min}=0$, the mode of the Gaussian is negative! Of course the numbers all agree again when you take  $x_{min} \to -\infty$.
If you have concrete values for $a_1, a_2$, you can still solve for $\lambda_{1,2}$ numerically and plug in the solutions into the general equation and you are done! The values of $\lambda_{1,2}$ from the unbounded case may be a good starting point for the numerical solver.
This question is a duplicate of https://math.stackexchange.com/questions/598608/what-is-the-maximum-entropy-distribution-for-a-continuous-random-variable-on-0


Autoit dead loop problem

Question: In SSMS (SQL Server Management Studio), you have to middle-click the tab or press Ctrl+F4 to close the current editor tab. I want to use Autoit to make a shortcut Ctrl+w do the same thing. But I have problem with it. The following is the code. What I thought is, when the user press Ctrl+w, check if the user is in SSMS, if so, send Ctrl+F4 to close the current tab, if not, send Ctrl+w to let it go as normal. But the point is, if you send Ctrl+w, it will be captured again by Autoit, so dead loop occurs. I can't find a way to solve this problem. Anyone can help me with it?
Thanks.
HotKeySet("^w", "close_ssms_editor")

While 1
    Sleep(200)
WEnd

; using Ctrl + w to close
; * editors in SSMS
; * editors in SSMS through Royal TS
Func close_ssms_editor()
    $window_class_name = get_window_class_name(WinGetHandle(""))
    If $window_class_name = "wndclass_desked_gsk" or $window_class_name = "WindowsForms10.Window.8.app.0.218f99c" Then
        Send("^{F4}")
    Else
        Send("^w")
    EndIf
EndFunc

Func get_window_class_name($nCtrl)
    If Not IsHWnd($nCtrl) then $nCtrl = HWnd($nCtrl)
    Local $struct = DllStructCreate("char[128]"),$classname = 0
    $ret = DllCall("user32.dll","int","GetClassName","hwnd",$nCtrl,"ptr",DllStructGetPtr($struct),"int",DllStructGetSize($struct))
    If IsArray($ret) Then
        $classname = DllStructGetData($struct,1)
        While (StringIsDigit(StringRight($classname,1)))
            $classname = StringTrimRight($classname,1)
        WEnd
    EndIf
    $struct =0
    Return $classname
EndFunc

Answer: I found the solution.
; using Ctrl + w to close
; * editor in SSMS
; * editor in SSMS through Royal TS
Func close_ssms_editor()
    $window_class_name = get_window_class_name(WinGetHandle(""))
    If $window_class_name = "wndclass_desked_gsk" or $window_class_name = "WindowsForms10.Window.8.app.0.218f99c" Then
        Send("^{F4}")
    Else
        HotKeySet("^w")
        Send("^w")
        HotKeySet("^w", "close_ssms_editor")
    EndIf
EndFunc

Autoit dead loop problem


How to convert the currency AED to USD then pass it to Paypal

Question: Can anyone provide me a solution .How to convert the currency AED to USD before pass it to Paypal .
Answer: You can simply use Google
Try
var_dump(simpleConvert("AED","USD",1));

Output
array
  '1.000000' => string '0.272257' (length=8)

Function Used
function simpleConvert($from,$to,$amount)
{
    $content = file_get_contents('https://www.google.com/finance/converter?a='.$amount.'&from='.$from.'&to='.$to);

     $doc = new DOMDocument;
     @$doc->loadHTML($content);
     $xpath = new DOMXpath($doc);

     $result = $xpath->query('//*[@id="currency_converter_result"]/span')->item(0)->nodeValue;
     return $result;
}

Comment: Apparantly, the URL has changed from `https://www.google.com` to `https://finance.google.com`.
Answer: You can simple add this code.
<?php

function convertCurrency($amount, $from, $to){
$data = file_get_contents("https://www.google.com/finance/converter?   a=$amount&from=$from&to=$to");
preg_match("/(.*)<\/span>/",$data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return number_format(round($converted, 3),2);
}
echo convertCurrency("10", "AED", "USD");

?>


Python transform list of dictionaries into another list of dictionaries

Question: I have a list of dictionaries in python. Here is a contrieved example with hair color and race.
some_list = [
        {'blond': 3, 'race': 'WHITE'},
        {'black': 4, 'race': 'WHITE'},
        {'light brown': 6, 'race': 'WHITE'},
        {'black': 2, 'race': 'AFRICAN_AMERICAN'},
        {'blond': 1, 'race': 'AFRICAN_AMERICAN'},
        {'dark brown': 1, 'race': 'AFRICAN_AMERICAN'}
]

The hair color is one of the keys and the value for the hair color is the count of how many people have that hair color for the given race. I do not know how many hair colors there are nor do I know how many races there are. I want to transform this list to include counts of ALL hair colors for ALL races such that the result would include 0 counts for colors not listed for a given race:
some_list = [
        {'blond': 3, 'race': 'WHITE'},
        {'black': 4, 'race': 'WHITE'},
        {'light brown': 6, 'race': 'WHITE'},
        {'dark brown': 0, 'race': 'WHITE'},
        {'black': 2, 'race': 'AFRICAN_AMERICAN'},
        {'blond': 1, 'race': 'AFRICAN_AMERICAN'},
        {'dark brown': 1, 'race': 'AFRICAN_AMERICAN'},
        {'light brown': 0, 'race': 'AFRICAN_AMERICAN'}
]

For the life of me I can't think of a simple 'python' way to do this easily. Surely there is a trick to this? Anyone know a succient way to solve this?
Comment: Show us what you tried. I also think that the data structure you chose is a bit weird.
Comment: You can iterate, and use `set(..)` to find unique colors/races, then use `itertools.product(..)` to find all combinations. Fill zeros where you dont have entry in `some_list`. Tell us where you are stuck.
Comment: Thats where I'm stuck...I have a unique list already...as shown in the first code snippet...but I don't know a good way to iterate through and fill in the missing hair colors for given race. How does itertools.product(..) help?
Answer: If I'm understanding your question correctly, and you are able to use external libraries, you could accomplish this with pandas:
import pandas as pd

df = pd.DataFrame(some_list, index=None)

df = df.groupby(by='race').count().transpose()

for col in df.columns:
    rw = df.loc[df[col] == 0]
    dic = {rw.index[0]: 0, 'race': col}
    some_list.append(dic)

# output:
# some_list = [
#     {'blond': 3, 'race': 'WHITE'},
#     {'black': 4, 'race': 'WHITE'},
#     {'light brown': 6, 'race': 'WHITE'},
#     {'black': 2, 'race': 'AFRICAN_AMERICAN'},
#     {'blond': 1, 'race': 'AFRICAN_AMERICAN'},
#     {'dark brown': 1, 'race': 'AFRICAN_AMERICAN'},
#     {'light brown': 0, 'race': 'AFRICAN_AMERICAN'},
#     {'dark brown': 0, 'race': 'WHITE'}
# ]


How to train and fine-tune fully unsupervised deep neural networks?

Question: In scenario 1, I had a multi-layer sparse autoencoder that tries to reproduce my input, so all my layers are trained together with random-initiated weights. Without a supervised layer, on my data this didn't learn any relevant information (the code works fine, verified as I've already used it in many other deep neural network problems)
In scenario 2, I simply train multiple auto-encoders in a greedy layer-wise training similar to that of deep learning (but without a supervised step in the end), each layer on the output of the hidden layer of the previous autoencoder. They'll now learn some patterns (as I see from the visualized weights) separately, but not awesome, as I'd expect it from single layer AEs.
So I've decided to try if now the pretrained layers connected into 1 multi-layer AE could perform better than the random-initialized version. As you see this is same as the idea of the fine-tuning step in deep neural networks.
But during my fine-tuning, instead of improvement, the neurons of all the layers seem to quickly converge towards an all-the-same pattern and end up learning nothing.
Question: What's the best configuration to train a fully unsupervised multi-layer reconstructive neural network? Layer-wise first and then some sort of fine tuning? Why is my configuration not working?
Answer: After some tests I've came up with a method that seems to give very good results, and as you'd expect from a 'fine-tuning' it improves the performance of all the layers:
Just like normally, during the greedy layer-wise learning phase, each new autoencoder tries to reconstruct the activations of the previous autoencoder's hidden layer. However, the last autoencoder (that will be the last layer of our multi-layer autoencoder during fine-tuning) is different, this one will use the activations of the previous layer and tries to reconstruct the 'global' input (ie the original input that was fed to the first layer).
This way when I connect all the layers and train them together, the multi-layer autoencoder actually reconstructs the original image in the final output. I found a huge improvement in the features learned, even without a supervised step.
I don't know if this is supposed to somehow correspond with standard implementations but I haven't found this trick anywhere before.
Comment: What do you mean by this? Could you please explain it more. I have the problem with the features which are extracted and am using the trainAutoencoder toolbox of Matlab and do not how to implement your idea. Thanks.
Comment: @Hamed look up Andrew Ng's tutorials they'll give you a great insight


PXE boot not happening - Please advise

Question: Hi we are trying to PXE boot but it says ---->
PXE-E61 : Media test failure , check cable
PXE-M0F : Exiting Broadcom PXE ROM .
What should we check for ?
Thanks
Nishant
Comment: The cable was not connected to the correct NIC it was given to NIC 2 instaed of NIC 1 . Thanks for the pointers .
Comment: So you mean it works now? In this case, can you close the question?
Answer: "Media test failure", as emphasized by "check cable" means that there is no link detected on the local NIC.
Do you have the link led on for this machine ? If so, you might assume a buggy PXE/bios rom. If not, make a physical fix.
Answer: Is the cable okay?
Answer: I guess you're trying to netboot a netbook via Wi-Fi — forget it!
Generally, this means PXE BootLoader can use no network connection. Check your cable.

PXE boot not happening - Please advise


file_get_contents() erro!

Question: Possuo o formulário html:

        <form method="POST" action="Controller/jsonTeste.php">
            CEP: <input type="text" name="cep" placeholder="Insira o cep" required/>
            <input type="submit" />

        </form>

E o arquivo php:
<?php
$formCEP = $_POST['cep'];
$formCEP = preg_replace("/[^0-9]/", "", $formCEP);
$url = file_get_contents('http://viacep.com.br/ws/$formCEP/json/');
?>

Ao passar a variável $formCEP para a ULR: http://viacep.com.br/ws/$formCEP/json/, recebo um "Warning" como reposta, mas ao digitar um CEP valido para a URL, é aceito como válido. Como resolver?
Comment: Qual warning você recebe?
Comment: Acho que o problema é somente o uso da variavel $formCEP
Concatena ela na URL

$url = file_get_contents('http://viacep.com.br/ws/' . $formCEP . '/json/');
Answer: Você não está substituindo o $formCEP na sua String. Quando usa strings de aspas únicas, a interpolação não funciona. Para resolver, utilize aspas duplas.
<?php

$formCEP = "15047200";
$formCEP = preg_replace("/[^0-9]/", "", $formCEP);

echo 'http://v...content-available-to-author-only...m.br/ws/$formCEP/json/';
echo "\n";
echo "http://v...content-available-to-author-only...m.br/ws/$formCEP/json/";

Portanto, para funcionar, altere
$url = file_get_contents('http://viacep.com.br/ws/$formCEP/json/');

para
$url = file_get_contents("http://viacep.com.br/ws/$formCEP/json/");

Código funcionando: https://ideone.com/Pkz2HC
Comment: Obrigado! Após a alteração, funcionou perfeitamente.

file_get_contents() erro!