text:
Q: Making a tag suggestion using jQuery chosen plugin I am using jquery chosen plugin https://github.com/harvesthq/chosen/ to make my select form fields pretty. Here is the demo page for chosen plugin https://github.com/harvesthq/chosen
I was thinking if it is possible to make tags like stackoverflow using chosen plugin because some of its feature looks alike. I am also like to know how do i use chosen with ajax to add tag suggestions.
I could use one of those jquery tags out there but i would like to know if i can do it using chosen so i don't need to add another script with my page.
Let me know if you need to know anything more.

A: All that you have to do is to modify the select box with an ajax request. Than use :
$("#form_field").trigger("list:updated");
to tell "chosen" that the list has been updated.

A: Yes, all of what you ask is possible. From my answer to "Is there a way to dynamically ajax add elements through jquery chosen plugin?":

Take a look at the neat Select2 plugin, which is based on Chosen itself and supports remote data sources (aka AJAX data) and infinite scrolling.

A: The koenpunt fork of chosen has the functionality you want. More info here


text:
Q: Weird behaviour of DownloadFileAsync (WebClient) I have a simple script for downloading/uploading files to FTP. It worked just fine on Unity 2018.1.9f1, but recently I updated Unity to 2018.4.5f1 and DownloadFileAsyn got broken. It writes an empty file with error "Server returned an error: 550  No such file or directory". The file is there, the permissions are correct(I'm sure of it, because my UploadFile method still works fine). I wrote a new method using FtpWebRequest(same credentials, file path etc.), and guess what - it works fine too! But WebClient download is broken.
My DownloadFileAsync method:
    public void DownloadFile(string FilePath)
    {
        Debug.Log("Download Path: " + FilePath);

        WebClient client = new System.Net.WebClient();
        Uri uri = new Uri(FTPHost + new FileInfo(FilePath).Name);

        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(OnFileDownloadProgressChanged);
        client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(OnFileDownloadCompleted);

        client.QueryString.Add("filename", FilePath);
        client.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword);
        client.DownloadFileAsync(uri, Application.persistentDataPath + "/" + FilePath);
    }

My new download method using FtpWebRequest(it works, but i prefer WebClient):
public void DownloadFileNew(string FilePath)
{
    Uri uri = new Uri(FTPHost + new FileInfo(FilePath).Name);

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);

    using (Stream ftpStream = request.GetResponse().GetResponseStream())
    using (Stream fileStream = File.Create(god.persPath + "/" + FilePath))
    {
        ftpStream.CopyTo(fileStream);
    }

    reader.Close();
    response.Close();
}

And finally UploadFile method using WebClient that still works fine:
public void UploadFile(string FilePath)
{
    FilePath = Application.persistentDataPath + "/" + FilePath;
    Debug.Log("Upload Path: " + FilePath);

    WebClient client = new System.Net.WebClient();
    Uri uri = new Uri(FTPHost + new FileInfo(FilePath).Name);

    client.UploadProgressChanged += new UploadProgressChangedEventHandler(OnFileUploadProgressChanged);
    client.UploadFileCompleted += new UploadFileCompletedEventHandler(OnFileUploadCompleted);
    client.Credentials = new System.Net.NetworkCredential(FTPUserName, FTPPassword);

    client.UploadFileAsync(uri, "STOR", FilePath);
}

A: I found an answer.
client.QueryString.Add("filename", FilePath);

Somehow, the problem is in that line. I used it to identify what file I downloaded in OnFileDownloadCompleted.
userToken seems like a better option for this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best method to create HD graphics for android games Is there a good method to create HD like graphics for regular 480x800 devices as well as tablets? So far I can create HD like graphics for only 480x800 devices. And since i'm using OpenGL i place all of my graphics in the assets folder. My images are in the 480x800 format. I have thought of multiple ways and they are listed below.

*

*I tried using 480x800 graphics and using OpenGL to stretch it to a tablet with GL_LINEAR. As expected, the graphics were great on the 480x800 devices and average if not poor on the tablet.

*I have not tried this but I believe this to be a good method (need clarification). Using seamless textures and creating my background from those. (problem with this is that my character would become non-HD like).

*(Soon to be tried) Using the res folder instead of the assets folder. Seperating tablet graphics and phone graphics. However, i have not come up with a good method to place these graphics in identical places with OpenGL. [need clarification on this :)]
What are some of your good methods to create HD games for both 480x800, 480x854 and tablets?

A: The answer is the one you probably expected - for the best results you should create images of different sizes and use the most appropriate set.


text:
Q: Why coping an image into a new variable doesn't copy data but pointer? When i do something lile this:
BufferedImage image = otherImage;

and  image got affected otherImage get affected too?

A: This is how java memory model works.
All objects placed in a heap. In your methods frames you only have an access to link that refers to this objects. You can manipulate with objects via this links.
Statement that you posted says that you want take the second link and refer it to the same object as first link refers.
In case you need to copy object you need to care about that by yourself. There are a few ways to achieve this.
For example you can make some copying method that will take initial object, take it's fields, create a new instance, and set fields of this newly created object to previous extracted ones.
UPD: Take a look into this. There are explanations for your concrete case with BufferedImage. But seems like the question need to be updated and marked as duplicate.


text:
Q: Will Nest.js dynamic cron jobs be deleted after a restart or shutdown? So I developed a system with Nest.js which is able to create a dynamic cronjob from a user's input in the frontend application, I store this data in my database and at the same time I create the job in the server with the Dynamic schedule module API. Today I was wondering what would happen to my cronjobs if my server was shutdown or if it restarted itself, since my jobs aren't declarative and they are created at runtime I think that maybe when my server starts I should create the cronjobs again? I'm not sure if this get stored in memory or something since it's not in the documentation.
My concern, in fewer words, is:
Should I recreate my jobs using the information from the database once the server starts itself? Why yes or why not?

A: Once the server restarts, you'll have to restart your CRON tasks.
The reason for this is that your NestJS application is not really adding CRON expressions to a crontab on the machine but instead scheduling and running these tasks in a CRON expression capable task runner (package example: node-cron)
Once the server stops, the scheduler (that runs on the same process) also stops.
You've mentioned you already store the tasks in a database, so you should be able to get the information you need to recreate the task on server init.
I assume you have a Service that handles CRON tasks and has access to the DB. Otherwise you can just create a dedicated one
You can modify it to implement the OnModuleInit interface and execute logic that would read all the existing tasks that should run and start them:
@Injectable()
class CronService implements OnModuleInit {
  constructor(private readonly cronRepository: CronRepository) {}

  /*
    ...
    CRON IMPLEMENTATION
    ...
  */

  private async restartSavedCronTasks(): Promise<void> {
    // get date from DB and start all relevant tasks
  }

  async onModuleInit: Promise<void> {
    await this.restartSavedCronTasks();
  }
}

A: The answer is yes, you should recreate the cron jobs after the server restarts.
It's best that once the user's creates the cron job, you'll store it in the DB or use the DB you already use for Frontend.

A: In general, you could have two levels of persistence of this data in case of necessity.
Scenario 1
You very seldom restart your servers. In this case, store to something persistent like a json file in an s3 bucket (not public) or to a sql or mongo database if you have it connected.
Recreate the "unhandled" or relevant cron jobs on server warmup.
Scenario 2
You often restart your servers/services. In this case, perhaps store to an in-memory db like Redis as well as a more persistent type (in case your Redis db falls and you need to repopulate it - provided that this data is important).
Recreate the "unhandled" or relevant cron jobs on server warmup.
Storing to Redis in general instead of storing in-memory on a specific server instance will also allow your general architecture to be more scalable as a different server can read from Redis as well (same "source of truth")
I hope this helps you plan your architecture accordingly :)


text:
Q: Obtener ultima fila de datos en una consulta tengo la siguiente consulta
SELECT
    num_cotizacion,
    CONCAT(num_cotizacion,'-',num_modificacion) AS correlativo,
    nombre_contacto,
    cargo_contacto,
    rut_empresa,
    razon_social,
    fecha_registro,
    IF( estado_cotizacion = 1,'Aceptado',IF ( estado_cotizacion = 2, 'Rechazado', 'Pendiente')) AS estado_cotizacion,
    IF( estado_solicitud = 1,'Aceptado',IF ( estado_solicitud = 2, 'Rechazado', IF ( estado_solicitud = 3, 'Pendiente', 'N/A'))) AS estado_solicitud,
    IF( estado_enviado = 0,'NO', 'SI') AS estado_enviado,
    IF(DATE_ADD( fecha_registro,INTERVAL  dias_vencimiento DAY) <= now(),'SI','NO') AS vencimiento FROM
    cot_cabedoc_hist /*GROUP BY num_cotizacion*/ ORDER BY fecha_registro ASC

Lo que quiero es mostrar todos los registros agrupados por el num_cotizacion pero con los datos del último número num_modificacion (correlativo).
Por ejemplo, el num_cotizacion 1 tiene dos correlativos 1-1 y 1-2, lo cual quiero que se muestre solo la fila 1-2 con sus datos.

A: Como no indicas si la tabla cot_cabedoc_hist tiene una columna con un id único para cada registro, lo que podrías hacer es:

*

*Buscar los registros agrupados por num_cotizacion y su MAX(num_modificacion) (Consulta A)

*Unir dichos resultados a la tabla cot_cabedoc_hist donde sus num_cotizacion y num_modificacion coincidan (JOIN B).

*Para que la unión sea más eficiente, es mejor crear un indice sobre ambas columnas.
ALTER TABLE cot_cabedoc_hist ADD INDEX (`num_cotizacion`, `num_modificacion`);

Ejemplo:
SELECT
    num_cotizacion,
    CONCAT(num_cotizacion,'-',num_modificacion) AS correlativo,
    nombre_contacto,
    cargo_contacto,
    rut_empresa,
    razon_social,
    fecha_registro,
    IF( estado_cotizacion = 1,'Aceptado',IF ( estado_cotizacion = 2, 'Rechazado', 'Pendiente')) AS estado_cotizacion,
    IF( estado_solicitud = 1,'Aceptado',IF ( estado_solicitud = 2, 'Rechazado', IF ( estado_solicitud = 3, 'Pendiente', 'N/A'))) AS estado_solicitud,
    IF( estado_enviado = 0,'NO', 'SI') AS estado_enviado,
    IF(DATE_ADD( fecha_registro,INTERVAL  dias_vencimiento DAY) <= now(),'SI','NO') AS vencimiento
FROM (
    SELECT num_cotizacion,
        MAX(num_modificacion) AS num_modificacion
    FROM cot_cabedoc_hist
    GROUP BY num_cotizacion
) AS A
    INNER JOIN cot_cabedoc_hist AS B
       USING (`num_cotizacion`, `num_modificacion`)
ORDER BY fecha_registro ASC

Demo

A: Con base en los resultados que muestras de primera instancia no podríamos hacer un GROUP BY ya que algunos de los elementos en las celdas no son los mismos aunque pertenecen al mismo numero_cotizacion.
Dicho lo anterior lo que podemos hacer es trabajar con:
GROUP_CONCAT

Esta función de MySQL y presente también en MariaDB nos permitirá agrupar concatenando valores que incluso podemos separar por algún símbolo.
Dado eso y entonces conociendo que tenemos columnas como:

*

*correlativo

*nombre_contacto

*cargo_contacto

Deberás por cada una de ellas hacer uso de dicha función y pasarla como argumento  y opcionalmente SEPARATOR indicando entre comillas que valor separará cada uno de los registros que se concentren ahí.
Ejemplo
GROUP_CONCAT(correlativo SEPARATOR '/')

Fuente de consulta

*

*Función GROUP_CONCAT


text:
Q: Some items doesn't display on iPad Pro Some items doesn't display on iPad Air.
If you check this page: https://xposed-837fc.web.app/magazin-online
Under the "Profesionalism. Promptitudine. Perfectionare.", you shall find some projects with their images. But on iPad Air doesn't display.
I tested it on Chrome for all dimensions and they appear, even with the iPad Pro emulator, which has almost the same specs with the Air and it works.
But on the iPad Air doesn't.
Do someone know why?
I can't find any logical explanation
iPad Air

iPar Pro Emulator from Chrome

Projects Map Component
function ProjectsMap({ projects }) {
  const sectionData = {
    title: "Profesionalism. Promptitudine. endl Perfectionare.",
    subtitle: "PORTOFOLIU",
    description:
      "Oferim servicii de programare de inalta calitate. Fie ca vorbim de un simplu site de prezentare sau de o Aplicatie Mobila, proiectul tau are aceeasi importanta pentru noi. Facem ideea ta sa fie realitate in cel mai scurt timp posibil. Avem grija la toate detaliile proiectului tau. Produsul final va fi exact ceea ce iti doresti. Ne place sa invatam lucruri noi. In fiecare zi, ne perfectionam in ceea ce stim deja. Suntem deschisi intotdeauna la noile trenduri ale industriei si dornici sa ne adaptam.",
  }

  return (

      <TextSection data={sectionData} />

        {projects.map(project => {
          return (
            <Link
              style={{ backgroundImage: `url(${project.picture})` }}
              className="projects__item"
              key={project.title}>

                {project.title}

            </Link>
          )
        })}

  )
}

SCSS
.projects {
  padding: 100px 90px;

  &__container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
  }

  &__item {
    width: 50%;
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: center;
    aspect-ratio: 16 / 9;
    transition: all 1.2s;

    &:hover {
      background-size: 130%;
    }

    &__overlay {
      position: relative;
      width: 100%;
      height: 100%;
      z-index: 1;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background-color: rgba(0, 0, 0, 0.5);
        background-size: 150% !important;

        span {
          display: block;
        }
      }

      span {
        display: none;
        color: #fff;
        font-size: 36px;
        text-shadow: 0px 3px 5px gray;
      }
    }
  }
}

@media (max-width: 990px) {
  .projects {
    padding: 100px 30px;

    &__container {
      grid-template-columns: 100%;
    }
  }
}

@media (max-width: 600px) {
  .projects__item {
    width: 100%;
  }
}

A: aspect-ratio is not supported in your version of Safari for iOS. It will be available in Version 15.
You can use this padding trick in the interim.


text:
Q: How to properly extend HTMLImageElement Extending HTMLImageElement directly works okay for Chrome, Firefox etc.
export default class CustomImg extends HTMLImageElement {
    constructor() {
        super();
    }
}

However it does not work at Safari which says super() is an illegal constructor. According to MDN Image() is the proper constructor for HTMLImageElement (https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement). I tried to extend Image as well. However even though it does not print out any errors, it just does not behave as a CustomElement.
Any ideas on how to create a custom element on top of HTMLImageElement that can work for both Chrome and Safari?

A: There are 2 different flavored Web Components:
details see Web Components : extending native elements

*

*Autonomous Elements (extend from HTMLElement)

*Customized Built-In Elements (extend from any Element)

But Apple/WebKit will not implement the latter as stated in 2016:
https://github.com/WICG/webcomponents/issues/509


text:
Q: MERN contact form showing undefined values on the backend. Using sendgrid for email I have a contact form in my application (tech stack MERN) and the form sends the data perfectly fine and it hits the route. But on the backend the req shows as undefined. I am using sendgrid to send myself the email, and it sends the email successfully but the message, name, etc are undefined.
This is my form:
import { useState } from 'react'
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import ContactService from '../services/contact.service';
import {
  Button,
  FormControl,
  Container,
  CircularProgress,
  OutlinedInput,
  Paper,
  TextField,
  InputAdornment,
  Box,
  Typography,
  ImageList,
  ImageListItem,
} from "@mui/material";

const ContactForm = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: '',
  });
  const navigate = useNavigate();

  const handleChange = (e) => {
    setFormData((prev) => ({ ...prev, [e.target.name]: e.target.value }));
    console.log(formData)
  };

  async function handleSubmit(e, from='/') {
    e.preventDefault();
    const contactForm = new FormData();

    contactForm.append("name", formData.name);
    contactForm.append("message", formData.message);
    contactForm.append("email", formData.email);
    await ContactService.contact(contactForm);
    navigate(from, {
      state: {
        type: "success",
        message: `Message sent!`,
      },
      replace: true,
    });
  };

    return (
        <>

Send us a
 message

                <input class="w-full bg-gray-100 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline"
            type="text" placeholder="First Name*" name='name' onChange={handleChange}/>
                <input class="w-full bg-gray-100 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline"
            type="email" placeholder="Email*" name='email' onChange={handleChange}/>
                <input class="w-full bg-gray-100 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline"
            type="number" placeholder="Phone*" />

                    <textarea name='message' onChange={handleChange} placeholder="Message*" class="w-full h-32 bg-gray-100 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline"></textarea>

                    <button onClick={handleSubmit} class="uppercase text-sm font-bold tracking-wide bg-blue-900 text-gray-100 p-3 rounded-lg w-full
                      focus:outline-none focus:shadow-outline">
            Send Message
          </button>

Drop in our office

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam
                        tincidunt arcu diam,
                        eu feugiat felis fermentum id. Curabitur vitae nibh viverra, auctor turpis sed, scelerisque ex.

Main Office

5555 Tailwind RD, Pleasant Grove, UT 73533

Call Us

Tel: xxx-xxx-xxx

Fax: xxx-xxx-xxx

        </>
    )
}

export default ContactForm

This is my service:
import http from "../utils/http-common";

class ContactService {
    contact(formData) {
        return http.post("/contact", formData);
      }

}

export default new ContactService();

And my http-common:
import axios from "axios";

var url;
process.env.NODE_ENV === "production"
  ? (url = "")
  : (url = "http://localhost:5000");
export default axios.create({
    baseURL: url,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: true,
});

Finally this is the route that is being successfully hit:

module.exports.contact = async (req, res, next) => {
    const { email, name, message } = req.body;
    console.log(req.body,
        req.params)

    const sgMail = require('@sendgrid/mail')
    sgMail.setApiKey(process.env.SENDGRID_API_KEY)
    const msg = {
      to: 'test@example.com', // Change to your recipient
      from: 'test@example.com', // Change to your verified sender
      subject: `${email}`,
      text: `${message}`,
      html: `<p>${message}</p>`,
    }
    sgMail
      .send(msg)
      .then(() => {
        console.log('Email sent')
      })
      .catch((error) => {
        console.error(error)
      })
}

I tried using a different form style, sending the request directly using axios without the service, logging the request to diagnose the problem (the data is 100% sent properly from the frontend).


text:
Q: Quotient metric on compact homogeneous spaces Suppose $G$ is a compact Lie group, $K$ a closed Lie subgroup and $\langle\cdot,\cdot\rangle$ is a Riemannian metric on $G$ that is either

*

*$G$-bi-invariant
or

*$G$-left-invariant and $K$-right-invariant.

Note that since $G$ and thus $K$ is compact, we can find such metrics by averaging left-invariant metrics by right-translations by elements of either $G$ or $K$.
Let $M=G/K$ (this is a homogeneous $G$-space) and let $\pi\colon G\to M$ be the projection which sends $g$ to the coset $gK$.
The subgroup $K$ acts on $G$ from the right by right multiplication: $G\times K\to G, (g,k)\mapsto R_k(g)=g\cdot k=gk$.
In the language of e.g. [Lee, p.23] this action is

*

*vertical, i.e. $\pi(R_k(g))=\pi(g)$ for all $g\in G$ and $k\in K$.

*transitive on fibers, i.e. for every $g,h\in G$ with $\pi(g)=\pi(h)$ there is $k$ (here $=g^{-1}h)\in K$ such that $R_k(g)=h$.

*and isometric, i.e. the map $G\to G, g\mapsto R_k(g)$ is an isometry for every $k\in K$.

The first two properties hold by definition of $\pi$ and the last one holds because the metric on $G$ is supposed to be at least $K$-right-invariant.
Then [Lee, Thm. 2.28] states that there is a unique Riemannian metric on $M$ such that $\pi$ turns into a smooth Riemannian submersion.
Furthermore, one easily sees that this quotient metric is $G$-invariant.

Question 1:
If $G=O(n)$ and $K=O(n-1)$ then $M=\mathbb{S}^{n-1}$. If I'm not mistaken than the quotient metric resulting from property (2) is exactly the usual round metric on the sphere.
What is the quotient metric resulting from property (1)?
Question 2:
"How different" are the quotient metrics resulting from property (1) and (2) in general? Can this be quantified?
Somehow it feels like property (1) should lead to something "worse" because the isometry group of $G$ is bigger than the one for property (2) and thus taking the quotient by $K$ should lead to more elements in the resulting isometry group.
The questions arose because in my application I have two subgroups of $G=O(n)$, namely $K=O(n-1)$ and $L=O(k)\times O(n-k)$. Hence to get metrics on both quotients I would like to choose one Riemannian metric on $G$, i.e. fulfilling property (1) rather than choosing two different metrics on $G$ which fulfil property (2), respectively.
So, hopefully, the answer to Q2 is "not very different" or so?

[Lee] Lee, Introduction to Riemannian manifolds, 2nd ed.

A: Regarding Q1: (1) implies (2): Each biinvariant metric is also $G$-left invariant and right $K$-invariant for each $K< G$. In the example of $G=O(n), K=O(n-1)$, the resulting metric is isometric to the induced metric on a round sphere in $E^n$ of some radius.
I am not sure what exactly you mean by Q2: This class of metrics given by (2) is, in general, much larger than by (1). A good example to consider is $G=SU(2)$ and $K=\{1\}$. Then $G/K=G$ is diffeomorphic to $S^3$. However, most metrics arising from (2) will not have constant curvature. Interesting examples of metrics on $S^3$ obtained this way (assuming that the metrics are right $SO(2)$-invariant) are "Berger spheres".  This is a 1-parameter family $g_t$ of  homogeneous Riemannian metrics on $S^3$ (with $g_1$ having constant curvature) admitting foliations by closed geodesics (fibers of a Hopf fibration), the common lengths these geodesics is $L_t$, and $\lim_{t\to 0} L_t=0$.


text:
Q: AWS: free 3rd level DNS name to access EC2 instance When I start EC2 instance it receives public new DNS name like ec2-xx-xx-xx-xx.compute-1.amazonaws.com.
Problem is this name is simply a shortcut for xx.xx.xx.xx, and it changes upon next instance restart. This means I need to update this name in my scripts.
Is there a way to assign a meaningful name for an instance, so that it will work as normal DNS name and survive server restarts? For example
my-site1-instance.compute-1.amazonaws.com.
Route 53 is good for public DNS names like site1.com but you have to pay for each name. I would be happily satisfied with a free 3rd level domains.

A: You could install a no-ip.com client on the instance and have it update a hostname at no-ip.com (or any other dynamic dns service).
An alternative would be to assign an EIP to the instance which is free if the instance is running and costs a little ($0.005/h) if the instance is down.
This way you can setup a DNS A record wherever you have your domains configured already.


text:
Q: Table dynamic loading SAPUI5 / UI5 I want to display a huge set of data in a SAPUI5-Table component. I used to implement these datatables with dynamically loading, which means that the table initially loaded ~50 records. After the user scrolled down far enough, the next set of 50 records were loaded into the table. This way it was possible for me to display a table of more than 160.000 entries without any performance issues.
Now I need to do the same with SAPUI5-Table. I already implemented the server side, the OData service is ready to use. I already implemented the clientside but without that dynamic loading. The page always tries to load all records out of the database.
How can i achieve this? Is there any premade way to implement this? I know that the OData service can be called with various parameters which specify the dataset it will deliver, but i dont know how to make the table to these calls while scrolling?

A: Generally, a table bound to an OData Model does the most of it for you.
If you´re using sap.m.Table you can take a look at the growing properties here.
An example on how to use paging with a sap.m.Table can be found in the Explored app in the List section.
Using sap.ui.table.Table the threshold property controls the fetch size and is described here. Additionally you can choose a navigationMode. It can be a Paginator as well as a Scrollbar.
A very simple example for sap.ui.table.Table looks like this:
var oModel = new sap.ui.model.odata.ODataModel("<yourURL>", true);
var oTable = new sap.ui.table.Table({
          columns : [], //set up columns as usual
          threshold : 50 //your fetch size here
});
oTable.setModel(oModel).bindRows("/<yourEntity>");


text:
Q: Functions implicitly taking in arguments I am just curious as to why the function below works perfectly fine, although in its definition we can't see any arguments defined?
This does not seem to be intuitive to a starting JS developer.
const add = () => {
    return num => {
        const result = num + 10;
        return `Calculated! ${result}`;
    };
};

const addFn = add()
console.log(addFn(5)) // Calculated! 15

A: You're partially right. add takes no arguments.  If you supply any, they will be ignored.
But when you call add, you get back the function
num => {
    const result = num + 10;
    return `Calculated! ${result}`;
}

which might be easier to recognize as a function if you wrapped its single argument in parentheses:
(num) => {
    const result = num + 10;
    return `Calculated! ${result}`;
}

This new function takes (presumably) a number, adds 10 to it, and returns a formatted string including that result.
So this:
const addFn = add()

simply assigns the value of addFn as this function returned by add (), namely the function we describe above.
When we call it with 5, it returns that formatted string involving  the result of 10 + 5.
Does that make it any clearer?


text:
Q: If ElseIf Else error in random events code Here is my full code, This worked perfectly fine when I had all elseif as if and all else as elseif.
But I need the first if statement to run before anything. that way if they had less then the minimum turns they will not be aloud to continue.
here is the error i am getting...
Parse error: syntax error, unexpected T_ELSEIF
CODE
<?php

$ingame = "*";
require 'includes/header.php';
include 'includes/modzoideditables.php';
include 'includes/zoideditables.php';
include 'includes/offdefvalues.php';
$turns = 5;
$turns2 = 10;
$zoidmany = 1;
$zoidmany2 = 2;
$excav1 = 1;
$excav2 = 0;
$goldgive1 = 500;
$goldgive2 = 700;
$goldgive3 = 1000;
$goldgive4 = 1500;
$goldgive5 = 2000;
$fight1 = 20000;
$fight2 = 27000;
$fight3 = 31000;
$goldtake1 = 250;
$goldtake2 = 500;
$goldtake3 = 750;
$goldtake4 = 1000;
$miner = 5;

    $rand = rand( 1, 22 );
if ( $turns > $user['uAttackTurns'] ) {
        echo "You don't have enough turns.";
}
    $rand = rand( 1, 22 );
 elseif ( $excav1 > $user['uExcavation2'] ) {
}
   else ( $rand == 1 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uGatlingzaberfangweap=uGatlingzaberfangweap+$zoidmany,uExcavation2=uExcavation2-$excav1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/>You decide to keep it!
<?php
    }
    else ( $rand == 2 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uGatlingzaberfangweap=uGatlingzaberfangweap+$zoidmany2,uExcavation2=uExcavation2-$excav1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany2?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/>You decide to keep it!
<?php

        }
        elseif ( $excav2 = $user['uExcavation2'] ) {
}
   else ( $rand == 1 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/> But you have no excavation tool! You cannot excavate
<?php
     ?>Tools needed: 1 <img src="<?=$excav_image2?>"/>
<?php
    }
    else ( $rand == 2 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany2?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/> But you have no excavation tool! You cannot excavate
<?php
?>Tools needed: 1 <img src="<?=$excav_image2?>"/>
<?php

    }
            elseif ( $rand == 3 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uWeapon42=uWeapon42+$zoidmany,uAttackTurns=uAttackTurns+'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>You see something shiny in the distance, What is that you wonder?
<?php
        ?>You just found a fully working <?=$wp_42_nm?>!<img src="<?=$wp_42_image?>"/>
<?php
        ?>No need for excavation tools here, This bad boy runs!
<?php
    }
         elseif ( $fight2 > $defensetotal ) {
}
   else ( $rand == 4 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive3,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a group of <?=$wp_43_nm?>'s <img src="<?=$wp_43_image?>"/>.
 <?php
        ?>You managed to fend them off and scored a nice <?=$goldgive3?> gold!

<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight2?>

<?php
    }
    elseif ( $fight2 < $defensetotal ) {
}
   else ( $rand == 4 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$goldtake2,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a pack of <?=$wp_43_nm?>'s <img src="<?=$wp_43_image?>"/>.
<?php
        ?>Your defense couldn't hold up to their might! You loose <?=$goldtake2?> Gold!
<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight2?>

<?php
    }
             elseif ( $fight1 > $defensetotal ) {
}
   else ( $rand == 5 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive2,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a group of <?=$wp_32_nm?>'s <img src="<?=$wp_32_image?>"/>.
 <?php
        ?>You managed to fend them off and scored a nice <?=$goldgive2?> gold!

<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight1?>

<?php
    }
    elseif ( $fight1 < $defensetotal ) {
}
   else ( $rand == 5 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$goldtake1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a pack of <?=$wp_32_nm?>'s <img src="<?=$wp_32_image?>"/>.
<?php
        ?>Your defense couldn't hold up to their might! You loose <?=$goldtake1?> Gold!
<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight1?>

<?php
    }
    elseif ( $rand == 6 || $rand == 7 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$gold1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just got ambushed. You loose 50 gold!
<?php
    }
            elseif ( $rand == 8 || $rand == 9 || $rand == 10 || $rand == 11  ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>After a long hard journey you come up empty handed!
<?php
    }
    elseif ( $excav1 > $user['uExcavation2'] ) {
}
   else ( $rand == 12 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uEleshotbrhinosweap=uEleshotbrhinosweap+$zoidmany,uExcavation2=uExcavation2-$excav1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap6_nm?>. <img src="<?=$mz_weap6_image?>"/>You decide to keep it!
<?php
    }
    elseif ( $excav2 = $user['uExcavation2'] ) {
}
   else ( $rand == 12 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap6_nm?>. <img src="<?=$mz_weap6_image?>"/> But you have no excavation tool! You cannot excavate
<?php
     ?>Tools needed: 1 <img src="<?=$excav_image2?>"/>
<?php
    }
         elseif ( $fight3 > $defensetotal ) {
}
   else ( $rand == 13 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive4,uWeapon48=uWeapon48+$zoidmany,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a group of <?=$wp_48_nm?>'s <img src="<?=$wp_48_image?>"/>.
 <?php
        ?>You managed to fend them off and scored a nice <?=$goldgive4?> gold!

<?php
        ?>You also managed to take a fully working <?=$wp_48_nm?>, <img src="<?=$wp_48_image?>"/>.
 <?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight3?>

<?php
    }
    elseif ( $fight3 < $defensetotal ) {
}
   else ( $rand == 13 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$goldtake3,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a pack of <?=$wp_48_nm?>'s <img src="<?=$wp_48_image?>"/>.
<?php
        ?>Your defense couldn't hold up to their might! You loose <?=$goldtake3?> Gold!
<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight3?>

<?php
    }
        elseif ( $rand == 14 || $rand == 15 || $rand == 16 || $rand == 17  ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$goldgive1?> Gold. You decide to keep it!
<?php
    }
        elseif ( $rand == 18 || $rand == 19 || $rand == 20 || $rand == 21  ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uMiners=uMiners+$miner,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just found <?=$miner?> miners, your forcing them to join you!
<?php
    }
elseif ( $turns > $user['uAttackTurns'] ) {
}
   else ( $rand == 22 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-$turns,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just lost an additional <?=$turns?>. Better luck next time!
<?php
    }

require 'includes/footer.php';

?>

And BELOW IS THE WORKING CODE, THE ONLY PROBLEM I HAVE IS, WHEN THEY GET BELOW THE TURN LIMIT THEY CAN STILL USE IT CAUSING THEM TO GO INTO NEGATIVE TURNS.
    <?php

$ingame = "*";
require 'includes/header.php';
include 'includes/modzoideditables.php';
include 'includes/zoideditables.php';
include 'includes/offdefvalues.php';
$turns = 5;
$turns2 = 10;
$zoidmany = 1;
$zoidmany2 = 2;
$excav1 = 1;
$excav2 = 0;
$goldgive1 = 500;
$goldgive2 = 700;
$goldgive3 = 1000;
$goldgive4 = 1500;
$goldgive5 = 2000;
$fight1 = 20000;
$fight2 = 27000;
$fight3 = 31000;
$goldtake1 = 250;
$goldtake2 = 500;
$goldtake3 = 750;
$goldtake4 = 1000;
$miner = 5;
    $rand = rand( 1, 22 );
if ( $turns > $user['uAttackTurns'] ) {
        echo "You don't have enough turns.";
}
    $rand = rand( 1, 22 );
 if ( $excav1 > $user['uExcavation2'] ) {
}
   elseif ( $rand == 1 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uGatlingzaberfangweap=uGatlingzaberfangweap+$zoidmany,uExcavation2=uExcavation2-$excav1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/>You decide to keep it!
<?php
    }
    elseif ( $rand == 2 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uGatlingzaberfangweap=uGatlingzaberfangweap+$zoidmany2,uExcavation2=uExcavation2-$excav1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany2?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/>You decide to keep it!
<?php

        }
        if ( $excav2 = $user['uExcavation2'] ) {
}
   elseif ( $rand == 1 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/> But you have no excavation tool! You cannot excavate
<?php
     ?>Tools needed: 1 <img src="<?=$excav_image2?>"/>
<?php
    }
    elseif ( $rand == 2 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany2?> <?=$mz_weap3_nm?>. <img src="<?=$mz_weap3_image?>"/> But you have no excavation tool! You cannot excavate
<?php
?>Tools needed: 1 <img src="<?=$excav_image2?>"/>
<?php

    }
            if ( $rand == 3 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uWeapon42=uWeapon42+$zoidmany,uAttackTurns=uAttackTurns+'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>You see something shiny in the distance, What is that you wonder?
<?php
        ?>You just found a fully working <?=$wp_42_nm?>!<img src="<?=$wp_42_image?>"/>
<?php
        ?>No need for excavation tools here, This bad boy runs!
<?php
    }
         if ( $fight2 > $defensetotal ) {
}
   elseif ( $rand == 4 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive3,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a group of <?=$wp_43_nm?>'s <img src="<?=$wp_43_image?>"/>.
 <?php
        ?>You managed to fend them off and scored a nice <?=$goldgive3?> gold!

<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight2?>

<?php
    }
    if ( $fight2 < $defensetotal ) {
}
   elseif ( $rand == 4 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$goldtake2,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a pack of <?=$wp_43_nm?>'s <img src="<?=$wp_43_image?>"/>.
<?php
        ?>Your defense couldn't hold up to their might! You loose <?=$goldtake2?> Gold!
<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight2?>

<?php
    }
             if ( $fight1 > $defensetotal ) {
}
   elseif ( $rand == 5 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive2,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a group of <?=$wp_32_nm?>'s <img src="<?=$wp_32_image?>"/>.
 <?php
        ?>You managed to fend them off and scored a nice <?=$goldgive2?> gold!

<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight1?>

<?php
    }
    if ( $fight1 < $defensetotal ) {
}
   elseif ( $rand == 5 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$goldtake1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a pack of <?=$wp_32_nm?>'s <img src="<?=$wp_32_image?>"/>.
<?php
        ?>Your defense couldn't hold up to their might! You loose <?=$goldtake1?> Gold!
<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight1?>

<?php
    }
    if ( $rand == 6 || $rand == 7 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$gold1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just got ambushed. You loose 50 gold!
<?php
    }
            if ( $rand == 8 || $rand == 9 || $rand == 10 || $rand == 11  ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>After a long hard journey you come up empty handed!
<?php
    }
    if ( $excav1 > $user['uExcavation2'] ) {
}
   elseif ( $rand == 12 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uEleshotbrhinosweap=uEleshotbrhinosweap+$zoidmany,uExcavation2=uExcavation2-$excav1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap6_nm?>. <img src="<?=$mz_weap6_image?>"/>You decide to keep it!
<?php
    }
    if ( $excav2 = $user['uExcavation2'] ) {
}
   elseif ( $rand == 12 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$zoidmany?> <?=$mz_weap6_nm?>. <img src="<?=$mz_weap6_image?>"/> But you have no excavation tool! You cannot excavate
<?php
     ?>Tools needed: 1 <img src="<?=$excav_image2?>"/>
<?php
    }
         if ( $fight3 > $defensetotal ) {
}
   elseif ( $rand == 13 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive4,uWeapon48=uWeapon48+$zoidmany,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a group of <?=$wp_48_nm?>'s <img src="<?=$wp_48_image?>"/>.
 <?php
        ?>You managed to fend them off and scored a nice <?=$goldgive4?> gold!

<?php
        ?>You also managed to take a fully working <?=$wp_48_nm?>, <img src="<?=$wp_48_image?>"/>.
 <?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight3?>

<?php
    }
    if ( $fight3 < $defensetotal ) {
}
   elseif ( $rand == 13 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold-$goldtake3,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You were attacked by a pack of <?=$wp_48_nm?>'s <img src="<?=$wp_48_image?>"/>.
<?php
        ?>Your defense couldn't hold up to their might! You loose <?=$goldtake3?> Gold!
<?php
        ?>YOUR DEFENSE: <?=$defensetotal?>

<?php
        ?>THEIR ATTACK: <?=$fight3?>

<?php
    }
        if ( $rand == 14 || $rand == 15 || $rand == 16 || $rand == 17  ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET ugold=ugold+$goldgive1,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just stumbled across <?=$goldgive1?> Gold. You decide to keep it!
<?php
    }
        if ( $rand == 18 || $rand == 19 || $rand == 20 || $rand == 21  ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uMiners=uMiners+$miner,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just found <?=$miner?> miners, your forcing them to join you!
<?php
    }
if ( $turns > $user['uAttackTurns'] ) {
}
   elseif ( $rand == 22 ) {
        $rand_cash = rand( 1, 50 );
        $db->query( "UPDATE users SET uAttackTurns=uAttackTurns-$turns,uAttackTurns=uAttackTurns-'$turns' WHERE uID='" . $user['uID'] . "'" );

 ?>This Exploration costed you 5 Turns
<?php
        ?>You just lost an additional <?=$turns?>. Better luck next time!
<?php
    }

require 'includes/footer.php';

?>

A: That random shoud be inside, you can'do this
if (condition)
 {
 //code
 }
 //another code
elseif (condition)
 {
 //code
 }

so you should change your code here:
if ( $turns > $user['uAttackTurns'] ) {
        echo "You don't have enough turns.";
        $rand = rand( 1, 22 );
}
 elseif
 //code...

EDIT:
There is no condition after else, so
else(condition)
{
//code
}

will produce another error. Last else will be done if everything else failed.

A: The error is pretty concise.
"unexpected T_ELSEIF" - how else can I make this simpler? There is  an elseif that was not expected, should not be there, is in the wrong place...
You didn't give a line or code where it occurs, but I'm guessing it's this:
if ( $turns > $user['uAttackTurns'] ) {
        echo "You don't have enough turns.";
}
    $rand = rand( 1, 22 );
 elseif ( $excav1 > $user['uExcavation2'] ) {
}

So to do else, elseif, etc, you need to follow from one curly bracket to another..
if (something)
  {
    whatever
  }
elseif (something else)
 {
   whatever else
 }

Also, I don't see you actually using your $rand var inside the if/elseif, so is there some missing code? If you need it on each if/else, put it inside the elseif.

A: This is because you have the statement $rand = rand( 1, 22 ); in between your first 'if' and the first 'elseif'. The 'elseif' needs to directly follow an 'if' with no statements in between.

A: The users are getting more turns because you aren't doing anything that prevents them from doing so. Put the rest of your code in using else {} after the first if statement:
if( $turns > $user['uAttackTurns'] ) {
    echo "You don't have enough turns.";
}
else {

    /*** Carry on As Usual ***/
}

This will prevent any other code from running if $turns is greater than $user['uAttackTurns'].
Also, you don't have to redefine $rand = rand( 1, 22);. You declare it once above, and again after the first if statement.


text:
Q: Не получается как на макете. Нужно сделать прозрачным лого, а сами цифры оставить 100% На макете логотип имеет прозрачность -0.43. Ставлю opacity, шрифт также становится бледным.

body, h1, h2, h3, h4, p, a {
  margin: 0;
  font-size: 100%;
  font-weight: normal;
}

body {
 font-family: 'Roboto', serif;
 overflow-x: hidden;
}
a{
 text-decoration: none;
}
.numbers {
  background:  rgba(1, 1, 1, 0.4)  ;
  z-index: 2;
  height: 601px;
  text-align: center;
 }
.numbers h3 {
font-family: "Roboto Regular" sans-serif;
font-size: 36px;
text-transform: uppercase;
color: #fff;
}
.about {
font-weight: bold;
}

.num {
margin-top: 70px;
height: 450px;
background:  url(backlogo.png) no-repeat;

background-size: contain;
background-position: center;
z-index: 1;
opacity: 0.5;
color: #fff;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
font-family: "Roboto Regular" sans-serif;
text-transform: uppercase;
}

.num p   {
margin-left: 8rem;
font-size: 24px;
opacity: 1;

}

.num span {
font-size: 72px;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="style1.css" />
     <meta name="viewport" content="width=device-width, initial-scale=1" />
     <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
 <link href="http://allfont.ru/allfont.css?fonts=arial-narrow-bold" rel="stylesheet" type="text/css" />
 <title>Свила</title>

о нас в цифрах

2907
проведенных
 мероприятий

11
лет на рынке

7000
человек
крупнейшее мероприятие

A: Один из возможных вариантов решения Вашей проблемы: задаём фон не родительскому блоку, а псевдоэлементу (предварительно спозиционировав его абсолютно и растянув во весь размер .num):

.numbers {
  background:  rgba(1, 1, 1, 0.4)  ;
  z-index: 2;
  height: 601px;
  text-align: center;
 }
.numbers h3 {
font-family: "Roboto Regular" sans-serif;
font-size: 36px;
text-transform: uppercase;
color: #fff;
}
.about {
font-weight: bold;
}

.num {
margin-top: 70px;
height: 450px;
z-index: 1;
color: #fff;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
font-family: "Roboto Regular" sans-serif;
text-transform: uppercase;
position: relative;
}
.num > div {
  position: relative;
}
.num:before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url(https://www.sokolniki.com/content/images/0017386_0.jpeg) no-repeat;
  background-size: cover;
  background-position: center;
  border: 1px solid red;
  opacity: 0.5;
}

.num p   {
margin-left: 8rem;
font-size: 24px;
}

.num span {
font-size: 72px;
}

о нас в цифрах

2907
проведенных
 мероприятий

11
лет на рынке

7000
человек
крупнейшее мероприятие

A: Заменил шрифт так как не могу найти шрифт из примера

смотреть на весь экран

html,
body {
  margin: 0;
  padding: 0;
}

.items {
  text-align: center;
  color: #fff;
  height: 60vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.items>h2 {
  margin: 0;
}

.blocks {
  display: flex;
  justify-content: space-around;
}

.blocks p {
  font-size: 24px;
}

.blocks-item {
  text-align: center;
  width: 100%;
  position: relative;
  z-index: 1000;
}

h2 {
  font-size: 50px;
}

.section {
  width: 100%;
  height: 100vh;
  position: relative;
  background: rgba(0, 0, 0, 0.5);
}

.section img {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  opacity: 0.5;
}

О нас в цифрах

2907

Проведённых
мероприятий

11

Лет на рынке

7000

Человек
крупнейшее мероприятие


text:
Q: How to show only related objects in a django admin model In a django admin model with inlines other admin model I want to show only related objects.
simplified example:
class Business(models.Model):
    name = models.TextField()

class BusinessAddress(models.Model):
    business = models.ForeignKey(Business)
    address = models.TextField()

class Pos(models.Model):
    business = models.ForeignKey(Business)
    label = models.TextField()

class PosAddress(models.Model):
    pos = models.ForeignKey(Pos)
    address = models.ForeignKey(Address)

So I want to retrieve only the related addresses of the selected pos in PosAddress and not all the available addresses
class PosAddressAdmin(admin.ModelAdmin):
    model = PosAddress
    extra = 1

class PosAdmin(admin.ModelAdmin):
    model = Pos
    inlines = [PosAddressAdmin]

How is that possible, if it is possible?


text:
Q: Test unmounting with react-testing-library I am confused by when/how a queried element get updated. For example:
I have a button that counts up. And when it counts to 3, it disappears.
import React, { useState } from "react";

export default () => {
  const [count, setCount] = useState(0);

  return (

      {count < 3 && (
        <button onClick={() => setCount(count + 1)}>{count}</button>
      )}

  );
};

I'm testing it like so:
test("Counter counts up and disappears", () => {
  const { queryByText } = render(<App" />);

  const button = queryByText("0");
  expect(button.textContent).toEqual("0");

  fireEvent.click(button);
  expect(button.textContent).toEqual("1");

  fireEvent.click(button);
  expect(button.textContent).toEqual("2");

  fireEvent.click(button);
  expect(button).toBe(null);
});

The test failes with the following error:
expect(received).toBe(expected)

Expected value to be (using ===):
  null
Received:
  <button>2</button>

Why does the button element knows its text content has changed? We didn't need to run queryByText("1") and queryByText("2") after each click.
And why it doesn't know that the button has been unmounted after the last click? And we do need to do queryByText("3") if we want to check that it is indeed null.
Here's the code sandbox:
https://codesandbox.io/s/react-testing-library-demo-76zhi

A: I guess it's about how react-dom and jsdom(which used by testing too) works.
(Please correct me or let me know if guessing is unacceptable! I will remove this. )

*

*Button type return by queryByText is HtmlElment

*react or react-dom is just minimize the task for dom manipulation, eventually jsdom would still do the text changing and button removing works.

*Since the testing tool is using jsdom, I check the removeChild part of code, and believe they are following W3C specification. I assume in the level of dom manipulation, jsdom would works like browsers. Thus I simulated your code like this:

const btn = document.getElementById('btn');
const btnContainer = document.getElementById('btnContainer');

btn.textContent = '1';
console.log('btn after click 1: ' + btn);
btn.textContent = '2';
console.log('btn after click 2: ' + btn);
btnContainer.removeChild(btn);
console.log('btn after removed: '+  btn);

<button id='btn'>0<button>

*As you can see, after removing from div, the btn variable is still [object HTMLButtonElement]
Maybe It's similar to use splice to an array which contained a defined object, the initial obj still remains the same?

const obj = { 'a': 1};
const arr = [obj];
arr[0]['a'] = 2;
arr.splice(0, -1);
console.log(obj)

Therefore, I think it's more about how garbage collection works in javascript.
In addition, maybe not to reuse the query result, and always query again in this situation, the result will be more expectable.

P.S. I found there is a method call toBeInTheDocument!


text:
Q: ispell in emacs exits with error code 2 after upgrading emacs I recently upgraded my emacs to version 24.3.1 on ubuntu (I had a lower 24 version before). I first purged the old version and the installed the current version to get a clean update. Since, then cannot use ispell anymore.
First, I got an error message stating that there is not such function or program. I checked: ispell was installed. I then specified the path to ispell using
setq ispell-program-name.

Then doing so, I got an error message that permission is denied. So I changed permission (chmod aou+wrx) for the file. Now I get the following error message:
ispell.el exited with code 2.

This happens whether I evoked ispell-region or ispell-word.
I also installed ispell by hand on my home site-lisp and loaded that fiel, with the same result.
Any suggestions about the meaning of the code would be helpful.
Thanks! Stephan

A: You should not set the path to ispell.el -- instead the path should be to an executable program like aspell -- e.g.:
(setq-default ispell-program-name "/Users/HOME/.0.data/.0.emacs/elpa/bin/aspell")

You do not need to check to see whether ispell.el is installed because it automatically comes with a full version of Emacs.  Instead, you need to install something like aspell if you don't already have it installed. You also need to install the language dictionary used by aspell -- e.g., English dictionary.  Here is a link you may find helpful regarding installing aspell on Ubuntu:
http://packages.ubuntu.com/lucid/aspell
Think of ispell.el as a front-end, which has useful functions to operate a separately installed spelling program like aspell -- with a separately installed dictionary database (e.g., English).


text:
Q: Secret Santa generator with IF condition I´m new at this, trying to make in python a secret santa generator, but i want to make condition that some family members cant give to each other (Example : parents and own children | only gift other relatives)
I have some code and it does the random generation, but I can´t make the condition that I want.
Can someone help?
def Santa(names, draw):
  matches= []
  while names:
    giver = names.pop() #chooses giver and removes name
    receiver = random.choice(draw) #picks random to receive

    if giver != receiver:
      matches.append([giver, receiver]) #adds pair
      draw.remove(receiver) #removes person from receiving list
      if giver
    else:
      names.append(giver) #if names are the same, adds name back to list
  return matches

family1=['Carlos', 'Minda', 'Ana', 'Catarina']
family2=['Paulo','Alexandre','Luquinhas']
family3=['Ivone','Lucas','Susana','Pedro']
family4=['Tia Ângela','Mãezinha Avó']


text:
Q: Java Applet with External Jar Hi guys
I have an Applet in MyApplet.java file. It uses external .jar libraries and I have to get it work on a Web Browser.
1) I am a complete newbie in writing custom classpath, manifest ecc... which is the correct way to compile my .java file to get the .class?
2) Once i have the .class file, what i have to do in my webspace? where to put the jar files? what i have to write in my html page?

A step by step tutorial would be awesome

A: There are nice resources out there, for example "The Java Tutorial", which has a section on How to write Applets.
But you seem to need even more basic advise on compiling - so take a look at Getting Started, and later at Deployment. Then come back if you have more concrete problems.


text:
Q: Timed Pagination or Scrolling in Django I have a very simple Django webapp that tracks job status in a shop.  It works fine, but I'd like to add in a feature that automatically scrolls or changes pages, whichever is easier, every 30 seconds so that if there are more jobs than fit on one screen, it shows all the jobs on a time interval.  Is anyone aware of a method to do this with Django or javascript?
Much appreciated.

A: I developed a relatively simple solution for this after looking around the web.  Thought it might be helpful for someone down the line.
I used a little javascript script:
<script>

setInterval(function(){ location.reload() }, 600000);

$(document).ready(function scroll(){
  $("html, body").animate({ scrollTop: $('#start').offset().top }, 40000).delay(5000),
  $("html, body").animate({ scrollTop: $('#stop').offset().top }, 40000), scroll();
})
scroll();
</script>

I just put in the head html page, but you could load it in the static folder as well.  I just added two objects on the page, one at the top called 'start' and one called 'stop', i.e. I put an image at the top as follows:
<img src="{% static 'logo.png' %}" id="start">

It is simple but it works very well and just scrolls up and down all day.


text:
Q: send data from python to cordova app via Bluetooth Hello to All Developers,
I am facing problem to make communication channel between Python to cordova (Phonegap) App.
I have an python script that is sending data it is working only when I receive data by another python script via bluetooth.
But I couldn't any solution to receive data in cordova app.
This is python script.
import bluetooth

bd_addr = "01:23:45:67:89:AB"

port = 1

sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))

sock.send("hello!!")

sock.close()

I want to make an cordova script that will receive data in android phone.
It will be more appreciate if I got help from you side.
Thanks

A: Edit
If you want to use sockets to connect and transfer data you could try this plugin.
https://www.npmjs.com/package/cordova-plugin-networking-bluetooth
Installation:
cordova plugin add cordova-plugin

Example connection:
var uuid = '94f39d29-7d6d-437d-973b-fba39e49d4ee';

networking.bluetooth.connect(device.address, uuid, function (socketId) {
    // Profile implementation here.
}, function (errorMessage) {
    console.log('Connection failed: ' + errorMessage);
});

Example receiving data from a socket:
networking.bluetooth.onReceive.addListener(function (receiveInfo) {
      if (receiveInfo.socketId !== socketId) {
          return;
      }

      // receiveInfo.data is an ArrayBuffer.
});

Original
I have used this plugin before:
https://github.com/don/BluetoothSerial
Installation:
cordova plugin add cordova-plugin-bluetooth-serial

Your phone must initiate the connection though, then you can use the subscribe method to listen for data. This data is then passed to the callback function.
In your data sent from the python script you will need to include a delimiter such as a new line so that the plugin knows when it has finished reading the data. Usage is like this:
function connectSuccess(){

    //The first argument is the delimiter to stop reading data at

    bluetoothSerial.subscribe('\n', function (data) {
        console.log(data);
    }, failure);

}

function failure(e){

    console.log('Subscribe failure: ' + e);

}

function connectFailure(e){

    console.log('Connect failure: ' + e);

}

bluetoothSerial.connect(macAddress_or_uuid, connectSuccess, connectFailure);


text:
Q: Comma use: "from the ground up" or "from the ground, up"? Is it appropriate to use a comma in the expression: ..."from the ground, up" or should there be no comma?
Without a comma, the expression seems strange to me.  I've been criticized by a non-native English speaker for writing the expression in this way.  Since he's put a lot more effort into learning the "rules" of English, I have a shadow of self-doubt.  However, I have a feeling that this is one of the many (many) cases where English proves that rules were meant to be broken - or at the very least, that there are more rules than one can easily learn.

A: No comma.
http://thesaurus.com/browse/from+scratch

From the very beginning
Synonyms:     from square one, from the ground up, from the top,
  initially

A: There is no rule to be broken here. Your friend is wrong and you are right, unless we're talking about some special case here, but since you didn't provide any further info, I'll assume we aren't.
The comma in the phrase would normally be very displaced. To explain further:
A) If you want the phrase, then no comma!

The fire burnt the house from the ground up.

B) If they are two different sentences:

The plane took off from the ground, up.

The case with the comma, although grammatical, still sounds a bit strange.

A: The comma is unnecessary when supplying a direction.

from the top down
from Route 23 north
from the third one over
from Wednesday onward

One would include the comma only to set the direction apart for emphasis or contrast.

For the entire film, Zoolander only turns right. We expect the same in the climactic scene, as he strides out onto the platform. Then he turns, left.

So as you can imagine, the comma would be especially distracting when the direction is metaphorical.

The company is organized from the ground up.

There is a possibility of mis-reading "ground up" as in the results of something put through a grinder (e.g. 2g pepper, ground up or his dissertation committee really ground him up), but I think the chance is very slim here.

A: I'd only include a comma if trying to make clear that this was not the conventional phrase "from the ground up". Like, "Trash was littered across the ground, up to the doorway, and inside the house."
But, "I built this company from the ground up", there should be no common.


text:
Q: TFS Work Item<->Build association best practices We recently adopted the concept of feature branches in one of our bigger projects, to segregate work on different aspects of the product that can be completed independently of each other.
For each so-called feature, we are creating the following:

*

*a branch from 'main', aptly named after what the feature is supposed to be

*a new team in the project portal, containing the people that will work on the feature

*a build definition to validate check-ins against the source on the branch

The main point I would like to see discussed here is about the build definition. Currently, each one of them is set to gated checkins.
The question then, is: what is the best practice on associating work items to a build?
In our case, these feature branches are supposed to be disposable: we would like to be able to delete these builds/branches/teams later on when the feature is complete, but still be able to track them throughout the product lifecycle.
If I associate work items with these temporary builds, I'll lose tracking capability later on when the feature implementation ends. At the same time, I just found out that gated checkins always associate work items, regardless of what is configured in the build definition.
Would it be feasible to disable work item integration with the feature branches (in this case also converting them from gated to continuous integration) and enable it in the main build, so that these features can be tracked in the main product line? Or maybe this should be only enabled for Release build definitions, so that we can find out what was integrated on a certain release? For those of you who follow the sprint/feature concept, how do you handle this situation? Do you also have a build for each branch?
Update:
I just found something similar (but not exactly like what I wanted) in this question. The answer there lead me to a plugin that automatically associates work items on merge checkins. This should offer great traceability on it's own, so I think I'll give it a shot.
Would still like to hear what your thoughts are in regards to the builds in this scenario.

A: You're approaching this wrong IMO.  You shouldn't be worrying about associating Builds and WI's, but rather associating Changesets and WI's.  When your developers check-in changes in the feature branch you should ensure that they are linking them to the relevant WI(s).  You can even enforce this via a Check-In Policy.
Now if you ever want to inspect that feature in the future to see all the changes associated with it, you can by inspecting the Feature WI, and looking at all linked Changesets.  Even if you delete the branch all the Changesets are still available.


text:
Q: How do I set value of nested object to key of current object? This array has the key to substitute with nested key of 'name'

const arr = ['status', 'user', ...]  <-- This array contains key to be replaced with name

This is what my current response object is

[
  {
    "id": 11,
    "location": "Mumbai",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Rakesh"
     }
  }
]

How do I modify the above array of objects to this below

[
  {
    "id": 11,
    "location": "Mumbai",
    "status": "NEW",
    "user": "Rakesh"
  }
]

A: can try below code

const keys = ['status', 'user']
let arr = [
  {
    "id": 11,
    "location": "Mumbai",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Rakesh"
     }
  }
]

arr.map(a => keys.forEach(k => {
   if(a[k] && a[k].name) a[k] = a[k].name
}));

console.log(arr);

A: I'd try this one:

const results = [
  {
    "id": 11,
    "location": "Mumbai",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Rakesh"
    }
  }, {
    "id": 12,
    "location": "Helsinki",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Samuli"
    }
  }
];

const flattenObject = ([key, value]) => ((typeof value === 'object') ? {[key] : value[Object.keys(value)[0]]} : {[key]: value});

const reduceToSingleObject = (acc, b) => ({...acc, ...b});

const actualResults = results.map((result) => Object.entries(result).map(flattenObject).reduce(reduceToSingleObject));

console.log(actualResults);

Explanation:

*

*flattenObject is a function to flatten structure of object inside object. This only takes the first prop (without knowing the name of the key). If you, for some reason, would need to flatten several key-values, then it'd need whole different kind of helper function to sort that out.

*reduceToSingleObject is a function to put all the key-value pairs into a single object. This could have been done already in flattenObject function, but for the clarity, I separated it to a normal map - reduce pattern.

*actualResults is the outcome where we go through all the entries of your original results.


text:
Q: Installing an updated byobu on Debian The Debian package for byobu still points to version 5.112-1 from 2016-09-16 while there were several new versions released since then.
Is there any chance that the Debian package will get updated any time soon? And what would be the best way to get a more recent version installed in the meantime (if possible at all)?

A: Yes, indeed!  I happen to be the author and maintainer of Byobu, and I've recently been approved as a Debian Maintainer, which enables me to upload to Debian now.


text:
Q: Between clause not giving desired results in query I need to return results from a mssql stored proc on the basis of datetime2. There's a employee table with punch in and punch out time. I need to return results all the data from an employee on the basis of start time and end time. My query is some what like
Select *
from   employee
where  empid ='123'
and     punchin  between 'starttime' and 'endtime'
and     punchout between 'starttime' and 'endtime'

this query is not returning expected results. Am I doing anything wrong here, also in between punch in or punch out column one can be empty, in that case result will be returned on the basis of one column.

A: Based on assumption:
Table Structure:
CREATE TABLE employee (
  empid VARCHAR(20) not null,
  punchin datetime2(7),
  punchout datetime2(7)
)

Sample data:
INSERT INTO employee VALUES
('1', null, '2021-03-28 10:50:00'),
('2', '2021-03-28 05:00:00', '2021-03-28 9:00:00'),
('3', '2021-02-28 05:00:00', null)

Procedure:
CREATE PROCEDURE getData
@empid VARCHAR(20),
@startTime datetime2(7),
@endTime datetime2(7)
AS
BEGIN
  SELECT *
  FROM employee
  WHERE empid = @empid
    AND (punchin IS NULL OR (punchin IS NOT NULL AND punchin >= @startTime))
    AND (punchout IS NULL OR (punchout IS NOT NULL AND punchout <= @endTime))
END

Usage:
EXEC getData '1', '2021-03-27 10:50:00', '2021-03-27 10:50:00'

See, if it works.
Note: Without proper structure or data, it is hard to do things based on assumption.


text:
Q: ¿Como agregar librerías a un proyecto java? Lo que quiero hacer es añadir librerias jar  al proyecto y no añadirlo como ruta , en estos momentos lo añado de esta forma :
Librerías ->Add JAR/Folder y selecciono los que necesito , funciona pero como esas librerías están en mi USB cuando lo desconecto me muestra error en mi proyecto indicándome que debo añadir las librerías
Cuando voy a  las propiedades del proyecto -> Librerias  me salen las librerías que uso pero con la ruta de mi USB.
Esta es una captura cuando el USB esta conectado :

Aquí una captura cuando desconecto el USB :

¿Alguien me puede decir como añadir librerías de forma correcta?
La idea final es convertir el proyecto en un ejecutable y tengo la duda de que si lo convierto usando rutas el proyecto .exe no ejecute correctamente.

A: Hay la opción de crear una carpeta libs en la raíz del proyecto y usar la opción Add JAR/Folder, para agregarlas desde ahí. Esto permite que al momento de crear el ejecutable todas las librerías se empaquetan dentro del .war o .jar. Y ese archivo es un ejecutable que se puede correr en cualquier plataforma que tenga el JRE instalado.
NOTA: Recuerda que el ejecutable es válido, siempre y cuando ese (.jar o .war) se haya generado de una compilación exitosa.

A: Deberias copiar las librerias en tu proyecto. Normalmente en una carpeta "lib" y luego realizar los pasos de Add Jar con la libreria del workspace.
Por otra parte una mejora seria usar algun sistema com "maven" donde referencies las librerias en el fichero POM y estas se descarguen automaticamente desde un repositorio central


text:
Q: Get the rudder rotation angle of the robot's compass there is an electronic compass with angles of 1-360 degrees (or 0-359, whatever)
https://i.stack.imgur.com/Q7RmH.jpg
there are variables

*

*Yaw - compass readings degrees

*HDG - established direction rudder degrees

*rudder - the degrees to turn the steering wheel (need to get)

variables to check
HDG:20
Yaw:340
=need to get rudder=40
HDG:50
Yaw:90
=need to get rudder=-40

What is the formula to get the angle by which to rotate?
the problem is to find the shortest turn in the right direction..
it seems simple, but it broke my mind
something like

if (Yaw<=180) {
rudder=set HDG-Yaw;
} else {
rudder=360-Yaw+setHDG;
}

but here is an error if setHDG is 350 and Yaw=20 ... gives 330 and it should be 30

A: if (setHDG>=Yaw)
      rudder=360-(360-setHDG+Yaw);
else
      rudder=setHDG-Yaw;


text:
Q: cronjob is running 2x in a hour instead 1x I have written a small backup script for my vserver and added its execution to my /etc/crontab
25 * * * * root /etc/cron.daily/backup.sh

This is the entry (yeah it is still located in the wrong folder right now :) )
But when I check my log I see that the script is executed a min of 2 times a hour. Which is not a problem but I would like to know why this is happening.
Backup done on Fr 8. Jun 02:59:00 UTC 2012
Backup done on Fr 8. Jun 03:28:20 UTC 2012
Backup done on Fr 8. Jun 03:58:44 UTC 2012
Backup done on Fr 8. Jun 04:39:44 UTC 2012
Backup done on Fr 8. Jun 05:06:43 UTC 2012
Backup done on Fr 8. Jun 05:32:34 UTC 2012
Backup done on Fr 8. Jun 05:59:06 UTC 2012
Backup done on Fr 8. Jun 06:28:58 UTC 2012
Backup done on Fr 8. Jun 06:59:07 UTC 2012

A: Scripts in /etc/cron.daily are automatically run daily, scripts in /etc/cron.hourly hourly. There is no need to put a script into one of the /etc/cron.{hourly|daily|weekly|monthly} AND calling it from /etc/crontab. Putting your script into /etc/cron.hourly and calling it from /etc/crontab would run the script twice.
I suggest you also add a Backup started log message. That way you will see when it gets called any you can eventually correlate that information with what you have configured.


text:
Q: Collecting data from Ebay using Xpath and HtmlAgiltyPack Hey I'm trying to get the text value of the following html element Ebay Website + Dev Tool
The XPath expression for the price seems to work fine and I get the price of the product from the site, but my xPath expression for the name just doesnt work. This is my first time working with XPath, can anyone please help me with the Xpath expression for the product name?
Here is a picture of my Code
Code


text:
Q: Wrong output of mahout PFPGrowth algorithm? I'm using latest trunk version of mahout's PFP Growth implementation on top of a hadoop cluster to determine frequent patterns in movielens dataset.
In a previous step I converted the dataset to a list of transactions as the pfp growth algorithm needs that input format.
However, the output I get is unexpected
For example for item 1017 the only frequent pattern is

1017    ([100,1017, 50])

I would also expect a pattern like ([1017], X) with X >= 50 in that line.
I also testset an example input

1,2,3
1,2,3
1,3

and the output I get is

1  ([1, 3],3), ([1],3), ([1, 3, 2],2)
2  ([1, 3, 2],2)
3  ([1, 3],3), ([1, 3, 2],2)

There are missing patterns like ([1,2],2)
What is wrong?

A: The reason is that the FP Algorithm does not output subsets of a frequent pattern if its support is not greater. It's described here:
http://www.searchworkings.org/forum/-/message_boards/view_message/396093
I need to rewrite the code for my use.

A: I read the paper and the code and it seems the PFP algorithm is not correct at all. I am wondering why nobody hasn't realized it.
It is so obvious if you already know about FP-Growth and just take a couple hours to read this paper and the code.


text:
Q: Define $g(x)=xf(x)$. If $f$ is continuous at $0$, then prove that $g$ is differentiable at $0$.
Given $f\colon \mathbb{R} \rightarrow \mathbb{R}$ and define $g\colon\mathbb{R} \rightarrow \mathbb{R}$ by $g(x)=xf(x)$. If $f$ is continuous at $0$, then prove that $g$ is differentiable at $0$ with $g'(0)=f(0)$.

Here's my attempt:
We know that if $f(x)$ is continuous at $0$, then $g(x)$ is continuous at $0$, because multiplication of $x$ and $f(x)$ again a continuous function. It follows that:
\begin{align}
g(0)=0
\end{align}
Also, because we know that $f$ is continuous at $x=0$:
\begin{align}
\lim_{x\to\ 0} f(x)=f(0)
\\ \lim_{x\to\ 0} \frac{f(x)-f(0)}{x-0}(x-0) \end{align}
That means $f$ also differentiable, so by knowing $x$ and $f(x)$ are differentiable we can say $g(x)$ is also differentiable at $x=0$. If we take the derivative at the definition of the function we get
\begin{align}
g'(0)=f(0)
\end{align}
Is it true logic? Or does it make sense? Thanks for helping.

A: No, in the middle of your argument you conclude that $f$ is differentiable at $x=0$, but $f$ is only assumed to be continuous at $x=0$.
Hint.
Study the quotient
$$
\frac{g(x)-g(0)}{x-0}=\frac{xf(x)}{x}
$$
and use the continuity of $f$ at $x=0$.

A: First, you don't need a complicated argument regarding continuity of $g$ to conclude that $g(0)=0$, you can simply substitute
$$g(0) = 0 \cdot f(0) = 0
$$
But the main problem with your proof is that in order to determine whether $g'(0)$ exists, you must write out the difference quotient $\frac{g(x)-g(0)}{x-0}$ and simplify it and try to find its limit as $x \to 0$. I do not see anywhere in your solution that you have written out the different quotient.


text:
Q: Apache Rewrite doesn't work to turn any domain name into a .com domain from a .co.uk one I am using the following rule to turn any domain name into a .com domain from a .co.uk one. Why doesn't this work? Do people have a better way of doing this?
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_HOST} ^(.*).co.uk(.*)$ [NC]
    RewriteRule $1.com$2 [R=301,L]
</IfModule>

A: Your rewrite rules's syntax is wrong. This is the code that should work for you:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(.+?)\.co\.uk$ [NC]
RewriteRule ^ http://%1.com%{REQUEST_URI} [R=302,L]

Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.


text:
Q: How to establish a SecIdentityRef in an iPhone keychain ? (Without a .p12) How do you create a SecIdentityRef in an iPhone keychain if
1) you already have the private key in the keychain and
2) you have just received the certificate from a CA?
SecPKCS12Import does not help in this case unless there is an API to create a .p12 from a private key and a certificate.
SecIdentityCreateWithCertificate would be the answer on the Mac but it does not exist on the iPhone.
Is it possible using SecItemAdd ?
http://developer.apple.com/library/ios/#documentation/Security/Reference/keychainservices/Reference/reference.html
many thanks, Andrew

A: OK, to answer my own question:
On iOS the keychain will automatically bound the certificate to the private key. That means you only need to:

*

*Generate the key pair

*Get a certificate that matches the private key

*Insert the certificate into the keychain.

After this you should be able to get a SecIdentityRef for the certificate / private key.
IMPORTANT:
SecItemAdd function allows you to insert the certificate data directly (NSData of the DER representation). This way you will be able to get a valid certificate reference, but not an identity ref.
The right way to insert the certificate is to first use the SecCertificateCreateWithData function over the DER bytes of the certificate. This will return a SecCertificateRef object which then should be used to persist the certificate into the keychain using the SecItemAdd function.
I hope this will make someone's life easier ;-)
Regards,
Pece


text: Q: How to direct Google Chrome Rich Notifications to different monitor/screen? I'm using Windows 7 at work with two monitors. I'd like to have my notifications appear on the screen that's not assigned as my desktop. Is there any way to do this?


text:
Q: Django Postgresql Configuration ERROR : ImproperlyConfigured: settings.DATABASES A newbie to Django!!
In the process of switching from sqlite3 to postgresql,
I tried to follow the steps in the link.

http://www.marinamele.com/taskbuster-django-tutorial/install-and-configure-posgresql-for-django

settings.py (added Database settings as follows)
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': get_env_variable('DATABASE_NAME'),
        'USER': get_env_variable('DATABASE_USER'),
        'PASSWORD': get_env_variable('DATABASE_PASSWORD'),
        'HOST': '',
        'PORT': '',
    }
}
def get_env_variable(var_name):
    try:
        return os.environ[var_name]
    except KeyError:
        error_msg = "Set the %s environment variable" % var_name
        raise ImproperlyConfigured(error_msg)

In Django shell

>>>from trydjango import settings
>>>settings.DATABASES
{'default': {'ENGINE': 'django.db.backends.dummy', 'AUTOCOMMIT': True,
'ATOMIC_REQUESTS': False, 'NAME': '', 'CONN_MAX_AGE': 0, 'TIME_ZONE':    None,
'PORT': '', 'HOST': '', 'USER': '',
'TEST': {'COLLATION': None, 'CHARSET': None, 'NAME': None, 'MIRROR': None},
'PASSWORD': '', 'OPTIONS': {}}}

ERROR :

django.core.exceptions.ImproperlyConfigured:settings.DATABASES is improperly configured.
Please supply the ENGINE value. Check settings documentation
for more details.

Please help me out to solve this.

A: Answering instead of commenting due to rep.
Your settings.py shows this: 'ENGINE': 'django.db.backends.postgresql_psycopg2'
But your shell output shows: 'ENGINE': 'django.db.backends.dummy'
Are you sure you have everything configured correctly?

A: There was a mistake in settings.DATABASES configurations
settings.py (The database settings now)
DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.postgresql_psycopg2',
         'NAME': 'myproject',
         'USER': 'myprojectuser',
         'PASSWORD': 'password',
         'HOST': 'localhost',
         'PORT': '',
    }
}

and there were some mistakes in database configuration with $DATABASE_URL
which have been corrected as
#Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

then applying migrations using
python manage.py makemigrations
python manage.py migrate

solved the issue.
Now the DATABASE configuration in Django shell
>>> from trydjango.settings import DATABASES
>>> DATABASES
{'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2',
'AUTOCOMMIT': True, 'ATOMIC_REQUESTS': False, 'NAME': 'myproject',
'CONN_MAX_AGE': 0, 'TIME_ZONE': None, 'OPTIONS': {}, 'HOST': 'localhost',
'USER': 'myprojectuser', 'TEST': {'COLLATION': None, 'CHARSET': None,
'NAME': None, 'MIRROR': None}, 'PASSWORD': 'password', 'PORT': ''}}

Done


text:
Q: Does raising smithing over 100 do anything? Semi-related:
Is it possible to boost skills beyond 100 points?
I bring this up because I just found the http://elderscrolls.wikia.com/wiki/Notched_Pickaxe.
I did test this myself, and I didn't seem to see any difference in improving my armor.  Also note that the wikia page for the pickaxe specifically states that it can't be improved over 100.
Just want to verify with you guys, thanks!
EDIT
Thanks for the quick answers.  Not only is it possible, you can disenchant the Notched Pickaxe and get 10 extra smithing points by enchanting it onto 2 weapons we can be dual wielded.

A: Yes, smithing over 100 has an affect on upgrading.  In this answer I raised smithing to 130 via two items.  That allowed me to increase the armor rating from 528 (@100 smithing) to 610 (@130 smithing).

A: Raising smithing above an effective value of 100 using items or potions does increase how much you can upgrade your items. Although there is no higher category than Legendary, you can still increase the numerical bonus.
You can test this by upgrading an item to Legendary without any gear or potions, then equipping items of +Smithing and drinking a potion, and upgrading the item on the workbench or grindstone (quickly, as the potion time limit does run down while you're smithing). You'll be able to upgrade a Legendary item even further.

A: The armor cap is 569 with 4 pieces of armor. And it is increased by 25 for each piece of armor you remove since each armor has a hidden 25 point bonus and it of course is lowered if you have a mask on. So any more then 569 is pointless plain and simple. In that sense 100 smithing isn't really needed if you've already reached 569 with 4 pieces of armor.


text:
Q: Is there a way of rendering LaTeX equations in Crystal Reports? I'm developing a report in Crystal Reports and need to render some math formulas and equations in it. The formulas and equations are stored in a SQL Server database in plain text (using LaTeX markup).
Getting them to render in HTML is not a problem, because I'm using MathJax to do the work at browser level (in either HTML/CSS or MathML).
The real problem is: how can I get these equations rendered in the report? I've searched throught the web and found nothing about it. Doing some more search at the Crystal interface, the only thing I've found is inserting the (obsolete) "Microsoft Equation Editor" as a OLE object in the report, but neither this worked.
So, how render these LaTeX math equations in this Crystal report? Is there some (obscure) component/plugin that does the job? If not, is there a better manner of doing this? Someone already got and resolved a similar use-case?
OBS 1: I must have this report generated in PDF because of already validated standards in use at my job.
OBS 2: The app which will generate this report is a ASP.NET MVC 3 web app, with a SQL Server 2008 database (using NHibernate).

A: You'll need to create a user-function library (UFL) to do this.  Pass the LaTeX representation of the formula to the UFL, generate an image representation of the formula, return the image's URL.
To use the path, insert a 'picture', then reference the UFL's function in the 'graphic location' property:
//Insert | Picture...; graphic location conditional formula
latex({table.latex_field})

A: I've found a workaround that is at the same time elegant and not relies on extending the Crystal Reports using C.
I've found this small and simple "latex equation renderer": mimeTeX. Using it, I'm able to render latex equations into GIF images (as a CGI application). With that, I created a phantom byte array field in the datatable where the report is getting data.
Here is what I've done:

*

*Recover the latex equation markup from my real database;

*Query mimeTeX using this markup and mimeTeX returns a gif image;

*Take this image and convert it to png format (Crystal surprisingly do not support GIF files);

*Finally put this PNG image (its bytes) in the phantom field created in the datatable used by the report;

*Now you can use this field in the report! The images for each record (equation) are generated and displayed without problems!

The only drawback I've found until now using this approach is that all the images are streched to the same size of the field placeholder. If the images have sizes that varies much, some will be displayed pixelated and others will become "squashed". But I'm looking forward how to resolve this issue!
--- Edit ---
Solved the "squashed images" problem. I resize the images in code maintaining their aspect ratio and "pasting" them in a fixed size image. Now all the images get the same size and doesn't get squashed!
Here is the code for the resizing:
MemoryStream ResizeImage(Stream OriginalFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
    int finalWidth = NewWidth;
    int finalHeight = MaxHeight;

    System.Drawing.Image FullsizeImage = System.Drawing.Image.FromStream(OriginalFile);

    // Prevent using images internal thumbnail
    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
    FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

    if (OnlyResizeIfWider)
    {
        if (FullsizeImage.Width <= NewWidth)
        {
            NewWidth = FullsizeImage.Width;
        }
    }

    int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
    if (NewHeight > MaxHeight)
    {
        // Resize with height instead
        NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
        NewHeight = MaxHeight;
    }

    System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

    // Clear handle to original file so that we can overwrite it if necessary
    FullsizeImage.Dispose();

    MemoryStream bmpStream = new MemoryStream();

    // Put in a new image of A x B pixels to evict distortion
    using (var bitmap = new Bitmap(finalWidth, finalHeight))
    {
        using (var canvas = Graphics.FromImage(bitmap))
        {
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
            canvas.Clear(Color.White);
            canvas.DrawImage(NewImage, 0, 0);
            canvas.Save();
        }

        bitmap.Save(bmpStream, ImageFormat.Bmp);
    }

    return bmpStream;
}


text:
Q: Android 4.0 Face Recognition Intent? Android 4.0 now features Face Recognition to unlock the phone. Is this functionality available as an INTENT that other applications can also use for Identification?
Note: I'm not talking about the Face Detection that is supported in the API.
Thanks

A: It looks like the new face detection stuff was built into the Camera stack ( Perhaps an oversignt? ) and can be found at Camera.Face -- it appears you start it with Camera.startFaceDetection() after Setting the listener
I have not done more than look around the API docs, so I don't know if this is all the peices to the puzzle you need, but it should get you started on the right direction.

A: I would try
face2.equals(face2);


text:
Q: Skip irelevant text from some of bars in plotly bar chart I create a simple plotly bar chart but inside the first columns I get a weird text that I need to delete.
library(plotly)
sum2<-structure(list(month = structure(c(1451606400, 1454284800, 1456790400,
1459468800, 1462060800, 1464739200, 1467331200, 1470009600, 1472688000,
1475280000), tzone = "UTC", class = c("POSIXct", "POSIXt")),
    Monthly = c(14236.895, 4519.892, 55691.009, 28295.345, 23648.287,
    34595.1276, 33946.393, 27909.4685, 81777.3508, 31453.393)), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))

fig <- plot_ly(sum2, x = ~month, y = ~Monthly, type = 'bar', text = text,
               marker = list(color = 'rgb(158,202,225)',
                             line = list(color = 'rgb(8,48,107)',
                                         width = 1.5))
)
fig <- fig %>% layout( width=1800,height=600
)

fig

A: Not sure what you were doing with text = text but just remove that line and it looks fine.
plot_ly(
  sum2,
  x = ~ month,
  y = ~ Monthly,
  type = 'bar',
  # text = text,
  marker = list(
    color = 'rgb(158,202,225)',
    line = list(color = 'rgb(8,48,107)',
                width = 1.5)
  )
)

This happens because text is referring to the function graphics::text() and when called without parentheses it just gives the report of that object with that name. Try just running text at the console (without parentheses) and you'll see what was getting passed as labels to your plot.
text
#> function (x, ...)
#> UseMethod("text")
#> <bytecode: 0x0000000013994f20>
#> <environment: namespace:graphics>

Created on 2022-02-07 by the reprex package (v2.0.1)


text:
Q: System.Windows.Controls.PrintDialog is not working I'm trying to print some user control in wpf.
It does work on my computer, but on another computer it doesn't.
My computer is windows 10, the other computer is windows 7, both have latest framework update.
The application is closing before it gets to
if(printDialog.ShowDialog() == true)

This is the code:
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == true)
    printDialog.PrintVisual(border, "Treatment Form");

What may be the problem?


text:
Q: Optional(not random) argument in URL patterns How can I pass optional argument in url patterns(not random)?
/new/
/new/save-and-add-new/
url(
    regex=r'^~new/[save-and-add-new]/$',
    view=views.BudgetCreateView.as_view(),
    name='create'
),

I need to use this in:
def get_success_url(self):
   if save_and_add_new_argument_in_url:
       return HttpResponseRedirect(reverse('item:new'))
   return HttpResponseRedirect(reverse('item:list'))

A: url(
regex=r'^~new/(?P<param>\w+)/$',
view=views.BudgetCreateView.as_view(),
name='create'
),
url(
regex=r'^~new/$',
view=views.BudgetCreateView.as_view(),
name='create'
),

Then
def get_success_url(self, param=None):
   if param is not None:
       return HttpResponseRedirect(reverse('item:new'))
   return HttpResponseRedirect(reverse('item:list'))


text:
Q: Invalid arithmetic operator while loop using output from aws cli commands We patch and reboot a large number of Windows instances via AWS SSM commands currently but there is an issue where the SSM agent doesn't always check in. My thought process was to speed things up I can run a while loop on each of our patch groups that pulls the uptime of each instance in the group. Once all instances had been up for say 2 minutes the next group will be rebooted. I can't seem to get past a simple issue with how to properly create a while loop to accomplish this though.
When running the below commands as a bash script I'm getting an error that mentions I'm trying to use an  "invalid arithmetic operator" in the loop. I have tested by outputting the value of $upTime and it was '18'.
This seems like one of those small mess ups that I am just wasting way too much time on and someone will be able to quickly point out what I am doing wrong. If the output of $upTime is a number I assumed the less than in the loop would function. If I just hard set it to 18 it loops properly which makes me think it must be some weird formatting issue from the SSM command but that should be plaintext and from my tests there is not white space coming through.
#!/bin/bash

aws ec2 reboot-instances --instance-ids `aws ec2 describe-instances --filters "Name=tag:RebootGroup,Values=01" --query 'Reservations[].Instances[].InstanceId' --output text`

sleep 30

upTime=1

while [[ $upTime -le 120 ]]
do

ssmID=$(aws ssm send-command --document-name "AWS-RunPowerShellScript" --document-version "1" --targets '[{"Key":"tag:RebootGroup","Values":["01"]}]' --parameters '{"commands":["$wmi = Get-WmiObject -Class Win32_OperatingSystem ","$uptimeSeconds = ($wmi.ConvertToDateTime($wmi.LocalDateTime)-$wmi.ConvertToDateTime($wmi.LastBootUpTime) | select-object -expandproperty \"TotalSeconds\")","[int]$uptimeSeconds"],"workingDirectory":[""],"executionTimeout":["3600"]}' --timeout-seconds 600 --max-concurrency "50" --max-errors "0" --region us-west-2 --output text --query "Command.CommandId")

echo "Value of ssmID = $ssmID"

echo "Value of upTime before sleep = $upTime"

sleep 15

upTime=$(aws ssm list-command-invocations --command-id "$ssmID" --details --query "CommandInvocations[].CommandPlugins[].{Output:Output}" --output text)

echo "Value of upTime after command invocation = $upTime"

echo "Waiting for instance uptime of 2 minutes before continuing"
done

A: I bet you have a stray carriage return in there:
$ upTime=$'42\r'
$ [[ $upTime -le 120 ]] && echo y || echo n
")syntax error: invalid arithmetic operator (error token is "
n

And because of the error, [[ returns non-zero and the while loop ends too soon.
Try this:
printf "Value of upTime after command invocation = %q\n" "$upTime"

If I'm right, you can remove the CR with a parameter expansion:
upTime=${upTime%$'\r'}

or with sed
upTime=$(aws ... | sed 's/\r$//')