text:
Q: How to remove extra space from end of the line before newline in python? I'm quite new to python. I have a program which reads an input file with different characters and then writes all unique characters from that file into an output file with a single space between each of them. The problem is that after the last character there is one extra space (before the newline). How can I remove it?
My code:
import sys
inputName = sys.argv[1]
outputName = sys.argv[2]

infile = open(inputName,"r",encoding="utf-8")
outfile = open(outputName,"w",encoding="utf-8")
result = []
for line in infile:

   for c in line:
       if c not in result:
           result.append(c)
           outfile.write(c.strip())

          if(c == ' '):
             pass
          else:
             outfile.write(' ')

outfile.write('\n')

A: With the line outfile.write(' '), you write a space after each character (unless the character is a space). So you'll have to avoid writing the last space. Now, you can't tell whether any given character is the last one until you're done reading, so it's not like you can just put in an if statement to test that, but there are a few ways to get around that:

*

*Write the space before the character c instead of after it. That way the space you have to skip is the one before the first character, and that you definitely can identify with an if statement and a boolean variable. If you do this, make sure to check that you get the right result if the first or second c is itself a space.

*Alternatively, you can avoid writing anything until the very end. Just save up all the characters you see - you already do this in the list result - and write them all in one go. You can use
' '.join(strings)

to join together a list of strings (in this case, your characters) with spaces between them, and this will automatically omit a trailing space.

A: Why are you adding that if block on the end?
Your program is adding the extra space on the end.
import sys
inputName = sys.argv[1]
outputName = sys.argv[2]

infile = open(inputName,"r",encoding="utf-8")
outfile = open(outputName,"w",encoding="utf-8")
result = []
for line in infile:
   charno = 0
   for c in line:
       if c not in result:
           result.append(c)
           outfile.write(c.strip())

          charno += 1
          if (c == ' '):
              pass
          elif charno => len(line):
              pass
          else:
              outfile.write(' ')

outfile.write('\n')


text:
Q: angular google map api doesn't work I created directive for google location autocomplete input filed, I include the google api.js file in the index page, the weird thing is if I put the directive in the index.page it works, but if I put it in the other pages, it doesn't work.
directive:
angular.module('ecom').controller('googleMapsCtr', ['$scope',
    function($scope) {
        console.log($scope.locationgoogle);
    }])
.directive('smartgooglemaps', function() {
    return {
                    restrict:'E',
                    replace:false,
                    // transclude:true,
                    controller:'googleMapsCtr',
                    template: '<input id="google_places_ac" name="google_places_ac" type="text" class="input-block-level" ng-model="locationgoogle"/>',
                    link: function($scope, elm, attrs){
                        var autocomplete = new google.maps.places.Autocomplete($("#google_places_ac")[0], {});

                    }
                }
})

I put my directive in the accordion directive which is included by :

what should I do to make my directive work?

redpajama_set_name: RedPajamaStackExchange


text:
Q: vtkResliceImageViewer get bounds image in view Situation:
I'm using vtkresliceimageviewer to display the three MPR views, based on this example.

So I can rotate the cursors to generate a new view on all three screens.
Question:
I want to know the bounds of my image on the viewer, even after rotating some of the cursors.
obs
I tried to get the values from the imageActor and ask for my renderer positions, but this works only when I have no interaction from the other cursors.
Example for axial:
void UpdatePointWordToViewer(vtkRenderer* rend, double p[4])
{
    rend->SetWorldPoint(p);
    rend->WorldToDisplay();
    rend->GetDisplayPoint(p);
}

void UpdateBoxAxial()
{
    auto bounds = pMPR->GetViewer(2)->GetImageActor()->GetBounds();
    auto ren = pMPR->GetViewer(2)->GetRenderer();
    auto size = pMPR->GetViewer(2)->GetInteractor()->GetSize();

    double pIni1[]{ 0,0,0,1 };
    double pIni2[]{ 0,0,0,1 };
    double pIni3[]{ 0,0,0,1 };
    double pIni4[]{ 0,0,0,1 };
    double pConvert1[]{ 0,0,0 };
    double pConvert2[]{ 0,0,0 };

    //check the bounds
    pIni1[0] = bounds[0];
    pIni1[1] = bounds[3];
    pIni1[2] = bounds[4];

    pIni2[0] = bounds[1];
    pIni2[1] = bounds[3];
    pIni2[2] = bounds[4];

    pIni3[0] = bounds[0];
    pIni3[1] = bounds[2];
    pIni3[2] = bounds[4];

    pIni4[0] = bounds[1];
    pIni4[1] = bounds[2];
    pIni4[2] = bounds[4];

    //convert the points for viewer coordinates
    UpdatePointWordToViewer(ren, pIni1);
    UpdatePointWordToViewer(ren, pIni2);
    UpdatePointWordToViewer(ren, pIni3);
    UpdatePointWordToViewer(ren, pIni4);

    //P1
    if (pIni1[0] < pIni3[0])
        pConvert1[0] = pIni1[0];
    else
        pConvert1[0] = pIni3[0];

    if (pIni3[1] < pIni4[1])
        pConvert1[1] = pIni3[1];
    else
        pConvert1[1] = pIni4[1];

    //P2
    if (pIni2[0] > pIni4[0])
        pConvert2[0] = pIni2[0];
    else
        pConvert2[0] = pIni4[0];

    if (pIni1[1] > pIni2[1])
        pConvert2[1] = pIni1[1];
    else
        pConvert2[1] = pIni2[1];
}

So I know the minimum point (Left - Down) and the maximum point (Right - Top)


text:
Q: How to connect to Amazon EC2 instance? After I created a ubuntu VM(Amazon EC2 instance), I see below entry in "view instances":
I see public dns as Public DNS: ec2-13-58-17-118.us-east-2.compute.amazonaws.com
Instance:  i-08c551d9713dfcd06 (ubuntu_VM)
Security groups: sg_ubuntu. view inbound rules. view outbound rules

To connect to this Amazon EC2 instance(ubuntu VM), am using below syntax from my ubuntu laptop:
ssh -i "ubuntu_key.pem" ubuntu@ec2-13-58-17-118.us-east-2.compute.amazonaws.com
and it works, but I do not know the reason, for its working
I understand that ec2-13-58-17-118.us-east-2.compute.amazonaws.com is domain name

1) What is ubuntu in ubuntu@ec2-13-58-17-118.us-east-2.compute.amazonaws.com?
2) Why Amazon EC2 instance creation process does not ask for assigning hostname to the EC2 instance, on aws website? after sshing, I see some dynamic hostname assigned(ip-172-31-30-203) which is not good for me...
3) What is security group? amidst creation of EC2 instance...

A: 1) ubuntu is the username of that particular ec2 instance. In this case, since your instance is using Ubuntu, then by default you get that username. If you had created an instance using Amazon Linux 2, it would of have been ec2-user. You can check more here.
If you intend to change this username, you can in fact. Just like you would in any Linux OS, except for a few extra steps you need to follow in order to connect using SSH with this new username.
2) Each time you stop and restart your Amazon EC2 instance (unless you are using an Elastic IP address), the public IPv4 address changes, and so does your public DNS name, system hostname, and shell prompt. This is found in the user guide. If you want to have a static IP, you must create an Elastic IP address, although, it has a cost.
3) The security group, is a set of rules of how to access (inbound rules) your instance and what can your server reach (outbound rules). By default, if not mistaken, in your inbound rules, you should only have your SSH connection available.

A: *

*ubuntu is the username on the server

*I'm not sure why this is, but you are able to change it using the command sudo hostnamectl set-hostname your-desired-hostname. You can read more in the AWS UserGuide

*Security groups are firewall rules that you can use to protect your VM from the outside world. You can block access to specific ports, only allow access to specific ports from an IP address or IP range. For example, you can use it to restrict access to SSH only to your office IP address to prevent anyone else from logging into your EC2 instance.


text:
Q: Enable/disable an activity programmatically I have an activity in in my app which I have kept as
android:enabled="false"

now I want that when a button is clicked it should get changer to
android:enabled="true"

How can I do this?

A: Here's a nice way to do it:
  public static void setActivityEnabled(Context context,final Class<? extends Activity> activityClass,final boolean enable)
    {
    final PackageManager pm=context.getPackageManager();
    final int enableFlag=enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
    pm.setComponentEnabledSetting(new ComponentName(context,activityClass),enableFlag,PackageManager.DONT_KILL_APP);
    }

example usage:
setActivityEnabled(this,SomeActivity.class,false);

A: Use PackageManager and setComponentEnabledSetting() to enable or disable any component within your app: activity, service, etc.

A: Here's an example how to enable/disable an Activity:
    PackageManager pm = getPackageManager();
    pm.setComponentEnabledSetting(new ComponentName(this, com.packagename.MyActivity.class),
                                  PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

    pm.setComponentEnabledSetting(new ComponentName(this, com.packagename.MyActivity.class),
                                  PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

A: In case you're using productFlavors, you can have separate AndroidManifest files for each flavor. In those you can easily override properties from the main Manifest file. When building a particular flavor manifest merger merges the Manifest based on the selected flavor.
In the flavor's manifest where you want to disable a particular activit you can do it like this
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:enabled="false"
        tools:node="remove">
    </activity>


text:
Q: Return response after async await function in nodejs I am develop a small app, I have a problem. After I await to run query from Mongodb then I use map method to do some task then I return my response, but the response always return promise and I have not necessary data. Here my code
    exports.getListChallenges = async function (req, res) {
    var status_code = Consts.STATUS_CODE.ERROR.UNKOWN_ERROR;
    try {
        var page_number = parseInt(req.params.page_number);
        var page_size = parseInt(req.params.page_size);
        var challenges = await Challenge.find()
            .skip(page_size * (page_number - 1))
            .limit(page_size);
        status_code = Consts.STATUS_CODE.SUCCESS.DATA_FOUND;

        challenges = challenges.map(async function (o) {
            var challenger_club = await Club.findById(o.challenger_club_id);
            var challege = {
                challenge: o,
                challenger_club_name: challenger_club.club_name,
                challenger_club_avatar: challenger_club.avatar
            };
            return challege;
        });

        res.json({
            "status": true,
            "message": "Challenges found !",
            "status_code": status_code,
            "challenges": challenges
        });

    } catch (error) {
        status_code = Consts.STATUS_CODE.ERROR.UNKOWN_ERROR;
        res.json({
            "status": false,
            "status_code": status_code,
            "error": error
        })
    }
}

the "challenges" in response always empty , how can I solve it ? thank !

A: You're very close - you've mapped each item in the initial challenges to a Promise that resolves to the challenge object you want, now you need to call Promise.all on that array of Promises to get the values they resolve to. To keep the code clear, it would be best not to reassign challenges unless it's necessary - call the new array of Promises something else, like challengePromises:
exports.getListChallenges = async function(req, res) {
  var status_code = Consts.STATUS_CODE.ERROR.UNKOWN_ERROR;
  try {
    var page_number = parseInt(req.params.page_number);
    var page_size = parseInt(req.params.page_size);
    var challenges = await Challenge.find()
      .skip(page_size * (page_number - 1))
      .limit(page_size);
    status_code = Consts.STATUS_CODE.SUCCESS.DATA_FOUND;

    var challengePromises = challenges.map(async function(o) {
      var challenger_club = await Club.findById(o.challenger_club_id);
      var challege = {
        challenge: o,
        challenger_club_name: challenger_club.club_name,
        challenger_club_avatar: challenger_club.avatar
      };
      return challege;
    });
    var challengeObjs = await Promise.all(challengePromises);

    res.json({
      "status": true,
      "message": "Challenges found !",
      "status_code": status_code,
      "challenges": challengeObjs
    });

  } catch (error) {
    status_code = Consts.STATUS_CODE.ERROR.UNKOWN_ERROR;
    res.json({
      "status": false,
      "status_code": status_code,
      "error": error
    })
  }
}

Also, just a suggestion, but if you're using async and await, you might consider going all the way with ES6+ syntax, such as const instead of var, arrow functions when possible, shorthand object properties, among other things - they can make code more concise and readable. For example, I'd refactor your code to:
exports.getListChallenges = async function(req, res) {
  try {
    const page_number = parseInt(req.params.page_number);
    const page_size = parseInt(req.params.page_size);
    const challengeData = await Challenge.find()
      .skip(page_size * (page_number - 1))
      .limit(page_size);
    const status_code = Consts.STATUS_CODE.SUCCESS.DATA_FOUND;
    const challengePromises = challengeData.map(async (o) => {
      const {
        club_name: challenger_club_name,
        avatar: challenger_club_avatar
      } = await Club.findById(o.challenger_club_id);
      return {
        challenge: o,
        challenger_club_name,
        challenger_club_avatar
      };
    });
    const challenges = await Promise.all(challengePromises);
    res.json({
      status: true,
      message: "Challenges found !",
      status_code,
      challenges
    });
  } catch (error) {
    const status_code = Consts.STATUS_CODE.ERROR.UNKOWN_ERROR;
    res.json({ status: false, status_code, error })
  }
}

Note that the status_code will always be Consts.STATUS_CODE.ERROR.UNKOWN_ERROR when there's an error, given the logic on your original code - there's no need to reassign it.


text:
Q: How to place glTF file in aframe? I'm just trying to add a 3d model from Sketchfab into this scene, but I can't find any straightforward tutorials on how to do so. Here's the code:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Peachtree Corners Veterans Monument - A-Frame</title>
        <meta name="description" content="Peachtree Corners Veterans Monument!">

Here's the sketchfab model I want to upload:https://sketchfab.com/models/729e5bc464454b5099445538e7785a19#

A: Use the gltf-model component - there is an example in the documentation
Download the zip from sketchfab, there are two files: scene.gltf, scene.bin and a textures folder, make sure they're in the same directory, and load the model:


text:
Q: Package 'neuralnet' in R, rectified linear unit (ReLU) activation function? I am trying to use activation functions other than the pre-implemented "logistic" and "tanh" in the R package neuralnet. Specifically, I would like to use rectified linear units (ReLU) f(x) = max{x,0}. Please see my code below.
I believe I can use custom functions if defined by (for example)
custom <- function(a) {x*2}

but if I set max(x,0) instead of x*2 then R tells me that 'max is not in the derivatives table', and same for '>' operator. So I am looking for a sensible workaround as I am thinking numerical integration of max in this case wouldn't be an issue.
nn <- neuralnet(
  as.formula(paste("X",paste(names(Z[,2:10]), collapse="+"),sep="~")),
  data=Z[,1:10], hidden=5, err.fct="sse",
  act.fct="logistic", rep=1,
  linear.output=TRUE)

Any ideas? I am a bit confused as I didn't think the neuralnet package would do analytical differentiation.

A: You can approximate the max function with a differentiable function, such as:
custom <- function(x) {x/(1+exp(-2*k*x))}

The variable k determines the accuracy of the approximation.
Other approximations can be derived from equations in section "Analytic approximations": https://en.wikipedia.org/wiki/Heaviside_step_function

A: The internals of the neuralnet package will try to differentiate any function provided to act.fct.  You can see the source code here.
At line 211 you will find the following code block:
if (is.function(act.fct)) {
    act.deriv.fct <- differentiate(act.fct)
    attr(act.fct, "type") <- "function"
}

The differentiate function is a more complex use of the deriv function which you can also see in the source code above.  Therefore, it is currently not possible to provide max(0,x) to the act.fct.  It would require an exception placed in the code to recognize the ReLU and know the derivative.  It would be a great exercise to get the source code, add this in and submit to the maintainers to expand (but that may be a bit much).
However, regarding a sensible workaround, you could use softplus function which is a smooth approximation of the ReLU.  Your custom function would look like this:
custom <- function(x) {log(1+exp(x))}

You can view this approximation in R as well:
softplus <- function(x) log(1+exp(x))
relu <- function(x) sapply(x, function(z) max(0,z))

x <- seq(from=-5, to=5, by=0.1)
library(ggplot2)
library(reshape2)

fits <- data.frame(x=x, softplus = softplus(x), relu = relu(x))
long <- melt(fits, id.vars="x")
ggplot(data=long, aes(x=x, y=value, group=variable, colour=variable))+
  geom_line(size=1) +
  ggtitle("ReLU & Softplus") +
  theme(plot.title = element_text(size = 26)) +
  theme(legend.title = element_blank()) +
  theme(legend.text = element_text(size = 18))

A: a bit belated, but in case anyone else is still looking for an answer. Here's how to incorporate the non-approximated ReLu function. This is achieved by loading it from a package.
Note that while you could technically define the relu function yourself (with max() or if(x<0) etc.), this wouldn't work in the neural net package because it needs a differentiable function.
First, load the relu function from sigmoid package, which is differentiable
install.packages('sigmoid')
    library(sigmoid)
    relu()

Second, insert in your code
   nn <- neuralnet(
   as.formula(paste("X",paste(names(Z[,2:10]), collapse="+"),sep="~")),
   data=Z[,1:10],
   hidden=5, err.fct="sse",
   act.fct=relu,
   rep=1,
   linear.output=TRUE)

I found this solution in another post, but can't for the life of me rememeber which one, so credits to unknown.


text:
Q: compilar juego de unity con dll nativo estoy intentando montar mi proyecto de Unity, que he creado en código nativo de C++.
Tengo la librería en el directorio raíz del proyecto, uso dicha librería con dllImport.
Al compilar el programa y crear el .exe (ejecutable), arroja un fallo de dllnotfoundexception.
no sé cómo hacer para montar el programa con la DLL.
¿alguna ayuda?

A: No es exactamente una respuesta que resuelva tu problema de forma directa pero hay bastante información dentro de la documentación de OpenCV, incluso tienen un foro y un método para obtener ayuda para resolver problemas.
Apoyo
Cuando algo falla
Si está intentando depurar un programa OpenCV:

*

*Al principio, intente solucionar el problema utilizando
documentación  y  tutoriales .

*Si no funciona, busque una respuesta o formule una pregunta en
OpenCV Answers .

*Si encontró un error o desea realizar una solicitud de función,
consulte la siguiente sección.

Problemas de informes / características de solicitud

*

*Primero, verifique el  rastreador de problemas : los errores
conocidos, a menudo con parches o soluciones, generalmente se
encuentran allí. Si tiene algo que agregar a un error existente,
agréguelo como un comentario al ticket, en lugar de publicarlo en las
listas de correo.

*Luego revise las  Respuestas de OpenCV  para ver si alguien más ha
hecho su pregunta o ha reportado su error. Si todos los pasos
anteriores fallaron, lo mejor que puede hacer es levantar un  boleto.

*Si no estás seguro de lo que encontraste es un error que puedes
preguntar en  OpenCV Answers . Si el problema se confirma como un
error, cree un ticket.
Haciendo una pregunta
¡Lea antes de publicar en cualquiera de los foros / listas de soporte de OpenCV!
No haga:

*

*Las siguientes no son   preguntas apropiadas:

*preguntas generales de programación / depuración

*Preguntas sobre software que no está relacionado con OpenCV

*pidiendo ayuda con tu tarea

*No  , no  en contacto con los desarrolladores / mantenedores
directamente:

*la comunidad no puede ver las preguntas o respuestas que no se han
hecho / contestado públicamente

*el desarrollo de código abierto funciona mejor cuando toda la
comunidad participa en discusiones y ayuda a responder preguntas
Hacer:

*

*Sea lo más específico posible, con pasos para reproducir. Si podemos
reproducir el problema, podemos solucionarlo rápidamente.

*Envíe todas las preguntas a  OpenCV Answers  u otra lista de correo
correspondiente, e informe todos los errores al rastreador de
errores.

*Especifique su plataforma (Windows 32 / 64bit, Linux x86 / x64 / ppc
/…, MacOSX 32 / 64bit / ppc); versión del compilador; Versión /
revisión de OpenCV; si IPP, OpenMP, MMX, SSE… se han habilitado o no,
y cualquier otra información que nos permita reproducir el entorno,
identificar y localizar el problema.

*Un código de ejemplo que reproduce el problema nos ayuda más. Por
favor verifique las  muestras  - para el estilo preferido (tamaño de
código pequeño, multiplataforma). No es  necesario  proporcionar
ningún archivo de proyecto o archivo make, si se trata de una muestra
corta de un solo archivo, podríamos compilarlo y ejecutarlo en un
minuto.

*Proporcione la salida de la
cv::getBuildInformation()
función cada vez que informe un error sobre la versión troncal de
OpenCV. El problema puede estar en la configuración de su
compilación, por lo que el registro puede ayudarnos enormemente.

*Si su aplicación es compleja y el problema ocurre en algún punto
intermedio, a menudo es posible crear una muestra independiente
corta: captura y almacena los datos que pasas a la función usando
FileStorage
Copia la llamada de función y coloca la lectura correspondiente desde
FileStorage
delante.

*Describa exactamente lo que estaba haciendo o está tratando de hacer
y qué salió mal. Si dice:  "¡OpenCV no funciona!"  , No podremos
ayudarlo.

*Según corresponda, también incluya su:

*backtraces

*archivos de configuración relevantes

*Capturas de pantalla o videos para demostrar el problema.

*

*documentación

*tutoriales

*Respuestas OpenCV

*Respuestas de OpenCV

*Ticket
etc...  etc...  etc... que puedes leer en los siguientes links


text:
Q: Circuitmaker - define board size manually Been testing out Circuitmaker for a few days now. Since I am a forme EAGLE user, I have quite a hard time figuring certain basic functions out. The most important one to me is the board size definition.
Is it possible to define the board size just by typing in the actual size and then set the board size to those values? I know the methods for defining the shapes via lines etc. but I would just like to type in some numbers and set the board according to that.
Is there a simple way how to do that?
Greetings,
Lukas

A: Home | Board | Board Shape » Edit Board Shape.
drag with handles and look at bottom left to see the size


text:
Q: Dropdownlist in razor cshtml with model and viewmodel I have the following code. The model is an Asset. However, what I want is to assign a user for each Asset in View Model through @Html.DropDownListFor(model => model.UserFromTable, new SelectList(Model.UsersFromTable, "UserName", "UserName")).
The thing is that I tried appropriate SelectList<> etc., but I don't know how to assign users from the dropdownlist in users column to assets in ViewModel. Another thing is that I don't receive my selection in ViewModel after Post. I can pass there some checkbox values but not the selections from the above dropdownlist.
I read some posts on stackoverflow and found out that some similar tasks require foreach. There is already one foreach loop in the code. I believe I should work on var item in Model.Assets somehow. I also have a separate CRUD Edit cshtml page for editing one single Asset but I want to save changes in user dropdownlist to all Assets on the current page.
Is it possible and how can I do it?
@Html.Partial("AssetsFiltering", Model.AssetsFilteringVM)
@foreach (var item in Model.Assets)
{

        @Html.Span(item.Id)
        ....

            @Html.DropDownListFor(model => model.UserFromTable, new SelectList(Model.UsersFromTable, "UserName", "UserName"))


text:
Q: Need SEO help with our sitemap.xml Google Index rate We have a Magento multi-store setup for 3 stores/domains built on October, 2013. Since then we have great google sitemap.xml index rates for over 90% across all 3 domains. On 2/25/2014, we added another domain into the same magento installation. The sitemap.xml index rate for the original 3 domains dropped significantly afterward.(Our mistake to include every single SKUs we have into the 4th domain) After we discovered the problem, we took out the 4th domain and changed everyting back to before. We waited for couple weeks, 2 of the websites are back on track on sitemap.xml with 90% index rate. For the other domain, we tried everything we could to increase the index rate without any luck. It's been over one month after we took out the 4th domain, somehow Google only indexed 1% of the sitemap.xml and kept the rate since.

*

*Our configurations:

*

*Magento Configurations are the same across all 3 stores/domains

*All 3 domains using different IP addresses. (We implemented this after the big drop on index rate)

*3 websites share some of the products and brands we carry

*All 3 domains shares same .htaccess and robot.txt

*All of our domains are more than 5 years old.

*We use Nexcess for Magento hosting. (Updated for reference.)

Question:
What else might causing google to not index the 3rd domain's sitemap.xml?
FYI: We are able to manually submit urls in webmaster tools for google to index it.

A: You are quite lucky you were reindexed in weeks, for most it takes months - normally 3-6mths. Regardless of what anyone says, there are no guarantees with indexing and ranking, only best practices, likely they have flagged that domain. Too many factors come in to play on the business and technology side, one of the factors is the hosting company. We use top tier providers but they are 2-5x slower than lower tier providers, so we used a special architecture from a third party making a site look bigger than it is. Without making your other domain 'look' bigger Google loses interest, especially if flagged.
The age of the domain makes no difference, a brand new domain was listing the same products next to eBay and Amazon first page. Google will see through full page caches so if your dynamic loads are more than 1-2s you will have a problem. There are too many factors to go through, so without enterprise style hosting -or- knowing the business tricks to mitigate most of these issues (only a handful know these), you will have to go the trial and error route over the coming months - checking once a week for any changes.
Lastly, this is a business problem not a technical problem, we never did find where to direct people for these as this is not the forum for it.


text:
Q: Symfony3 LDAP authentication bind credentials I'm struggling with the ldap authentication within a symfony project.
My service looks like this:
ldap:
    class: Symfony\Component\Ldap\Ldap
    factory: ['Symfony\Component\Ldap\Ldap', 'create']
    arguments:
        - 'ext_ldap'
        - host: 'ldap.example.com'

The bind and a example query to the ldap server are working fine:
$ldap = $this->get('ldap');
$ldap->bind('binduser', 'bindpw');
$query = $ldap->query('OU=MyBusiness,DC=example,DC=com', 'sAMAccountName=xxx');

Now I want to authenticate against the ldap server. I have used the firewall settings from http://symfony.com/doc/current/security/ldap.html#configuration-example-for-form-login.
But the great question is where to put the bind credentials here?
The corresponding log entry here is:
php.DEBUG: Warning: ldap_bind(): Unable to bind to server: Invalid credentials

So it's pretty obvious what's missing, but I couldn't find a way to provide the bind credentials to form_login_ldap.
The reference on http://symfony.com/doc/current/reference/configuration/security.html also doesn't show how to provide them.
Thanks!

A: The bind credentials are those submitted from the user in the form.
As you see here http://symfony.com/doc/current/security/ldap.html#configuration-example-for-form-login
            service: ldap
            dn_string: 'uid={username},dc=example,dc=com'

you just need to specify the dn_string and the user will be authenticated with his credentials calling a ldap_bind.
Is your user (the one you entered in the form) authorized to ldap_bind?
The one you enter in the config of the LDAP user provider, if you have one, is useless for this purpose.
The form login is a traditional login form that can be done following this http://symfony.com/doc/current/security/form_login_setup.html


text:
Q: can i store a value returned by apex method in a javascript variable? Is it possible to store a value returned by a controller method into a javascript variable?
i need to pass a date and sales qty from salesforce into flot library javascript to build a graph. So what i am doing is formatting a string in apex with the date and salesqty as required by flot library and returning it  in the method.
Can i say in my javascript
var d={!getformatteddata};

Thanks
Prady

A: You can do this, just omit the leading 'get':
var d='{!formatteddata}';


text:
Q: Partition of $\mathbb{Z}_8$ into cosets of Ker(θ) Question: Let $\theta : \mathbb{Z}_8 → \mathbb{Z}_4$ be defined by $\theta([i]_8) = [i]_4$ for all $i \in \mathbb{Z}$. You may assume that this is a well-defined ring homomorphism.

*

*Find Ker($\theta$)

*Exhibit the partition of $\mathbb{Z}_8$ into cosets of Ker($\theta$).
My Answer: So I found the Ker($\theta$) as Ker($\theta$) $=\{[0]_8, [4]_8\}$ as $\theta[0]_8=[0]_4$ and $\theta[4]_8=[4]_4=[0]_4$.
But I'm stuck on part 2. I was thinking that I would need to show that the partition of $\mathbb{Z}_8$ are equal to $[0]_4$ or $[4]_4$.
Sorry about how I have typed it, haven't really asked questions on the site before.

A: I think you have found the kernel correctly. The cosets of an ideal $I$ in a  ring are defined to be the translates $r+I$, where $r$ is some element. In particular, if $r \in I$, then $r+I=I$. Applying this, we see that we have 4 cosets, given by

*

*$0+ \text{Ker}(\theta) = \text{Ker}(\theta) = 4+ \text{Ker}(\theta)$

*$1+ \text{Ker}(\theta) = \{[1]_8,[5]_8\} = 5+ \text{Ker}(\theta)$

*$2+ \text{Ker}(\theta) = \{[2]_8,[6]_8\} = 6+ \text{Ker}(\theta)$

*$3+ \text{Ker}(\theta) = \{[3]_8,[7]_8\} = 7+ \text{Ker}(\theta)$

I'm not sure if you talked about quotient rings yet, but if you look at the left hand side, the translates $\{0,1,2,3\}$ end up having a structure isomorphic to $\mathbb{Z}_4$.
(Edited)

A: You've misunderstood what a partition is, I think. A partition is any bunch of disjoint subsets that cover the whole set. For example, the following is a partition of $\mathbb{Z}_8$:
$$\{1\}, \{2, 4, 6\}, \{3, 0\}, \{5\}, \{7\}.$$
Here's another:
$$\{1, 2, 3, 4, 6, 7\}, \{0,5\}.$$
Here's the crucial fact. Whenever you have a ring $R$, and an ideal $I$ of that ring, the cosets $a+I$ (for various $a\in R$) partition $R$. That is (assuming for simplicity that things are appropriately finite), there exist some $a_1, \dots, a_n\in R$ such that
$$a_1 + I, \dots, a_n + I$$
is a partition of $R$.
Now let $R = \mathbb{Z}_8$ and $I = \ker \theta$. Can you find such $a_1, \dots, a_n$? (Note that taking $0 + \ker\theta$ and $4 + \ker\theta$ gives you the same thing, for the reasons you said. On the other hand, $1+\ker\theta$ is something new.)

A: A partition of a set $X$ is a collection of subsets $X_i\subset X$ such that $X_i\cap X_j=\varnothing$ whenever $i\neq j$, and such that $\bigcup_{i\in I}X_i=X$. That is, a collection of non-overlapping subsets that together cover $X$.
For a (commutative) ring $R$ a coset of an ideal $I\subset R$ is defined  as a subset of $R$ of the form
$$r+I:=\{r+i:\ i\in I\},$$
for some $r\in R$. It is a nice exercise to prove that the cosets of an ideal form a partition of the ring.
With this information; what are the cosets of $\ker\theta\subset\Bbb{Z}/8\Bbb{Z}$? Can you show that they form a partition of $\Bbb{Z}/8\Bbb{Z}$?


text:
Q: how to change android spinner popupBackground I was trying to change the android spinner popup window background by setting the android:popupBackground, but it didn't have any effect. Is there any way I can change it?
    <Spinner
           android:id="@+id/eventNameSpinner"
           android:layout_width="160dp"
           android:layout_height="30dp"
           android:layout_alignParentLeft="true"
           android:layout_centerVertical="true"
           android:layout_marginLeft="6dp"
           android:background="@drawable/btn_name"
           android:paddingBottom="2dp"
           android:paddingTop="2dp"
           android:popupBackground="@drawable/bkg">

A: I presume you are trying to change the "outer" backgroud of a Spinner's popup, not the background of Spinner "pupup items". Also, I presume that by popup, you mean a Spinner's dialog mode, where a floating dialog window appears on top of your activity, as opposed to the new dropdown mode.
Strategy
For a clean, sustainable approach which behaves well across multiple Android platforms and reduces the need for redundancy in the App, I believe it is essential to understand what the official docs don't tell us. So follow me on a short journey.
The tricky part about Spinners is that an Adapter is used to connect them to data. While it is relatively easy to identify the hooks for changing the appearance of android.R.layout.simple_spinner_item and its friends, those only determine the style of the Spinner's currently displayed item as well as each single popup item. But it is the Adapter which is responsible for creating the ListView and other widgets which frame that ListView.
This complexity is probably the reason why Android has introduced some attributes which can be specified on-the-fly "for" the Spinner although they are then applied to the Spnner's children, such as android:popupBackground. This is not necessarily a clean approach, rather a limited set of convenience functions. Regarding popupBackground, btw, this was introduced in API level 1, but Spinners respect it only in spinnerMode=dropdown, which was introduced in API level 11. That's the reason why you'll never be notified if you use it wrongly.
Older Android Versions (such as 2.2)
ListView
Knowing that the Adapter creates a ListView, it's not a bad idea to change the ListView appearance in one's theme, so there's one single place for the design change and the styling straightforward, like so:
<style name="MyTheme" parent="@android:style/[reference to original theme]" >
    <item name="android:listViewStyle">@style/myListView</item>
    [...]
</style>

<style name="myListView" parent="@android:style/Widget.ListView">
    [check Android's Widget.ListView to understand what you can change here]
</style>

AlertDialog
Unfortunately, there's more work ahead. Because android:prompt can be used to create a headline for the popup, the popup really consists of more than just the ListView.
Android uses an AlertDialog
Recent Android Versions (such as 4.2)
Now that the AlertDialogs are styled, we still have to address the fact that more recent versions of Android don't use AlertDialogs for Spinner dialogs any more. That doesn't hurt, because for those, the AlertDialog style shouldd be kept anyways. It just means we need to style the new popup as well.
To do so, create version specific theme XML files to pull the additional styles into your customized theme, and provide version specific style XML files.
Feel like trying it yourself, starting here?

A: android:popupBackground is only valid when using android:spinnerMode = "dropdown" , thats probably why it wasnt any effect in your code. You need to tell that spinner which mode its in with some XML.
android:spinnerMode = "dropdown"

Links

*

*http://developer.android.com/reference/android/widget/Spinner.html#attr_android:popupBackground

*http://developer.android.com/reference/android/widget/Spinner.html


text:
Q: In Google Sheets, why does my recorded macro also run two other scripts when invoked? I have recorded a macro in Sheets, the purpose of which is to add a colour scale with conditional formatting. It works fine, but I get two popups saying "Done" when it completes. I have traced these to two other app scripts I have used in the past. (Note: These are scripts , not recorded macros)
Q. Why, when I invoke the macro with its assigned keyboard shortcut, do I also get the popups for the other scripts? The scripts themselves don't appear to run fully (as the ranges they amend are unchanged).
This is the recorded macro:
function Addcolourscale() {
  var spreadsheet = SpreadsheetApp.getActive();
  var conditionalFormatRules = spreadsheet.getActiveSheet().getConditionalFormatRules();
  conditionalFormatRules.push(SpreadsheetApp.newConditionalFormatRule()
  .setRanges([spreadsheet.getActiveRange()])
  .whenCellNotEmpty()
  .setBackground('#B7E1CD')
  .build());
  spreadsheet.getActiveSheet().setConditionalFormatRules(conditionalFormatRules);
  conditionalFormatRules = spreadsheet.getActiveSheet().getConditionalFormatRules();
  conditionalFormatRules.splice(conditionalFormatRules.length - 1, 1, SpreadsheetApp.newConditionalFormatRule()
  .setRanges([spreadsheet.getActiveRange()])
  .setGradientMinpoint('#57BB8A')
  .setGradientMaxpoint('#FFFFFF')
  .build());
  spreadsheet.getActiveSheet().setConditionalFormatRules(conditionalFormatRules);
  conditionalFormatRules = spreadsheet.getActiveSheet().getConditionalFormatRules();
  conditionalFormatRules.splice(conditionalFormatRules.length - 1, 1, SpreadsheetApp.newConditionalFormatRule()
  .setRanges([spreadsheet.getActiveRange()])
  .setGradientMinpoint('#57BB8A')
  .setGradientMidpointWithValue('#FFD666', SpreadsheetApp.InterpolationType.PERCENTILE, '50')
  .setGradientMaxpoint('#E67C73')
  .build());
  spreadsheet.getActiveSheet().setConditionalFormatRules(conditionalFormatRules);
};

This is one of the scripts that produces the popup, due to its final two lines, when the above macro completes. It's something I adapted from an online resource, so I don't know it well.
function CopyClientChannelUseBack(){
    /* Edit the vars below this line for your needs */
    var sourceSheet  = "12 mth Client channel use" ;  // Enter the name of the sheet with the source data
    var sourceRange = "A19:S29" ; // Enter the range of the cells with the source data
    var targetSheet = "12 mth Client channel use" ; // Enter the name of the target sheet
    var targetRange = "A20:S30" ; // Enter the range of cells you wish to copy data to. Note this must be same size as source range.
    /* No need to edit below this point */

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName(sourceSheet);
    var values = sheet.getRange(sourceRange).getValues();
    ss.getSheetByName(targetSheet).getRange(targetRange).setValues(values);
  SpreadsheetApp.flush()

      /* Edit the vars below this line for your needs */
    var sourceSheet  = "12 mth Client channel use" ;  // Enter the name of the sheet with the source data
    var sourceRange = "A49:N59" ; // Enter the range of the cells with the source data
    var targetSheet = "12 mth Client channel use" ; // Enter the name of the target sheet
    var targetRange = "A50:N60" ; // Enter the range of cells you wish to copy data to. Note this must be same size as source range.
    /* No need to edit below this point */

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName(sourceSheet);
    var values = sheet.getRange(sourceRange).getValues();
    ss.getSheetByName(targetSheet).getRange(targetRange).setValues(values);
  SpreadsheetApp.flush()
  SpreadsheetApp.getUi().alert("Done")
}

The manifest file has no reference to the scripts, only the macro.
{
  "timeZone": "Europe/London",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "sheets": {
    "macros": [{
      "menuName": "Add colour scale",
      "functionName": "Addcolourscale",
      "defaultShortcut": "Ctrl+Alt+Shift+9"
    }]
  }
}

A: OK. I worked out what the problem was. Nothing to do with the code I pasted. It turned out that I had added some code on the end of the other scripts, literally on the end, outside of the closing } bracket of that function. so those few lines were running as well. It appears GAS runs through all the scripts available, looking for the one that's just been called. As there was code outside of the functions, that was being executed too.


text:
Q: How to put a file in an array in java I've seen many links to do the opposite of this but that is not what I want.
I want to make an array and the contents of the array I want to equal the file, so they can be read one at a time in a loop but what I've shown below is what I have come up with at the moment, but have no idea how to get right.
File (lifeobjects[5]) = new File ("toad.lif");

EDIT:
I want to read a file from an array not into one.
The array just points to the file to be read. and I have a string array called lifeobjects which I want the files to be in.
EDIT:
All this array does is list the files, after that a for loop will get each file one at a time, read them and the contents will go into another array. To make java realize that each element of the array is a file is where I am getting stuck. The one line of code I have is one of many after the String array which is where the list of file names are found.
EDIT:
Ok I've managed to get it working, All I needed to do was change the array elements and add their file extensions to them and the code above wasn't needed at all, sorry if the question was too vague, had hard time explaining it. All I have to do now is convert this command line program to a GUI with  a square grid, I'll ask that question next as I have tried and tried and got nowhere.

A: If I understand your question correctly:
File[] lifeobjects = new File[5];
lifeobjects[0] = new File("toad.lif");
lifeobjects[1] = new File("toad2.lif");
...
lifeobjects[4] = new File("toad5.lif");


text:
Q: Add 12 hours to time.now in c# I am adding 12 hours to the current time. but the current time is displayed in the text box, what is wrong with the code
 DateTime expiresAt = System.DateTime.Now.AddHours(12);
 txt_ExpiresBy.Text = expiresAt.ToString(@"dd/MM/yyyy hh:mm:ss");

A: Maybe you are adding 12 hours and you don't see the difference between X AM and X PM?
Try using HH (hour in 24 hours format) instead of hh (hour in 12 hours format) in the format string, or adding the AM/PM indicator tt:
// 24 hours format
expiresAt.ToString(@"dd/MM/yyyy HH:mm:ss");

// 12 hours + am/pm
expiresAt.ToString(@"dd/MM/yyyy HH:mm:ss tt");

See Custom Date and Time Format Strings for a complete reference.


text:
Q: How to subscribe to Kafka topics using wildcards with DelphiKafkaClient (or librdkafka.dll)? I'm using DelphiKafkaClient (https://github.com/norgepaul/DelphiKafkaClient) which is a wrapper for the Apache Kafka (librdkafka.dll).
When creating a new consumer and specifying a topic name to subscribe to (in TKafkaFactory.NewConsumer), normal names do work well, but regex wildcards seem to not work (^*, *, #, ^.* or anything else).
Here's the relevant code from DelphiKafkaClient (see my comments):
procedure TKafkaConsumerThread.DoSetup;
var
  i: Integer;
  TopicList: prd_kafka_topic_partition_list_t;
  err: rd_kafka_resp_err_t;
begin
  FKafkaHandle := TKafkaHelper.NewConsumer(FConfiguration);

  if rd_kafka_brokers_add(FKafkaHandle, PAnsiChar(AnsiString(FBrokers))) = 0 then
  begin
    raise EKafkaError.Create(StrBrokersCouldNotBe);
  end;

  rd_kafka_poll_set_consumer(FKafkaHandle);

  TopicList := rd_kafka_topic_partition_list_new(0);

  for i := Low(FTopics) to High(FTopics) do
  begin
    rd_kafka_topic_partition_list_add(
      TopicList,
      PAnsiChar(AnsiString(FTopics[i])), // 'test' works, '^*' does not
      FPartitions[i]);
  end;

  err := rd_kafka_assign(FKafkaHandle, TopicList); // no errors returned, all fine

  // I have tried using rd_kafka_subscribe alongside or instead - makes no difference
  err := rd_kafka_subscribe(FKafkaHandle, TopicList); // no errors returned, all fine
end;

rd_kafka_subscribe description says that

Wildcard (regex) topics are supported:
any topic name in the \p topics list that is prefixed with \c "^" will
be regex-matched to the full list of topics in the cluster and matching
topics will be added to the subscription list.

However, specifying any wildcards for it and calling rd_kafka_subscribe does not seem to work either (see code above).
Hence my question - how should a string be formatted and passed to DelphiKafkaClient or librdkafka.dll to work as a valid regex for matching the topic subscriptions?

A: DelphiKafkaClient (https://github.com/norgepaul/DelphiKafkaClient) comes with a really old DLL. Upgrading the DLL from version 0.9.2 to a newer one made the RegEx work properly.


text:
Q: any easy and reliable java API than SMSLib for sending sms? I want to send sms from my java web application using SMSLib. I followed installation process from  http://smslib.org/doc/installation/. but its not working.if anybody help me by any code or information of java API, i really appreciate.
public void doIt() throws Exception
{
    OutboundNotification outboundNotification = new OutboundNotification();
    System.out.println("Example: Send message from a serial gsm modem.");
    System.out.println(Library.getLibraryDescription());
    System.out.println("Version: " + Library.getLibraryVersion());
    SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM4", 9600, "Nokia", "C2-03");
    gateway.setInbound(true);
    gateway.setOutbound(true);
    gateway.setSimPin("1234");

    // Explicit SMSC address set is required for some modems.
    // Below is for VODAFONE GREECE - be sure to set your own!
    gateway.setSmscNumber("+8801700000600");
    Service.getInstance().setOutboundMessageNotification(outboundNotification);
    Service.getInstance().addGateway(gateway);
    Service.getInstance().startService();
    System.out.println();
    System.out.println("Modem Information:");
    System.out.println("  Manufacturer: " + gateway.getManufacturer());
    System.out.println("  Model: " + gateway.getModel());
    System.out.println("  Serial No: " + gateway.getSerialNo());
    System.out.println("  SIM IMSI: " + gateway.getImsi());
    System.out.println("  Signal Level: " + gateway.getSignalLevel() + " dBm");
    System.out.println("  Battery Level: " + gateway.getBatteryLevel() + "%");
    System.out.println();
    // Send a message synchronously.
    OutboundMessage msg = new OutboundMessage("+8801719057995", "call me, sanchoy");
    Service.getInstance().sendMessage(msg);
    System.out.println(msg);

    System.out.println("Now Sleeping - Hit <enter> to terminate.");
    System.in.read();
    Service.getInstance().stopService();
}

A: You could purchase a cheap 150 dollar Android phone, sign up and install the Sent.ly app from the Google Play Store and then use the API provided by Sent.ly
http://sent.ly
The API is HTTP based so calling it from your web app would be really simple:
import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        String sentlyUsername = "yourusername";
        String sentlyPassword = "yourpassword";
        String destinationNumber = "+14085616821";
        String message = "This is what I want to send";
        URL sentlyService = new URL("http://sent.ly/command/sendsms" +
           "?username=" + sentlyUsername +
           "&password=" + sentlyPassword +
           "&to=" + destinationNumber +
           "&text=" + message);
        URLConnection yc = sentlyService .openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

More documentation can be found here:
https://docs.google.com/document/d/1MuFXPTWq7zNIChwZdzIrqiQ2-Mb3_rPrWqNlOZXJNws/edit?pli=1


text:
Q: I want to add values from a text file and add it in two dimensional java. But gives null pointer exception I want to read a text file and add the contents to the two dimensional array in java. but when i add these values to the array I am getting array out of bounds exception in java.
java.io.File test2 = new java.io.File("e:\\A.txt");

   BufferedReader bw =new BufferedReader(new FileReader("e:\\A.txt"));

   String s=bw.readLine();
   while(bw.readLine()!=null)
   {

       counterRow++;
   }

   System.out.println(counterRow);
   String sw=bw.readLine();

   String[] words=s.split(",");

   counterCol=words.length;
   System.out.println(words.length);

   @SuppressWarnings("resource")
Scanner input = new Scanner(test2);
   String Data[][]=new String[counterRow][counterCol];
   int i1=0,j1=0;
   while(input.hasNext())
   {
       String val=input.nextLine();
       j1=0;
       if(val.contains(","))
       {
           String str[]=val.split(",");
           int cn=str.length;
           while(cn>0)
           {
               Data[i1][j1]=str[j1];
               cn--;
               j1++;
           }
     }
         else
           Data[i1][j1]=val;
       i1++;
   }

My input file is
69,79,82
72,82,84
39,70,75
69,88,68
38,72,61
39,60,40
36,32,44
50,71,55
36,47,47
80,81,90

Error   :    Exception in thread "main" 100sssssss
  java.lang.NullPointerException    at
  com.associa.mining.AssociateRuleMiningAlgo.main(AssociateRuleMiningAlgo.java:200)

A: Thats because you are trying to read after you have reached EOF
while(bw.readLine()!=null)  // read till EOF
{

   counterRow++;
}

System.out.println(counterRow);
String sw=bw.readLine();         // ERROR cant read, you have reached EOF

PS - you dont even seem to use the variable "sw".

A: Change the  if(val.contains(",")) condition to if(val!=null && val.contains(","))
compelete code
String val=input.nextLine();
j1=0;
if(val!=null){

   if(val.contains(","))
   {
       String str[]=val.split(",");
       int cn=str.length;
       while(cn>0)
       {
           Data[i1][j1]=str[j1];
           cn--;
           j1++;
       }
     }else
        Data[i1][j1]=val;
     i1++;
 }


text:
Q: Tensorflow Backpropagation with variable batch size I have a tensorflow model where each tensor in a batch has a different size. Would it be possible to get the correct gradients if I concatenate all the losses and run the optimizer on them like in this example:
import tensorflow as tf

v1 = tf.range(9,dtype=tf.float32)
v2 = tf.range(6,dtype=tf.float32)
v1 = tf.reshape(v1,[3,3])
v2 = tf.reshape(v2,[2,3])

gt1 = tf.constant([2,5,4])
gt2 = tf.constant([1,5])

with tf.variable_scope("var"):
    w = tf.get_variable('w', [3,7], dtype=tf.float32)
    r1 = v1 @ w
    r2 = v2 @ w

loss1 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=gt1, logits=r1)
loss2 = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=gt2, logits=r2)

loss = tf.concat([loss1, loss2],axis=0)
optimizer = tf.train.AdamOptimizer().minimize(loss)

with tf.Session() as sess:
    # print the output of ta_final_result
    sess.run(tf.global_variables_initializer())
    print(sess.run(w))
    print(sess.run(optimizer))
    print(sess.run(w))

A: This is exactly equivalent to summing loss down to a scalar before passing it to minimize. In fact a reduce_sum will be implicitly added to the graph; you can try passing non-scalars to tf.gradients and see what happens:
import tensorflow as tf
session = tf.InteractiveSession()
v = tf.get_variable("v", shape=[])
session.run(v.assign(2.))
grad = tf.gradients([v ** 2., v ** 3.], [v])
session.run(grad)

[16.0]

Which is 2*2 + 3*2^2.


text:
Q: Text above the footer I am new to LaTeX and stuck at how to make a footer like shown in the figure:

Help would be appreciated.
Edit:
When I try to use \pagestyle{fancy} my documents runs out of memory (might be due to too many unnecessary packages). I tried using footnote like
\footnote{\textcopyright \;Gujrat Institute of Management Sciences\\
  PMAS-Arid Agriculture University, Rawalpindi}

but that did not work either, and I only want this footer on some specific pages.

A: With fancyhdr package:
\documentclass{article}

\usepackage{fancyhdr}
\pagestyle{fancy}

\fancyfoot{
    \centering
    \textbf{Institute}\\
    \textbf{University}\\
    \thepage\\
    \raggedright
    \footnotesize
    Copyright ...\\
    PMAS\\
    \rule{\textwidth}{1pt}%
}

\begin{document}

zzz

\end{document}

A: Well, because you gave us no MWE your question is not very clear. Because we do not know if you are using an KOMA-Script class or other standard class like article I simply guess you are using an class article. Then you can use package fancyhdr for creating headers and footers for every page of the document. Please note that situation changes if you are using KOMA-Script ...
To be able to use a special header-footer-combination for a special page(s) with command \thispagestyle{copyright} you need to define the style copyright like this:
\fancypagestyle{copyright}{%
  \fancyhf{} % empty header and footer
  \fancyfoot{%
    \centering
    \textbf{Gujrat Institute of Management Sciences}\\
    \textbf{PMAS-Arid Agriculture University, Rawalpindi}\\
    \thepage\\
    \raggedright\footnotesize
    \textcopyright\ Gujrat Institute of Management Sciences\\
    PMAS-Arid Agriculture University, Rawalpindi\\
    \rule{\textwidth}{0.5pt}%
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\footrulewidth}{0pt}
  }
}

Because your question is not very clear if you really need all the shown lines in your image I simply added all of them. Change the content of command \fancyfoot for your needs ... In the following MWE I added package showframe to visualize the used typing area and margins. Please see that on page 2 with your copyright style the footer changes the position of the pagenumber too.
With this MWE (see important code marked with <=====):
\documentclass{article}

\usepackage{showframe} % <================ to visualize typing area and margins
\usepackage{blindtext} % <================ adding dummy text into document
\usepackage{fancyhdr}

\fancypagestyle{copyright}{%
  \fancyhf{} % empty header and footer
  \fancyfoot{%
    \centering
    \textbf{Gujrat Institute of Management Sciences}\\
    \textbf{PMAS-Arid Agriculture University, Rawalpindi}\\
    \thepage\\
    \raggedright\footnotesize
    \textcopyright\ Gujrat Institute of Management Sciences\\
    PMAS-Arid Agriculture University, Rawalpindi\\
    \rule{\textwidth}{0.5pt}%
    \renewcommand{\headrulewidth}{0pt}
    \renewcommand{\footrulewidth}{0pt}
  }
}

\pagestyle{fancy}

\begin{document}

\blindtext

\clearpage % <======================= new page 2
\thispagestyle{copyright} % <======== style copyright only used on this page 2!
\blindtext

\clearpage % <======================= new page 3 with standard style fancy
\blindtext

\end{document}

you get the following pages:

If that is not what you need, please register your account and edit your question by adding more information to explain better your issue ...


text:
Q: Laravel - Is there any auth package without using database? What you recommend for Laravel authentication user based on JSON request and response? It should be without using database and token use for example:
I send request using JSON with username, password request and server responds as json using Auth class mechanism.
Is there any recommendations packages as json authentication usage?
I've tried Sentry but it uses MySQL.

A: No. You will have to store your user information somewhere, how else is anyone going to log in? You will need some sort of database to keep that data.


text:
Q: Go from 2*2 table to long date format in excel Any idea how I can generate dates for all occurrences of the different cell values in the following table?

Desired output:

Edit:
Monday in week1 is 04.01.21

A: 1] Set up a criteria with Qty column in Col N and Col O
2] In "Qty" O2, formula copied down :
=COUNTIF(B$2:I$5,N2)

3] In "Individual" K2, formula copied down :
=IFERROR(INDEX(N$2:N$4,AGGREGATE(15,6,ROW(N$2:N$4)-ROW(N$1)/(O$2:O$4>=COLUMN($1:$1)),ROW(A1))),"")

4] In "Date", L2 formula Copied down :
=44193+SUBSTITUTE(INDEX(A$1:A$5,AGGREGATE(15,6,ROW($2:$5)/(B$2:I$5=K2),COUNTIF(K$2:K2,K2))),"Week","")*7+LOOKUP(MOD(AGGREGATE(15,6,(ROW($2:$5)/1%+{2,3,4,5,6,7,8,9})/(B$2:I$5=K2),COUNTIF(K$2:K2,K2)),100),{2;3;4;5;6;7;8;9},{0;0;1;2;2;3;4;4})

Remark :
44193 (28/12/2020) being the Monday of last week number of year 2020,
then
Convert week number to date in the year of 2021 become >>
=44193 + WeekNumber x 7 + (0 to 4 being Mon to Fri)


text:
Q: Conditional Field Masking in Gravity Forms Hello I'm trying to figure out how to make a dynamic or on-the0fly field mask with Gravity Forms.
Which uses the Masked Input Plugin:
( http://digitalbush.com/projects/masked-input-plugin/ ) for it's field masking.
Example if first two numbers are 55 or 33 use '(##)-########' else use '(###)-#######' .
I was able to get a static version up that uses the mask '(##)-########'
Using the below javascript on the page:
"
setTimeout( function() {
    jQuery( '#input_9_1' ).mask( '(99)-99999999', { placeholder: '(__)-________' } );
}, 500 );

 "
Any thoughts on how I can alter the code to get the field to switch the mask according to the first two numbers inputted?
Here is the page:
goo.gl/8oGD8A
An Example of what I am trying to achieve using a different masking plugin:
http://jsfiddle.net/igorescobar/ebf0ovmj/
Any help would be appreciated.


text:
Q: Setting the form icon for an XNA window? Is there any way of changing the icon for an XNA game form (i.e. the one that appears in the top left corner of the form, and on the taskbar)?
I currently have a multi-icon with a variety of sizes embedded, including a 16x16 one. Unfortunately the project property "Application -> Resources -> Icon and manifest" uses the 32x32 one and scales it down, rather than the native one.
I'd like to manually set the icon to use the 16x16 one contained in the icon I have, and if possible change it dynamically at run-time.
Thank you.

A: After reading this thread, I came up with the following code (from program.cs):
static void Main(string[] args)
{

    using (Game1 game = new Game1())
    {
            ((System.Windows.Forms.Form)System.Windows.Forms.Form.FromHandle(game.Window.Handle)).Icon = new System.Drawing.Icon("file.ico");

            game.Run();
    }
}

file.ico should be copied to the same place as your executable.
You have to reference these assemblies in your solution:

*

*System.Windows.Forms

*System.Drawing

You can also replace the Game.ico in your solution folder, which has same effect.


text:
Q: How to unlink the SSIS parameter configuration between SSIS package in catalog and in the SQL server agent job step? I have a SSIS package deployed to the catalog. Parameters are configured.
A new SQL agent job step is used to run this SSIS package. In the configuration on the step, new values are set for a couple of parameters.
Now suppose I edit the parameters on the package in the catalog, then, for the parameters that were not edited in the previous step (in the job step), the value gets updated. How to unlink the SSIS parameter configuration between SSIS package in catalog and in the SQL server agent job step?


text:
Q: How to properly dispose objects: injected vs. owned I have a question about disposing objects.
Consider this IDisposable class
public class MyClass : DisposableParentClass
{
    private MyProp _prop;

    public MyClass(MyProp prop)
    {
        _prop = prop;
    }

    public MyClass()
    {
        _prop = new MyProp();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _prop.Dispose();
        }

        base.Dispose(disposing);
    }

}

On the first constructor, MyProp is injected. So MyClass is not the owner of the object. But on the second constructor, MyProp is created locally.
Should I always dispose MyProp, or should I check first if it is injected or not.
public class MyClass : DisposableParentClass
{
    private MyProp _prop;
    private bool _myPropInjected = false;

    public MyClass(MyProp prop)
    {
        _prop = prop;
        _myPropInjected = true;
    }

    public MyClass()
    {
        _prop = new MyProp();
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (!_myPropInjected) { _prop.Dispose(); }
        }

        base.Dispose(disposing);
    }

}

A: If your class should handle these two situations:

*

*It is not the owner of the provided object, it should not dispose of it

*It is the owner of the created object, it should dispose of it

Then yes, you need to have a mechanism that tells these two situations apart.
A common method (common to me anyway) is to use naming convention like this:
private MyProp _prop;
private bool _ownsProp = false;

ie. reverse the meaning of your flags, but this is details, your solution is just fine, and yes, you need to have a solution like this.

If you have a ton of these fields, where each must have its own bool field to handle this, it might be worth creating a helper class, such as this LINQPad program demonstrates:
void Main()
{
    Injectable i1 = new Injectable();
    Injectable i2 = new Injectable(new Injected("A"));
    Injectable i3 = new Injectable(new Injected("A"), new Injected("B"));

    Debug.WriteLine("dispose a and b");
    i1.Dispose();

    Debug.WriteLine("dispose b");
    i2.Dispose();

    Debug.WriteLine("no dispose");
    i3.Dispose();
}

public class Injected : IDisposable
{
    public Injected(string name) { Name = name; }
    public string Name { get; set; }
    public void Dispose() { Debug.WriteLine(Name + " disposed"); }
}

public class Injectable : IDisposable
{
    private Ownable<Injected> _A;
    private Ownable<Injected> _B;

    public Injectable(Injected a, Injected b)
    {
        _A = Ownable.NotOwned(a);
        _B = Ownable.NotOwned(b);
    }

    public Injectable(Injected a)
    {
        _A = Ownable.NotOwned(a);
        _B = Ownable.Owned(new Injected("B"));
    }

    public Injectable()
    {
        _A = Ownable.Owned(new Injected("A"));
        _B = Ownable.Owned(new Injected("B"));
    }

    public void Dispose()
    {
        _A.Dispose();
        _B.Dispose();
    }
}

public class Ownable<T> : IDisposable
    where T : class
{
    private readonly T _Instance;
    private readonly Action _CleanupAction;

    public Ownable(T instance, bool isOwned)
    {
        _Instance = instance;

        if (isOwned)
        {
            IDisposable disposable = instance as IDisposable;
            if (disposable == null)
                throw new NotSupportedException("Unable to clean up owned object, does not implement IDisposable");

            _CleanupAction = () => disposable.Dispose();
        }
    }

    public Ownable(T instance, Action cleanupAction)
    {
        _Instance = instance;
        _CleanupAction = cleanupAction;
    }

    public T Instance { get { return _Instance; } }

    public void Dispose()
    {
        if (_CleanupAction != null)
            _CleanupAction();
    }
}

public static class Ownable
{
    public static Ownable<T> Owned<T>(T instance)
        where T : class
    {
        return new Ownable<T>(instance, true);
    }

    public static Ownable<T> Owned<T>(T instance, Action cleanupAction)
        where T : class
    {
        return new Ownable<T>(instance, cleanupAction);
    }

    public static Ownable<T> NotOwned<T>(T instance)
        where T : class
    {
        return new Ownable<T>(instance, false);
    }
}

A: A different note can be made here either.
It depends on what is your MyClass is doing actually.
For example, if we are talking about a class that reads video stream from device, after applies some filters to it and writes data to a user specified file, where file writing is made by stream passed from the outside, say like this:
public class VideoProcessor : IDisposable {
    private FileStream _videoFile = null;
    private VideoProcessor() {}

    //user specified FileStream
    public VideoProcessor(FileStream fs) {_videoFile = fs;}

    public void Dispose() {
        _videoFile.Dispose(); //Dispose user passed FileStream
    }
}

disposing passed stream object during dispose call, makes actually sence.
In other cases, yes, it's better to not destroy object, if you are not an owner of it. Leave it to the caller to decide when it is appropriate time to do that.


text:
Q: What does glOrtho(-1, 1, -1, 1, -1, 1) accomplish? I'm reading the documentation for glOrtho and not understanding it.
I'm looking at this resize code for an 2D drawing and not getting why some of the index are positive and some negative. The drawing is supposed to stay flat so I don't know if its doing what's supposed to:
void reshape(int width, int height)
{

    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1, 1, -1, 1, -1, 1);
   //left, right, bottom, top, nearval, farval
    glMatrixMode(GL_MODELVIEW);

}

A: It's constructing the projection matrix. glOrtho multiplies the current matrix,which is the identity matrix due to the previous statement, by the orthographic projection matrix specified by the function.
Specifically, this call to glOrtho is constructing a matrix that will put world co-ordinates of (-1, -1, -1) at the bottom-left-front of the screen, and world co-ordinates of (1, 1, 1) at the top-right-back of the screen. So if you were to draw the triangle:
glBegin(GL_TRIANGLES);
glVertex3f(-1, -1, 0);
glVertex3f(-1, 1, 0);
glVertex3f(1, -1, 0);
glEnd();

It would cover exactly half of the screen.
Note that if you're only using 2D then the last two parameters aren't that important (although they can be used to control layers). Just draw everything with z=0, and if you need to put something in front of something else then use a higher z value.

A: It actually does nothing except flip the z coordinate. If you plug in your values you'll see that it generates the matrix
1  0  0  0
0  1  0  0
0  0 -1  0
0  0  0  1

Note that it's not the identity matrix because glOrtho is weird stupid (note the minus signs):

(left, bottom, -nearVal) and (right, top, -nearVal) specify the points on the near clipping plane that are mapped to the lower left and upper right corners of the window, respectively, assuming that the eye is located at (0, 0, 0).  -farVal specifies the location of the far clipping plane.

These minus signs mean that fNear and fFar have the opposite meaning.


text:
Q: How to plot the distribution between 2 variables with Plotly Express (Python)? I have a dataframe, which looks like this and contains around 20.000 rows.
print(df)
>>>>
CUSTOMER_INCOME   MARITAL_STATUS
   50000          Relationship
   65000          Single
   17000          Single
   120000         Relationship
   42000          Relationship
   56000          Single

(*MARITAL_STATUS has only these 2 variables: Relationship and Single)
I am trying to use plotly in order visualize the distribution of the 'Customer Income' according to their 'Marital_Status'.
The following code delivers this plot, but it doesn't look right.
px.scatter(df, x = 'Marital_Status', y = "Customer_Income")

How can I plot the distribution of the 'Customer Income' according to their 'Marital_Status' using plotly in a more reasonable way?

A: I think you want to use the color option in using px.histogram. I believe this solves your problem:
fig = px.histogram(df, x="CUSTOMER_INCOME",color="MARITAL_STATUS",barmode="overlay")

Do note that this won't get you distributions (distributions sum to 1), but it will give you a histogram. If you do want that, consider looking at https://plotly.com/python-api-reference/generated/plotly.express.histogram.html to find if the histnorm option is of any use to you.


text:
Q: Why are these the solutions of the diophantine equation? According to my notes:
$$
\begin{align}
& \text{ Let } a,b \text{ not both } 0. \\
& ax+by \text{ has a solution iff } (a,b) \mid c \\
& \text{ If } d:=(a,b) \mid c \text{ and } a=d \cdot a_1 , b=d \cdot b_1 \text{ and } x_1,y_1 \text{ is a solution of } \\
& ax+by=c \text{ , then all the solutions are given by the formulas: } \\
& x=x_1+k \cdot b_1, y=y_1-k \cdot a_1, k \in \mathbb{Z}
\end{align}
$$
I am looking at the solution of this exercise:
Let $a,b \geq 0 , (a,b)=1$ . Show that the diophantine equation $ax-by=c$ has infinite solutions with $x,y>0$.
That is the solution:
Since $(a,b)=1$ , $\exists x_0,y_0 \text{ such that } ax_0+by_0=1 \Rightarrow a(cx_0)-b(-cy_0)=c$
Therefore, $\displaystyle x_1=cx_0 , y_1=-cy_0 \text{ is a solution of } ax-by=c$
The solutions of $ax-by=c$ are described by the formulas:
$$x=cx_0+kb , y=-cy_0+ka, k\in \mathbb{Z}$$
And,as we want $x>0,y>0$, it must be $\displaystyle k> \max\left\{\frac{-cx_0}{b},\frac{cy_0}{a}\right\}$
But...why are these : $x=cx_0+kb , y=-cy_0+ka, k\in \mathbb{Z}$ the solutions of $ax-by=c$,and not $x=cx_0+kb, y=-cy_0-ka$. Doesn't it have to be at one of $x,y$ , minus and at the other one plus???

A: So that $ax-by = \langle\text{stuff with $c$s}\rangle +akb-bka$ and the last two terms cancel.


text:
Q: How can I safely purge the archival contents of /var/log and how do I change log retention policies? The contents of /var/log on my system are now taking up 80% of my hard drive and it's causing a lot of problems.
So I need to purge all the old contents but for some reason sudo rm -rf "*.gz" does not remove those old files.  Also weirdly enough I'm not 100% sure that all the logfiles I can see actually amount to the huge disk usage I'm dealing with.  Why would the Disk Usage Analysis tool show over 600GB used in /var/log when I can't find that much usage with ls?
Also, going forward I'd like to make sure this doesn't happen any more so I want to change the log file retention or rotation policies (however they're named).
EDIT:  The du command shows me that the syslog.1 takes up 597GB.  How do I change the way that whatever makes that log works to avoid this?
Edit2:  I think this link shows the root cause but I don't know what to do about it.  https://www.mail-archive.com/kernel-packages@lists.launchpad.net/msg386959.html

A: Start by examining the log and find what is filling it up. Then fix that issue.
ALL log files in /var/log/ that end in .gz are old compressed log files and can be deleted with
sudo rm -rf *.gz

That will leave the current logs intact. Those SHOULD end in .log.  If a log ending on a digit gets lines added (where it should add them to *.log  you will need to examine the software that adds to this log. There will be a mistake in one of the configuration files.
Make sure the permissions to *.log are correct. That could also be an issue.

*

*syslog should be -rw-r----- 1 root adm

*mysql.log should be -rw-r----- 1 mysql     adm

*apache2 is a directory and should be drwxr-x--- 2 root      adm
The 2 files in there should be -rw-r----- 1 root adm
If you need to empty ACTIVE log files do not use rm but use > /var/log/{logfile}. That will keep the permissions of the file, empty it and keep the file on disk present.


text:
Q: I want to download text inside placeholder,i want this code to work on my chrome extension option page? I want to download text inside placeholder as text file in my chrome extension options page.it is working well in w3schools compiler but not working in chrome extension
here is my code:
<script>
    function downloadFile() {
      let text = document.getElementById("blocked-list").value;
      var blob = new Blob([text], {type: "text/plain"});
      const url = URL.createObjectURL(blob);
      var downloadLink = document.createElement("a");
      downloadLink.href = url;
      downloadLink.download = "export.txt";
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(url);
    }
</script>


text:
Q: Chicken and egg dilemma with linked list implementation I mainly learned about linked lists in the context of C++. Here's a node implementation
struct node
{
  int data;
  node* next;//node IS what is being defined
};

I was taught that the C++ standards make a special exception for this because there is a self reference where the struct being defined has a member that is itself and that's a problem because it's not fully defined. Why is this possible? This screwed me up on an interview question and I need to know if other languages support this. For example I've seen a Java implementation
class Link {
public int data1;
public double data2;
public Link nextLink;

//Link constructor
public Link(int d1, double d2) {
    data1 = d1;
    data2 = d2;
}

//Print Link data
public void printLink() {
    System.out.print("{" + data1 + ", " + data2 + "} ");
}

}
So this seems to support Java makes some sort of "special exception" as well where public Link nextLink; occurs within the implementation of Link. In general do most programing languages have this feature? When can it be used?
So you are always allowed to have:
struct X{
 X* y;
};

and
    Plublic class X
    {
      Public X y;
    }

A: Why wouldn't this be possible? The field of type Link is just a reference, this is no special exception.
In your case, the reference is to an object of same type as the one being defined, but there is no recursion in memory, since the reference is just a pointer. Thus, no technical problem.
You could also say that within the class declaration, the class is not fully defined, yet you use the referenced object's methods and field. But this is exactly the same thing as using methods and fields of this within the class declaration, or even using methods before their own declaration. The compiler deals with it all the time, no worries.
Side note: by the way, the chicken egg came before the chicken, from a bird that was not exactly a chicken.

A: There is no real dilemma here. The next is just a pointer to another "object" of struct. Similarly, Link is just a reference to another object of the same definition.
Since a class is just a definition of what is contained within an object of its type and since there can be many objects, for each class definitions, there can be a reference to an object of the class within the object of another.

A: next is a pointer (4 or 8 bytes in size depending on whether you are on a 32 vs 64 bit system) which holds an address to a location in memory containing an instance of the struct node.  By the time the struct node is compiled, the compiler knows the size of the type and how to lay it out in memory.  At run-time, the 4 or 8-byte pointer will be assigned a value which points to any instance of struct node.  It could be any instance of this type.  In other words, the pointer is a variable used at runtime.  It is not a sort of type definition in-and-of-itself which would lead to a recursive type definition as you describe.


text:
Q: Named Cache Vs Regions I have a following requirement:
1) my cache framework should support Global cache and Application wise(based on country in which application is deployed) cache.
2) Global cache will contains the shared objects for all the applications
3) For the application wise cache, should I use named cache or Regions?  And why?

A: Regions offer searching capabilities, but by limiting cached objects to a single cache host, the use of regions presents a trade-off between functionality and scalability.
Named cache, also referred to as a cache is the default container that spans all cache hosts in the cluster. Even, if there is a limit of 128 named caches, we can find a way to bypass this limit by using a prefix in your cache key.


text:
Q: Colorcells and Rowcolor in spreadtab I wonder how to add some colorcell, rowcolor and so on in this type of table
  \documentclass[a4paper,14pt]{extreport}
  \usepackage{spreadtab}

  \begin{document}
  \begin{spreadtab}{{tabular}{|c|c|c|c|c|c|}}
  \hline
  & @Ammount&   @Buy & @ Sell & @Profit & \\ \hline
  &  & 1& 3 &                           & \\  \hline
  &  &  & 2 &                           & \\ \hline
  \hline
  &  &  & :={ sum(d2:d3) } &            & \\
  \hline
  \end{spreadtab}

  \end{document}

A: It is quite easy to customize styles of tables while using spreadtab if you would like to use tblr environment of tabularray package:
\documentclass[a4paper,14pt]{extreport}
\usepackage{spreadtab}
\usepackage{tabularray}
\usepackage{xcolor}

\begin{document}
\begin{spreadtab}{{tblr}{colspec={|c|c|c|c|c|c|},row{1}={blue9},cell{4}{4}={red8}}}
\hline
& @Ammount&   @Buy & @ Sell & @Profit & \\ \hline
&  & 1& 3 &                           & \\  \hline
&  &  & 2 &                           & \\ \hline
\hline
&  &  & :={ sum(d2:d3) } &            & \\
\hline
\end{spreadtab}

\end{document}


text:
Q: migrations in rails (sqlite) hey I have a small problem with my rake
class CreateEvents < ActiveRecord::Migration

  def self.up
    create_table :events do |t|
      t.integer :broadcast_id
      t.integer :position
      t.string :title
      t.string :location
      t.string :link
      t.text :description
      t.datetime :time
  end
    add_foreign_key :events, :broadcast_id, :broadcasts
  end

  def self.down
    remove_foreign_key :events, :broadcast_id, :broadcasts
    drop_table :events
  end

end

problem => add_foreign_key :events, :broadcast_id, :broadcasts
$ rake db:migrate
== CreateEvents: migrating ===================================================
-- create_table(:events)
-> 0.0021s
-- add_index(:events, :broadcast_id)
-> 0.0004s
rake aborted!
An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: near "FOREIGN": syntax error: ALTER TABLE "events" ADD FOREIGN KEY ("broadcast_id") REFERENCES "broadcasts"(id)

A: Why are you defining foreign keys this way?
If you want a relationship between your Events and Broadcasts then you should look into creating an active record relation. Something like
# Event model
class Event < ActiveRecord::Base
  belongs_to :broadcast
end

# Broadcast model
class Broadcast < ActiveRecord::Base
  has_many :events
end

This way you let rails maintain the foreign key relationship for you. Check out the Rails Guide on active record associations for more info.

A: As of version 3.6.19, SQLite, aka the default development database, supports foreign key constraints, but enforcement of foreign key constraints is turned off by default (for backwards compatibility), to fix it:
Suggested option:
Use another database such as mysql/postgresql as your development
    database in Rails, and below is an example:

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: user
  password: password
  socket: /tmp/mysql.sock
development:
  <<: *shared
  database: db_development

Other options include:

*

*Future versions(4.*) of SQLite has enabled foreign key constraints in default, but as of now, it's not released yet.

*We could also enable foreign key support by the following command:
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys // should print 1
But please note:

*

*it does not persist and you have to do it on every connection;

*If PRAGMA foreign_keys print nothing, it means your version of SQLite does not support foreign key, please upgrade to 3.6.19 or higher version;

*Some says we could enable it in connection string, but I didn't find out the correct string in Rails. You could refer to this answer.


text:
Q: Should I rely on the local phone's time for time sensitive app (Windows Phone 7) I'm building an app where my users will post content.  The exact time of the post is an important data point - I need to know exactly when the user hit the "Post" button.  Once the post has been captured I'll upload that posting to my web server.  My app should still work in offline mode, meaning when there is no internet connectivity the post will be saved locally and uploaded next time the network becomes available.
Question is, how can I guarantee that the time of the post is accurate?  Should I rely on the phone's local time?  Should I try to create some crazy code that regularly sync's the difference between my servers time and the devices time so I can always know the difference (if there is one).  Are there better time management solutions that I'm not aware of?
Thanks,
UPDATE
Here's the server side code that I wrote to ensure that server and client times are perfectly matched.  Hope it helps others...
    /// <summary>
    /// Calculates the actual time the client event occurred.
    /// Takes in account that the event and the sending of the
    /// event may have happened seprately.
    /// </summary>
    public static DateTime CalculateClientEventTime(
        DateTime serverReceiveTime,
        DateTime clientSendTime,
        DateTime clientEventTime)
    {
        // first we need to sync the client and server time
        // we also need to subtract any time zone offsets
        // then we can subtract the actual time on de ice

        DateTime serverReceiveUtc = serverReceiveTime.ToUniversalTime();
        DateTime clientSendUtc = clientSendTime.ToUniversalTime();
        DateTime clientEventUtc = clientEventTime.ToUniversalTime();

        // note: all dates are in utc
        // just need to subtract the client TimeSpan from the client Send
        // then subtract that TimeSpan from the server utc time

        TimeSpan diffBetweenClientEventAndClientSend = (clientSendUtc - clientEventUtc);

        return serverReceiveUtc.Subtract(diffBetweenClientEventAndClientSend);
    }

A: I suggest that you do the following:
In online mode: Take the time from your server when the user post their data.
In offline mode: Save the time from the phone. When going online, submit all saved data, and the current time of the phone. Calculate the difference between the phone and your server time to get the real time.

A: You cannot rely on the phone's time because user can change it and your app can run in diffrent time zones. Use always the sever time or you can get the phone time and calibrate your local timer to get the value of a lag.


text:
Q: Viewing (monitoring) line status of a serial port Is there a utility software (or an easy method to do it from shell script) to display a serial port's status — i. e. blinking "RXD", "TXD", "DCD", "DTR", "DSR", "RTS", "CTS"? Particularly, I need to monitor whether "DCD" line is set most of the time and momentarily cleared on some interval. The port doesn't need to be sniffed, it's okay to open it exclusively.
In DOS and Windows world, it's usual for terminal emulator and other modem-related software to display pin status, either in GUI or in console applications. However, I couldn't find an alternative even for Linux (although some say it may be possible to examine /proc/tty/driver/serial by hand, if it exists), not to mention FreeBSD, which is my actual target. Common tools like cu and minicom only display port settings at most, not the status.

A: AFAIK you can read the DCD pin using ports. According to https://www.freebsd.org/doc/en/articles/serial-uart/, DCD lives in bit 7 of the Modem Status Register (port 0x06+PORT_ADDR). For your application, Bit 3, DDCD probably is better though. It's also possible to hook interrupts, take a look at the Modem Status Change interrupt.

A: Ckermit was a very capable serial/modem communications program for Unix-based computers, but I don't remember if it supported a feature of visually displaying the status of RS232 control pins.  The project slowed down since Columbia U. suspended support for it in 2011, but it seems to be coming back.
I can't tell from www.kermitproject.org whether it has this kind of feature or not.  A number of Linux distros have ckermit packages, perhaps it's worth trying out.


text:
Q: Session start in Joomla using a while loop I have 2 databases, one with Joomla installed and the other with my personal data.
I need to work contemporaneously with these 2 databases.
Now I do a while into my DB with this query:
 $query="Select * From lista where user_id='$id'";
 $result = mysql_query($query) or die(mysql_error());
 while($row=mysql_fetch_array($result))
 {
     $ID_STRUCTURE=$row['ID'];
     ECHO '
Modifica '.$row['struttura'].'
';
     $session =& JFactory::getSession();
     $session->set( 'myvar', $ID_STRUCTURE );
 }

When I go on the page /test/index.php/modifica I use this code:
  $session =& JFactory::getSession();
  $myvar= $session->get('myvar');
  echo $myvar;

I must obtain only the $ID_STRUCTURE of the correspondent $row['struttura'].
If I use an array in the while and a foreach in the other page /test/index.php/modifica, I obtain all the values.
How can I fix it?

A: Don't use the while loop directly. Store it into an array or variable, so you can use it over and over. Now it's returning you the last value because the while loop already ran. So when you call it again, its already at its last record.
$query="Select * FROM `lista` WHERE `user_id` = '$id'";
$result = mysql_query($query) or die(mysql_error());
$a_Array = array();
while($row=mysql_fetch_array($result))
{
    $a_Array['id'] = $row['ID'];
    $a_Array['link'] = '
Modifica '.$row['struttura'].'
';
}
$session =& JFactory::getSession();
$session->set( 'myvar', $a_Array);

NOW USE A foreach() loop to get all the data on the other page. In that array are the values $myvar['id'] and $myvar['link'].
foreach($myvar as $value){
echo $value['id'].$value['link'];
}

A: Of course, because you are always overwrite that in your loop. You need to create an array, or make the key to be unique.
while ($row = mysqli_fetch_array($result)) {
    $ID_STRUCTURE = $row['ID'];
    ECHO '
Modifica ' . $row['struttura'] . '
';
    $myvarArray[] = $ID_STRUCTURE;
}
$session = & JFactory::getSession();
$session->set('myvar', $myvarArray);

Use mysqli or PDO instead mysql functions since they are deprecated.


text:
Q: How to remove some part of the URL in the address bar of the browser I try to remove a part of my url in the addressbar of the browser via javascript.
but I don't understand why it's not working, if I test it in the console the result is correct but it still does not change in the address bar.
How can I do it?
url I have:http://localhost:8090/Home/Index?x=72482&success=itsdone
url I want is:
http://localhost:8888/Home/Index?x=72482

here is my javascript code:
window.location.href.replace('&', '#');
window.location.hash = "";

A: replace doesn't change the string on which you call it (strings are immutable), it returns a new one.
To replace & with #, do
window.location = window.location.href.replace('&', '#');

If you want to remove everything from the first &, the best is to use a regular expression :
window.location = window.location.replace(/&.*$/,'');

If what you want is to retain the x parameter, then you should rebuild the location to ensure it's still OK if the parameters are in a different order in the URL :
window.location = window.location.replace(/([^?]*).*(\?|&)(x=)([^&]+).*/, "$1?$3$4")

This changes
"http://localhost:8888/Home/Index?a=2&x=72482&c=3"

or
"http://localhost:8888/Home/Index?x=72482&success=itsdone"

into
"http://localhost:8888/Home/Index?x=72482"

A: window.location will cause a page reload. to change the port too use this
window.location = window.location.protocol
                + "//"
                + window.location.host
                + ":8888/"
                + window.location.pathname
                + window.location.search.substr(0, window.location.search.indexOf('&')-1)

A: Is there a particular reason why you are passing isDone as a QueryString parameter if you do not even need it? Wouldn't it be easier to not even pass it to begin with and have the page decide if you are done?


text:
Q: Any ideas on why a "flutter install" to an android device doesn't show anything but "flutter run" works fine I have a large / fairly complex Flutter application we've been writing for a few months.  Soo -- we've been running against the simulator etc and on real-devices with flutter run (via usb cable) on various Android devices without issue ..
However, to publish we obviously have to create a APK package etc.  This is where it gets odd --
A "flutter install" of the same build that "flutter run" works fine does not show any artifacts on the device, either emulator or physical. There is no Icon that shows up (our custom one) - - no app shows in the "App List" .. However, in the Settings -> Apps   one DOES see our application listed .. but it doesn't do anything when tapped ...
We're sort of wits end here -- oh, and everything works just fine w/ iOS .. we can publish with TestFlight no problems.. so the issue is pure Android ..
We are pretty sure it must be something to do with the the Manifest.xml file .. but we've been looking at it and looking at it and nothing is popping out that, to us, explains this behavior.  Why does "flutter run" work and "flutter install" does not?
And it's not just my environment -- any of the other 3 programmers have the exact same issue / problem .. and "flutter doctor -v" is all green and again, "flutter run" works as expected (i.e. the app is installed and launched and runs) ..
Has anyone seen this?  Any ideas on how to debug what Android isn't liking in the package?  We're sort of newbie Android developers with just know enough knowledge to be dangerous :)
TIA!

A: OK -- so here is the actual answer -- the problem WAS the Manifest .. I had the intent-filter section rather wrong when I added deep-links and created an "impossible" intent that couldn't be ever satisfied.
Old Manifest.xml intent:
<intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
    <!-- Deep Links -->
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="missionmode4" />
</intent-filter>

The intent-filter is AND logic .. creating an impossible Intent .. the new and working version is:
<intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
 </intent-filter>
 <!-- Deep Links -->
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="missionmode4" />
</intent-filter>

That creates two separate intent filters .. one for the launcher and then one for the deep links as desired.
Voila!


text:
Q: MVC EditorFor Custom Helper I am trying to create a custom helper for EditorFor. I want to take the string lengths from the models and add this to the html attributes.
I have the following so far but this doesnt apply the new attributes that are added.
    public static IHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object ViewData, bool disabled = false, bool visible = true)
    {
        var member = expression.Body as MemberExpression;
        var stringLength = member.Member.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;

        RouteValueDictionary viewData =  HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData);
        RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(viewData["htmlAttributes"]);

        if (stringLength != null)
        {
            htmlAttributes.Add("maxlength", stringLength.MaximumLength);
        }

        return htmlHelper.EditorFor(expression, ViewData);
    }

A: You're returning original ViewData attribute in method parameter instead of custom HTML attributes collection on return htmlHelper.EditorFor(expression, ViewData). Based from this answer, your return method should changed to this:
public static IHtmlString MyEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object ViewData, bool disabled = false, bool visible = true)
{
    var member = expression.Body as MemberExpression;
    var stringLength = member.Member.GetCustomAttributes(typeof(StringLengthAttribute), false).FirstOrDefault() as StringLengthAttribute;

    RouteValueDictionary viewData =  HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData);
    RouteValueDictionary htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(viewData["htmlAttributes"]);

    if (stringLength != null)
    {
        htmlAttributes.Add("maxlength", stringLength.MaximumLength);
    }

    return htmlHelper.EditorFor(expression, htmlAttributes); // use custom HTML attributes here
}

Then, apply custom HTML helper on view side like this:
@Html.MyEditorFor(model => model.Property, new { htmlAttributes = new { @maxlength = "10" }})

Edit:
This method works on MVC 5 (5.1) and above, I can't sure it works in earlier versions (refer this question: Html attributes for EditorFor() in ASP.NET MVC).
For earlier MVC versions, usage of HtmlHelper.TextBoxFor is more preferred, which certainly has maxlength attribute:
return htmlHelper.TextBoxFor(expression, htmlAttributes);

Additional references:
Set the class attribute to Html.EditorFor in ASP.NET MVC Razor View
HTML.EditorFor adding class not working


text:
Q: Get correct return type value in our factory loader pattern The following example is working (in JavaScript), but I can't get the correct return types in TypeScript working. Depending on the factory object, is should know the correct return type of the "func" function.
We want to use this pattern for dynamically add and get DataLoaders.
class Dog {
  bark() { console.log("wuff")}
}
class Cat {
  miau() { console.log("miau")}
}

class FactoryItem<T extends () => {}> {
  constructor(public func: T) {}
}

class Factories {
  factories = new Map();

  add<T extends () => {}> (factories: FactoryItem<T>) {
    this.factories.set(factories,factories.func())
  }

  get<T extends FactoryItem<()=>{}>>(factory:T):ReturnType<typeof factory.func> {  // this is not working
    return this.factories.get(factory)
  }
}

const factoryA = new FactoryItem(() => new Dog());
const factoryB = new FactoryItem(() => new Cat());

const factories = new Factories();
factories.add(factoryA)
factories.add(factoryB)

factories.get(factoryA).bark(); // typescript is not happy
//factorys.get(factoryB).bark(); // this must fail
factories.get(factoryB).miau(); // typescript is not happy

A: In this function's return type-
  get<T extends FactoryItem<()=>{}>>(factory: T):ReturnType<typeof factory.func> {  // this is not working
    return this.factories.get(factory)
  }

You're claiming that the return type of get is the return type of factory.func - but this is just a constant type that is not dependent on the generic type.
If you want your return type to be influenced by the generic type - you must use the generic type, aka T-
  get<T extends FactoryItem<()=>{}>>(factory: T):ReturnType<T['func']> {
    return this.factories.get(factory)
  }

Remember, the context of the generic during usage of the generic function is only captured by the generic type (in this case T) - so any time you want to construct a type based on the captured context, you need to do that in terms of the generic type parameter (in this case T).
Here's a playground link


text:
Q: Boundedness of a function of two variables Let us consider the function from $\mathbb R^2$ to $\mathbb R$ defined by  $\phi(\alpha,\beta) = \frac{\alpha \beta}{\sqrt{\alpha ^4 + \beta ^4}}$ and $0$ otherwise.
If we look at the graph using Geogebra, then it is clearly bounded. However, proving this is the case feels like it requires a large number of cases, and it feels as though this is the incorrect approach.
It is trivial to show that when $\alpha = \beta$, then the function is bounded. Although from this point, it feels like a difficult process to bound the function in a simple way without introducing multiple cases for when $\alpha$ and $\beta$ are positive / negative / different and also when they are different combinations of $| \alpha | < 1$ and $| \beta | < 1$.
Is there a simpler solution to the problem, or would bounding this require all of the cases that I listed above?

A: We use the fundamental inequality $ab\leq\frac{a^2+b^2}2$ for $a,b\geq0$.
We have
\begin{align*}
|\phi(\alpha,\beta)|&=\frac{|\alpha| |\beta|}{\sqrt{\alpha ^4 + \beta ^4}}=\frac{\sqrt{|\alpha|^2 |\beta|^2}}{\sqrt{\alpha ^4 + \beta ^4}}=\frac1{\sqrt{\alpha ^4 + \beta ^4}}\cdot\sqrt{|\alpha|^2 |\beta|^2}\\
&\leq\frac1{\sqrt{\alpha ^4 + \beta ^4}}\cdot\sqrt{\frac{|\alpha|^4+|\beta|^4}2}=\sqrt{\frac12},\ \ \ (\alpha,\beta)\neq(0,0).
\end{align*}

A: We may also rewrite
$$
\phi(\alpha,\beta) = \frac{\beta/\alpha}{\sqrt{1+(\beta/\alpha)^4}}.
$$
This is a function of one variable $t:=\beta/\alpha$, which should be amenable to standard elementary methods.
In fact, let $f(t)=\frac{t}{\sqrt{1+t^4}}$. Then
$$
|f(t)| = \frac{1}{\sqrt{t^{-2}+t^2}}.
$$
It is enough to show that $t^{-2}+t^2$ is bounded below by a positive constant, which reduces further to analyzing $u^{-1}+u$ for $u>0$. It's elementary to show that $u^{-1}+u$ has a global minimum (for $u>0$) at $u=1$ with value $2$. Backtracking all the way back, we may conclude that
$$
|\phi(\alpha,\beta)| = |f(\beta/\alpha)|\le \frac{1}{\sqrt{2}},
$$
with equality exactly when $\alpha=\pm\beta$.
(Of course, $\alpha=0$ or $\beta=0$ are special trivial cases not covered by the above).